context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
//------------------------------------------------------------------------------
// <copyright file="DMLibTestMethodSet.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace DMLibTestCodeGen
{
using System;
using System.Collections.Generic;
public enum DMLibTestMethodSet
{
AllValidDirection,
Cloud2Cloud,
AllAsync,
AllSync,
AllServiceSideSync,
CloudSource,
CloudBlobSource,
CloudFileSource,
LocalSource,
CloudDest,
CloudBlobDest,
CloudFileDest,
LocalDest,
DirAllValidDirection,
DirCloud2Cloud,
DirAllAsync,
DirAllSync,
DirAllServiceSideSync,
DirCloudSource,
DirCloudBlobSource,
DirCloudFileSource,
DirLocalSource,
DirCloudDest,
DirCloudBlobDest,
DirCloudFileDest,
DirLocalDest,
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class DMLibTestMethodSetAttribute : MultiDirectionTestMethodSetAttribute
{
public static DMLibTestMethodSetAttribute AllValidDirectionSet;
public static DMLibTestMethodSetAttribute DirAllValidDirectionSet;
static DMLibTestMethodSetAttribute()
{
// All valid directions
AllValidDirectionSet = new DMLibTestMethodSetAttribute();
// Sync copy
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Local, DMLibDataType.Cloud));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Stream, DMLibDataType.Cloud));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.Local));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.Stream));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudFile, DMLibDataType.Cloud));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.CloudFile));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudBlob));
// Async copy
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.URI, DMLibDataType.Cloud, DMLibCopyMethod.ServiceSideAsyncCopy));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudBlob, DMLibCopyMethod.ServiceSideAsyncCopy));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.CloudFile, DMLibCopyMethod.ServiceSideAsyncCopy));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudFile, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideAsyncCopy));
// Service side sync copying
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudFile, DMLibDataType.Cloud, DMLibCopyMethod.ServiceSideSyncCopy));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.CloudFile, DMLibCopyMethod.ServiceSideSyncCopy));
AllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudBlob, DMLibCopyMethod.ServiceSideSyncCopy));
// All valid directory transfer directions
DirAllValidDirectionSet = new DMLibTestMethodSetAttribute();
// Sync copy
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Local, DMLibDataType.Cloud));
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.Local));
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudFile, DMLibDataType.Cloud));
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.CloudFile));
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudBlob));
// Async copy
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudBlob, DMLibCopyMethod.ServiceSideAsyncCopy));
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.CloudFile, DMLibCopyMethod.ServiceSideAsyncCopy));
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudFile, DMLibDataType.BlockBlob, DMLibCopyMethod.ServiceSideAsyncCopy));
// Service side sync copying
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudFile, DMLibDataType.Cloud, DMLibCopyMethod.ServiceSideSyncCopy));
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.Cloud, DMLibDataType.CloudFile, DMLibCopyMethod.ServiceSideSyncCopy));
DirAllValidDirectionSet.AddTestMethodAttribute(new DMLibTestMethodAttribute(DMLibDataType.CloudBlob, DMLibCopyMethod.ServiceSideSyncCopy));
}
public DMLibTestMethodSetAttribute()
{
}
/// <summary>
/// Create a new instance of <see cref="DMLibTestMethodSetAttribute"/> containing specific
/// valid transfer directions from a query string. Query string format:
/// propertyName1=value1,propertyName2=value2...
/// e.g.
/// To specify all valid async copy directions to blob:
/// DestType=CloudBlob,IsAsync=true
/// </summary>
/// <param name="queryString">Query string</param>
public DMLibTestMethodSetAttribute(string queryString)
{
this.AddTestMethodAttribute(AllValidDirectionSet);
DMLibDirectionFilter directionFilter = new DMLibDirectionFilter(queryString);
this.AddDirectionFilter(directionFilter);
}
public DMLibTestMethodSetAttribute(DMLibTestMethodSet directionSet)
{
switch (directionSet)
{
case DMLibTestMethodSet.AllValidDirection:
this.AddTestMethodAttribute(AllValidDirectionSet);
break;
case DMLibTestMethodSet.Cloud2Cloud:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.Cloud,
DestType = DMLibDataType.Cloud,
});
break;
case DMLibTestMethodSet.AllAsync:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
CopyMethod = DMLibCopyMethod.ServiceSideAsyncCopy,
});
break;
case DMLibTestMethodSet.AllSync:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
CopyMethod = DMLibCopyMethod.SyncCopy,
});
break;
case DMLibTestMethodSet.AllServiceSideSync:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
CopyMethod = DMLibCopyMethod.ServiceSideSyncCopy,
});
break;
case DMLibTestMethodSet.CloudSource:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.Cloud,
});
break;
case DMLibTestMethodSet.CloudBlobSource:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.CloudBlob,
});
break;
case DMLibTestMethodSet.CloudFileSource:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.CloudFile,
});
break;
case DMLibTestMethodSet.LocalSource:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.Local,
});
break;
case DMLibTestMethodSet.CloudDest:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
DestType = DMLibDataType.Cloud,
});
break;
case DMLibTestMethodSet.CloudBlobDest:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
DestType = DMLibDataType.CloudBlob,
});
break;
case DMLibTestMethodSet.CloudFileDest:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
DestType = DMLibDataType.CloudFile,
});
break;
case DMLibTestMethodSet.LocalDest:
this.AddTestMethodAttribute(AllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
DestType = DMLibDataType.Local,
});
break;
case DMLibTestMethodSet.DirAllValidDirection:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
break;
case DMLibTestMethodSet.DirCloud2Cloud:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.Cloud,
DestType = DMLibDataType.Cloud,
});
break;
case DMLibTestMethodSet.DirAllAsync:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
CopyMethod = DMLibCopyMethod.ServiceSideAsyncCopy
});
break;
case DMLibTestMethodSet.DirAllSync:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
CopyMethod = DMLibCopyMethod.SyncCopy
});
break;
case DMLibTestMethodSet.DirAllServiceSideSync:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
CopyMethod = DMLibCopyMethod.ServiceSideSyncCopy
});
break;
case DMLibTestMethodSet.DirCloudSource:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.Cloud,
});
break;
case DMLibTestMethodSet.DirCloudBlobSource:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.CloudBlob,
});
break;
case DMLibTestMethodSet.DirCloudFileSource:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.CloudFile,
});
break;
case DMLibTestMethodSet.DirLocalSource:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
SourceType = DMLibDataType.Local,
});
break;
case DMLibTestMethodSet.DirCloudDest:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
DestType = DMLibDataType.Cloud,
});
break;
case DMLibTestMethodSet.DirCloudBlobDest:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
DestType = DMLibDataType.CloudBlob,
});
break;
case DMLibTestMethodSet.DirCloudFileDest:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
DestType = DMLibDataType.CloudFile,
});
break;
case DMLibTestMethodSet.DirLocalDest:
this.AddTestMethodAttribute(DirAllValidDirectionSet);
this.AddDirectionFilter(new DMLibDirectionFilter()
{
DestType = DMLibDataType.Local,
});
break;
default:
throw new ArgumentException(string.Format("Invalid MultiDirectionSet: {0}", directionSet.ToString()), "directionSet");
}
}
}
}
| |
// 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.Events;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using IdentityServerHost.Filters;
using IdentityServerHost.ViewModels;
using IdentityServerHost.Models;
using IdentityServerHost.Constants;
using IdentityServerHost.Extensions;
namespace IdentityServerHost.Controllers
{
/// <summary>
/// This controller processes the consent UI
/// </summary>
[SecurityHeaders]
[Authorize]
public class ConsentController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IResourceStore _resourceStore;
private readonly IEventService _events;
private readonly ILogger<ConsentController> _logger;
public ConsentController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IResourceStore resourceStore,
IEventService events,
ILogger<ConsentController> logger)
{
_interaction = interaction;
_clientStore = clientStore;
_resourceStore = resourceStore;
_events = events;
_logger = logger;
}
/// <summary>
/// Shows the consent screen
/// </summary>
/// <param name="returnUrl"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Index(string returnUrl)
{
var vm = await BuildViewModelAsync(returnUrl);
if (vm != null)
{
return View("Index", vm);
}
return View("Error");
}
/// <summary>
/// Handles the consent screen postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ConsentInputModel model)
{
var result = await ProcessConsent(model);
if (result.IsRedirect)
{
if (await _clientStore.IsPkceClientAsync(result.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = result.RedirectUri });
}
return Redirect(result.RedirectUri);
}
if (result.HasValidationError)
{
ModelState.AddModelError(string.Empty, result.ValidationError);
}
if (result.ShowView)
{
return View("Index", result.ViewModel);
}
return View("Error");
}
/*****************************************/
/* helper APIs for the ConsentController */
/*****************************************/
private async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model)
{
var result = new ProcessConsentResult();
// validate return url is still valid
var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model?.Button == "no")
{
grantedConsent = ConsentResponse.Denied;
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested));
}
// user clicked 'yes' - validate the data
else if (model?.Button == "yes")
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesConsented = scopes.ToArray()
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.GrantConsentAsync(request, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.ClientId = request.ClientId;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
}
return result;
}
private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId);
if (client != null)
{
var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);
if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
{
return CreateConsentViewModel(model, returnUrl, request, client, resources);
}
else
{
_logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y));
}
}
else
{
_logger.LogError("Invalid client id: {0}", request.ClientId);
}
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
private ConsentViewModel CreateConsentViewModel(
ConsentInputModel model, string returnUrl,
AuthorizationRequest request,
Client client, Resources resources)
{
var vm = new ConsentViewModel
{
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
ReturnUrl = returnUrl,
ClientName = client.ClientName ?? client.ClientId,
ClientUrl = client.ClientUri,
ClientLogoUrl = client.LogoUri,
AllowRememberConsent = client.AllowRememberConsent
};
vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
{
vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] {
GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
});
}
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
DisplayName = identity.DisplayName,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(Scope scope, bool check)
{
return new ScopeViewModel
{
Name = scope.Name,
DisplayName = scope.DisplayName,
Description = scope.Description,
Emphasize = scope.Emphasize,
Required = scope.Required,
Checked = check || scope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Imaging.BitmapSource.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Imaging
{
abstract public partial class BitmapSource : System.Windows.Media.ImageSource, System.Windows.Media.Composition.DUCE.IResource
{
#region Methods and constructors
protected BitmapSource()
{
}
protected void CheckIfSiteOfOrigin()
{
}
public System.Windows.Media.Imaging.BitmapSource Clone()
{
return default(System.Windows.Media.Imaging.BitmapSource);
}
protected override void CloneCore(System.Windows.Freezable sourceFreezable)
{
}
public System.Windows.Media.Imaging.BitmapSource CloneCurrentValue()
{
return default(System.Windows.Media.Imaging.BitmapSource);
}
protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable)
{
}
public virtual new void CopyPixels(System.Windows.Int32Rect sourceRect, IntPtr buffer, int bufferSize, int stride)
{
}
public virtual new void CopyPixels(System.Windows.Int32Rect sourceRect, Array pixels, int stride, int offset)
{
}
public virtual new void CopyPixels(Array pixels, int stride, int offset)
{
}
public static BitmapSource Create(int pixelWidth, int pixelHeight, double dpiX, double dpiY, System.Windows.Media.PixelFormat pixelFormat, BitmapPalette palette, Array pixels, int stride)
{
return default(BitmapSource);
}
public static BitmapSource Create(int pixelWidth, int pixelHeight, double dpiX, double dpiY, System.Windows.Media.PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride)
{
return default(BitmapSource);
}
protected override bool FreezeCore(bool isChecking)
{
return default(bool);
}
protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
int System.Windows.Media.Composition.DUCE.IResource.GetChannelCount()
{
return default(int);
}
#endregion
#region Properties and indexers
public virtual new double DpiX
{
get
{
return default(double);
}
}
public virtual new double DpiY
{
get
{
return default(double);
}
}
public virtual new System.Windows.Media.PixelFormat Format
{
get
{
return default(System.Windows.Media.PixelFormat);
}
}
public override double Height
{
get
{
return default(double);
}
}
public virtual new bool IsDownloading
{
get
{
return default(bool);
}
}
public override System.Windows.Media.ImageMetadata Metadata
{
get
{
return default(System.Windows.Media.ImageMetadata);
}
}
public virtual new BitmapPalette Palette
{
get
{
return default(BitmapPalette);
}
}
public virtual new int PixelHeight
{
get
{
return default(int);
}
}
public virtual new int PixelWidth
{
get
{
return default(int);
}
}
public override double Width
{
get
{
return default(double);
}
}
#endregion
#region Events
public virtual new event EventHandler<System.Windows.Media.ExceptionEventArgs> DecodeFailed
{
add
{
}
remove
{
}
}
public virtual new event EventHandler DownloadCompleted
{
add
{
}
remove
{
}
}
public virtual new event EventHandler<System.Windows.Media.ExceptionEventArgs> DownloadFailed
{
add
{
}
remove
{
}
}
public virtual new event EventHandler<DownloadProgressEventArgs> DownloadProgress
{
add
{
}
remove
{
}
}
#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 RegexRunner class is a base class for compiled regex code.
// Implementation notes:
// It provides the driver code that call's the subclass's Go()
// method for either scanning or direct execution.
//
// It also maintains memory allocation for the backtracking stack,
// the grouping stack and the longjump crawlstack, and provides
// methods to push new subpattern match results into (or remove
// backtracked results from) the Match instance.
using System.Diagnostics;
using System.Globalization;
namespace System.Text.RegularExpressions
{
public abstract class RegexRunner
{
protected internal int runtextbeg; // beginning of text to search
protected internal int runtextend; // end of text to search
protected internal int runtextstart; // starting point for search
protected internal String runtext; // text to search
protected internal int runtextpos; // current position in text
protected internal int[] runtrack; // The backtracking stack. Opcodes use this to store data regarding
protected internal int runtrackpos; // what they have matched and where to backtrack to. Each "frame" on
// the stack takes the form of [CodePosition Data1 Data2...], where
// CodePosition is the position of the current opcode and
// the data values are all optional. The CodePosition can be negative, and
// these values (also called "back2") are used by the BranchMark family of opcodes
// to indicate whether they are backtracking after a successful or failed
// match.
// When we backtrack, we pop the CodePosition off the stack, set the current
// instruction pointer to that code position, and mark the opcode
// with a backtracking flag ("Back"). Each opcode then knows how to
// handle its own data.
protected internal int[] runstack; // This stack is used to track text positions across different opcodes.
protected internal int runstackpos; // For example, in /(a*b)+/, the parentheses result in a SetMark/CaptureMark
// pair. SetMark records the text position before we match a*b. Then
// CaptureMark uses that position to figure out where the capture starts.
// Opcodes which push onto this stack are always paired with other opcodes
// which will pop the value from it later. A successful match should mean
// that this stack is empty.
protected internal int[] runcrawl; // The crawl stack is used to keep track of captures. Every time a group
protected internal int runcrawlpos; // has a capture, we push its group number onto the runcrawl stack. In
// the case of a balanced match, we push BOTH groups onto the stack.
protected internal int runtrackcount; // count of states that may do backtracking
protected internal Match runmatch; // result object
protected internal Regex runregex; // regex object
private Int32 _timeout; // timeout in milliseconds (needed for actual)
private bool _ignoreTimeout;
private Int32 _timeoutOccursAt;
// We have determined this value in a series of experiments where x86 retail
// builds (ono-lab-optimized) were run on different pattern/input pairs. Larger values
// of TimeoutCheckFrequency did not tend to increase performance; smaller values
// of TimeoutCheckFrequency tended to slow down the execution.
private const int TimeoutCheckFrequency = 1000;
private int _timeoutChecksToSkip;
protected internal RegexRunner() { }
/// <summary>
/// Scans the string to find the first match. Uses the Match object
/// both to feed text in and as a place to store matches that come out.
///
/// All the action is in the abstract Go() method defined by subclasses. Our
/// responsibility is to load up the class members (as done here) before
/// calling Go.
///
/// The optimizer can compute a set of candidate starting characters,
/// and we could use a separate method Skip() that will quickly scan past
/// any characters that we know can't match.
/// </summary>
protected internal Match Scan(Regex regex, String text, int textbeg, int textend, int textstart, int prevlen, bool quick)
{
return Scan(regex, text, textbeg, textend, textstart, prevlen, quick, regex.MatchTimeout);
}
protected internal Match Scan(Regex regex, String text, int textbeg, int textend, int textstart, int prevlen, bool quick, TimeSpan timeout)
{
int bump;
int stoppos;
bool initted = false;
// We need to re-validate timeout here because Scan is historically protected and
// thus there is a possibility it is called from user code:
Regex.ValidateMatchTimeout(timeout);
_ignoreTimeout = (Regex.InfiniteMatchTimeout == timeout);
_timeout = _ignoreTimeout
? (Int32)Regex.InfiniteMatchTimeout.TotalMilliseconds
: (Int32)(timeout.TotalMilliseconds + 0.5); // Round
runregex = regex;
runtext = text;
runtextbeg = textbeg;
runtextend = textend;
runtextstart = textstart;
bump = runregex.RightToLeft ? -1 : 1;
stoppos = runregex.RightToLeft ? runtextbeg : runtextend;
runtextpos = textstart;
// If previous match was empty or failed, advance by one before matching
if (prevlen == 0)
{
if (runtextpos == stoppos)
return Match.Empty;
runtextpos += bump;
}
StartTimeoutWatch();
for (; ;)
{
#if DEBUG
if (runregex.Debug)
{
Debug.WriteLine("");
Debug.WriteLine("Search range: from " + runtextbeg.ToString(CultureInfo.InvariantCulture) + " to " + runtextend.ToString(CultureInfo.InvariantCulture));
Debug.WriteLine("Firstchar search starting at " + runtextpos.ToString(CultureInfo.InvariantCulture) + " stopping at " + stoppos.ToString(CultureInfo.InvariantCulture));
}
#endif
if (FindFirstChar())
{
CheckTimeout();
if (!initted)
{
InitMatch();
initted = true;
}
#if DEBUG
if (runregex.Debug)
{
Debug.WriteLine("Executing engine starting at " + runtextpos.ToString(CultureInfo.InvariantCulture));
Debug.WriteLine("");
}
#endif
Go();
if (runmatch._matchcount[0] > 0)
{
// We'll return a match even if it touches a previous empty match
return TidyMatch(quick);
}
// reset state for another go
runtrackpos = runtrack.Length;
runstackpos = runstack.Length;
runcrawlpos = runcrawl.Length;
}
// failure!
if (runtextpos == stoppos)
{
TidyMatch(true);
return Match.Empty;
}
// Recognize leading []* and various anchors, and bump on failure accordingly
// Bump by one and start again
runtextpos += bump;
}
// We never get here
}
private void StartTimeoutWatch()
{
if (_ignoreTimeout)
return;
_timeoutChecksToSkip = TimeoutCheckFrequency;
// We are using Environment.TickCount and not Timewatch for performance reasons.
// Environment.TickCount is an int that cycles. We intentionally let timeoutOccursAt
// overflow it will still stay ahead of Environment.TickCount for comparisons made
// in DoCheckTimeout():
unchecked
{
_timeoutOccursAt = Environment.TickCount + _timeout;
}
}
protected void CheckTimeout()
{
if (_ignoreTimeout)
return;
if (--_timeoutChecksToSkip != 0)
return;
_timeoutChecksToSkip = TimeoutCheckFrequency;
DoCheckTimeout();
}
private void DoCheckTimeout()
{
// Note that both, Environment.TickCount and timeoutOccursAt are ints and can overflow and become negative.
// See the comment in StartTimeoutWatch().
int currentMillis = Environment.TickCount;
if (currentMillis < _timeoutOccursAt)
return;
if (0 > _timeoutOccursAt && 0 < currentMillis)
return;
#if DEBUG
if (runregex.Debug)
{
Debug.WriteLine("");
Debug.WriteLine("RegEx match timeout occurred!");
Debug.WriteLine("Specified timeout: " + TimeSpan.FromMilliseconds(_timeout).ToString());
Debug.WriteLine("Timeout check frequency: " + TimeoutCheckFrequency);
Debug.WriteLine("Search pattern: " + runregex.pattern);
Debug.WriteLine("Input: " + runtext);
Debug.WriteLine("About to throw RegexMatchTimeoutException.");
}
#endif
throw new RegexMatchTimeoutException(runtext, runregex.pattern, TimeSpan.FromMilliseconds(_timeout));
}
/// <summary>
/// The responsibility of Go() is to run the regular expression at
/// runtextpos and call Capture() on all the captured subexpressions,
/// then to leave runtextpos at the ending position. It should leave
/// runtextpos where it started if there was no match.
/// </summary>
protected abstract void Go();
/// <summary>
/// The responsibility of FindFirstChar() is to advance runtextpos
/// until it is at the next position which is a candidate for the
/// beginning of a successful match.
/// </summary>
protected abstract bool FindFirstChar();
/// <summary>
/// InitTrackCount must initialize the runtrackcount field; this is
/// used to know how large the initial runtrack and runstack arrays
/// must be.
/// </summary>
protected abstract void InitTrackCount();
/// <summary>
/// Initializes all the data members that are used by Go()
/// </summary>
private void InitMatch()
{
// Use a hashtable'ed Match object if the capture numbers are sparse
if (runmatch == null)
{
if (runregex._caps != null)
runmatch = new MatchSparse(runregex, runregex._caps, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
else
runmatch = new Match(runregex, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
}
else
{
runmatch.Reset(runregex, runtext, runtextbeg, runtextend, runtextstart);
}
// note we test runcrawl, because it is the last one to be allocated
// If there is an alloc failure in the middle of the three allocations,
// we may still return to reuse this instance, and we want to behave
// as if the allocations didn't occur. (we used to test _trackcount != 0)
if (runcrawl != null)
{
runtrackpos = runtrack.Length;
runstackpos = runstack.Length;
runcrawlpos = runcrawl.Length;
return;
}
InitTrackCount();
int tracksize = runtrackcount * 8;
int stacksize = runtrackcount * 8;
if (tracksize < 32)
tracksize = 32;
if (stacksize < 16)
stacksize = 16;
runtrack = new int[tracksize];
runtrackpos = tracksize;
runstack = new int[stacksize];
runstackpos = stacksize;
runcrawl = new int[32];
runcrawlpos = 32;
}
/// <summary>
/// Put match in its canonical form before returning it.
/// </summary>
private Match TidyMatch(bool quick)
{
if (!quick)
{
Match match = runmatch;
runmatch = null;
match.Tidy(runtextpos);
return match;
}
else
{
// in quick mode, a successful match returns null, and
// the allocated match object is left in the cache
return null;
}
}
/// <summary>
/// Called by the implementation of Go() to increase the size of storage
/// </summary>
protected void EnsureStorage()
{
if (runstackpos < runtrackcount * 4)
DoubleStack();
if (runtrackpos < runtrackcount * 4)
DoubleTrack();
}
/// <summary>
/// Called by the implementation of Go() to decide whether the pos
/// at the specified index is a boundary or not. It's just not worth
/// emitting inline code for this logic.
/// </summary>
protected bool IsBoundary(int index, int startpos, int endpos)
{
return (index > startpos && RegexCharClass.IsWordChar(runtext[index - 1])) !=
(index < endpos && RegexCharClass.IsWordChar(runtext[index]));
}
protected bool IsECMABoundary(int index, int startpos, int endpos)
{
return (index > startpos && RegexCharClass.IsECMAWordChar(runtext[index - 1])) !=
(index < endpos && RegexCharClass.IsECMAWordChar(runtext[index]));
}
protected static bool CharInSet(char ch, String set, String category)
{
string charClass = RegexCharClass.ConvertOldStringsToClass(set, category);
return RegexCharClass.CharInClass(ch, charClass);
}
protected static bool CharInClass(char ch, String charClass)
{
return RegexCharClass.CharInClass(ch, charClass);
}
/// <summary>
/// Called by the implementation of Go() to increase the size of the
/// backtracking stack.
/// </summary>
protected void DoubleTrack()
{
int[] newtrack;
newtrack = new int[runtrack.Length * 2];
System.Array.Copy(runtrack, 0, newtrack, runtrack.Length, runtrack.Length);
runtrackpos += runtrack.Length;
runtrack = newtrack;
}
/// <summary>
/// Called by the implementation of Go() to increase the size of the
/// grouping stack.
/// </summary>
protected void DoubleStack()
{
int[] newstack;
newstack = new int[runstack.Length * 2];
System.Array.Copy(runstack, 0, newstack, runstack.Length, runstack.Length);
runstackpos += runstack.Length;
runstack = newstack;
}
/// <summary>
/// Increases the size of the longjump unrolling stack.
/// </summary>
protected void DoubleCrawl()
{
int[] newcrawl;
newcrawl = new int[runcrawl.Length * 2];
System.Array.Copy(runcrawl, 0, newcrawl, runcrawl.Length, runcrawl.Length);
runcrawlpos += runcrawl.Length;
runcrawl = newcrawl;
}
/// <summary>
/// Save a number on the longjump unrolling stack
/// </summary>
protected void Crawl(int i)
{
if (runcrawlpos == 0)
DoubleCrawl();
runcrawl[--runcrawlpos] = i;
}
/// <summary>
/// Remove a number from the longjump unrolling stack
/// </summary>
protected int Popcrawl()
{
return runcrawl[runcrawlpos++];
}
/// <summary>
/// Get the height of the stack
/// </summary>
protected int Crawlpos()
{
return runcrawl.Length - runcrawlpos;
}
/// <summary>
/// Called by Go() to capture a subexpression. Note that the
/// capnum used here has already been mapped to a non-sparse
/// index (by the code generator RegexWriter).
/// </summary>
protected void Capture(int capnum, int start, int end)
{
if (end < start)
{
int T;
T = end;
end = start;
start = T;
}
Crawl(capnum);
runmatch.AddMatch(capnum, start, end - start);
}
/// <summary>
/// Called by Go() to capture a subexpression. Note that the
/// capnum used here has already been mapped to a non-sparse
/// index (by the code generator RegexWriter).
/// </summary>
protected void TransferCapture(int capnum, int uncapnum, int start, int end)
{
int start2;
int end2;
// these are the two intervals that are cancelling each other
if (end < start)
{
int T;
T = end;
end = start;
start = T;
}
start2 = MatchIndex(uncapnum);
end2 = start2 + MatchLength(uncapnum);
// The new capture gets the innermost defined interval
if (start >= end2)
{
end = start;
start = end2;
}
else if (end <= start2)
{
start = start2;
}
else
{
if (end > end2)
end = end2;
if (start2 > start)
start = start2;
}
Crawl(uncapnum);
runmatch.BalanceMatch(uncapnum);
if (capnum != -1)
{
Crawl(capnum);
runmatch.AddMatch(capnum, start, end - start);
}
}
/*
* Called by Go() to revert the last capture
*/
protected void Uncapture()
{
int capnum = Popcrawl();
runmatch.RemoveMatch(capnum);
}
/// <summary>
/// Call out to runmatch to get around visibility issues
/// </summary>
protected bool IsMatched(int cap)
{
return runmatch.IsMatched(cap);
}
/// <summary>
/// Call out to runmatch to get around visibility issues
/// </summary>
protected int MatchIndex(int cap)
{
return runmatch.MatchIndex(cap);
}
/// <summary>
/// Call out to runmatch to get around visibility issues
/// </summary>
protected int MatchLength(int cap)
{
return runmatch.MatchLength(cap);
}
#if DEBUG
/// <summary>
/// Dump the current state
/// </summary>
internal virtual void DumpState()
{
Debug.WriteLine("Text: " + TextposDescription());
Debug.WriteLine("Track: " + StackDescription(runtrack, runtrackpos));
Debug.WriteLine("Stack: " + StackDescription(runstack, runstackpos));
}
internal static String StackDescription(int[] a, int index)
{
var sb = new StringBuilder();
sb.Append(a.Length - index);
sb.Append('/');
sb.Append(a.Length);
if (sb.Length < 8)
sb.Append(' ', 8 - sb.Length);
sb.Append('(');
for (int i = index; i < a.Length; i++)
{
if (i > index)
sb.Append(' ');
sb.Append(a[i]);
}
sb.Append(')');
return sb.ToString();
}
internal virtual String TextposDescription()
{
var sb = new StringBuilder();
int remaining;
sb.Append(runtextpos);
if (sb.Length < 8)
sb.Append(' ', 8 - sb.Length);
if (runtextpos > runtextbeg)
sb.Append(RegexCharClass.CharDescription(runtext[runtextpos - 1]));
else
sb.Append('^');
sb.Append('>');
remaining = runtextend - runtextpos;
for (int i = runtextpos; i < runtextend; i++)
{
sb.Append(RegexCharClass.CharDescription(runtext[i]));
}
if (sb.Length >= 64)
{
sb.Length = 61;
sb.Append("...");
}
else
{
sb.Append('$');
}
return sb.ToString();
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using NiL.JS.Core;
using NiL.JS.Core.Interop;
namespace NiL.JS.BaseLibrary
{
#if !(PORTABLE || NETCORE)
[Serializable]
#endif
public sealed class RegExp : CustomType
{
private struct RegExpCacheItem
{
public string key;
public Regex re;
public RegExpCacheItem(string key, Regex re)
{
this.key = key;
this.re = re;
}
}
private static RegExpCacheItem[] _cache = new RegExpCacheItem[_cacheSize];
private static int _cacheIndex = -1;
private const int _cacheSize = 16;
private string _source;
private JSValue _lastIndex;
internal Regex _regex;
[DoNotEnumerate]
public RegExp()
{
_source = "";
_global = false;
_sticky = false;
_unicode = false;
_regex = new Regex("");
}
private void makeRegex(Arguments args)
{
var ptrn = args[0];
if (ptrn._valueType == JSValueType.Object && ptrn.Value is RegExp)
{
if (args.GetProperty("length")._iValue > 1 && args[1]._valueType > JSValueType.Undefined)
ExceptionHelper.Throw(new TypeError("Cannot supply flags when constructing one RegExp from another"));
_oValue = ptrn._oValue;
_regex = (ptrn.Value as RegExp)._regex;
_global = (ptrn.Value as RegExp)._global;
_sticky = (ptrn.Value as RegExp)._sticky;
_unicode = (ptrn.Value as RegExp)._unicode;
_source = (ptrn.Value as RegExp)._source;
return;
}
var pattern = ptrn._valueType > JSValueType.Undefined ? ptrn.ToString() : "";
var flags = args.GetProperty("length")._iValue > 1 && args[1]._valueType > JSValueType.Undefined ? args[1].ToString() : "";
makeRegex(pattern, flags);
}
private void makeRegex(string pattern, string flags)
{
pattern = pattern ?? "null";
flags = flags ?? "null";
_global = false;
_sticky = false;
_unicode = false;
try
{
var options = RegexOptions.ECMAScript | RegexOptions.CultureInvariant;
for (int i = 0; i < flags.Length; i++)
{
switch (flags[i])
{
case 'i':
{
if ((options & RegexOptions.IgnoreCase) != 0)
ExceptionHelper.Throw(new SyntaxError("Try to double use RegExp flag \"" + flags[i] + '"'));
options |= RegexOptions.IgnoreCase;
break;
}
case 'm':
{
if ((options & RegexOptions.Multiline) != 0)
ExceptionHelper.Throw(new SyntaxError("Try to double use RegExp flag \"" + flags[i] + '"'));
options |= RegexOptions.Multiline;
break;
}
case 'g':
{
if (_global)
ExceptionHelper.Throw(new SyntaxError("Try to double use RegExp flag \"" + flags[i] + '"'));
_global = true;
break;
}
case 'u':
{
if (_unicode)
ExceptionHelper.Throw(new SyntaxError("Try to double use RegExp flag \"" + flags[i] + '"'));
_unicode = true;
break;
}
case 'y':
{
if (_sticky)
ExceptionHelper.Throw(new SyntaxError("Try to double use RegExp flag \"" + flags[i] + '"'));
_sticky = true;
break;
}
default:
{
ExceptionHelper.Throw(new SyntaxError("Invalid RegExp flag \"" + flags[i] + '"'));
break;
}
}
}
_source = pattern;
string label = _source + "/"
+ ((options & RegexOptions.IgnoreCase) != 0 ? "i" : "")
+ ((options & RegexOptions.Multiline) != 0 ? "m" : "")
+ (_unicode ? "u" : "");
if (_cacheIndex >= 0)
{
int _cacheSizeMinusOne = _cacheSize - 1;
for (var i = _cacheSize + _cacheIndex; i > _cacheIndex; i--)
{
if (_cache[i & _cacheSizeMinusOne].key == label)
{
_regex = _cache[i & _cacheSizeMinusOne].re;
return;
}
}
}
pattern = Tools.Unescape(pattern, false, false, true, _unicode);
if (_unicode)
pattern = translateToUnicodePattern(pattern);
_regex = new Regex(pattern, options);
_cacheIndex = (_cacheIndex + 1) % _cacheSize;
_cache[_cacheIndex].key = label;
_cache[_cacheIndex].re = _regex;
}
catch (ArgumentException e)
{
ExceptionHelper.Throw(new SyntaxError(e.Message));
}
}
private static string translateToUnicodePattern(string pattern)
{
if (pattern == null || pattern == "")
return "";
var s = new StringBuilder(pattern.Length);
/**
* This is what we need to change:
* 1. The dot. It has to be adjusted so that is now also matches all surrogate pairs.
* 2. Character sets have to be adjusted:
* a) [ (surrogate pair) ] should match the code point and not the high or low part of the surrogate pair.
* b) [^ set ] should include all Unicode characters (also > \uFFFF) except set.
* c) [(surrogate pair or UTF-16 char)-(surrogate pair)] should not throw an error.
* 3. Character classes (\D, \S and \W) outside of sets have to be adjusted.
* 4. Surrogate pairs should be surrounded by a non-capturing group to act as one character
*/
for (int i = 0; i < pattern.Length; i++)
{
char c = pattern[i];
if (c == '.')
{
s.Append("(?:[\uD800-\uDBFF][\uDC00-\uDFFF]|.)");
}
else if (c == '[' && i + 1 < pattern.Length)
{
int stop = i + 1;
while (i < pattern.Length && pattern[stop] != ']')
{
if (pattern[stop] == '\\')
stop++;
stop++;
}
if (stop >= pattern.Length)
{
s.Append('[');
continue;
}
bool inv = pattern[i + 1] == '^';
if (inv)
i++;
s.Append(translateCharSet(pattern.Substring(i + 1, stop - i - 1), inv));
i = stop;
}
else if (c == '\\' && i + 1 < pattern.Length)
{
c = pattern[++i];
if (c == 'D' || c == 'S' || c == 'W')
s.Append("(?:[\uD800-\uDBFF][\uDC00-\uDFFF]|\\" + c + ")");
else
s.Append('\\').Append(c);
}
else if (Tools.IsSurrogatePair(pattern, i))
{
s.Append("(?:").Append(c).Append(pattern[++i]).Append(')');
}
else
s.Append(c);
}
return s.ToString();
}
private struct CharRange
{
public int start;
public int stop; // inclusive
public CharRange(int start, int stop)
{
this.start = start;
this.stop = stop;
}
public static int MaxValue = 0x10FFFF;
public static int MinValue = 0;
}
private static string translateCharSet(string set, bool inverted)
{
CharRange[] crs = analyzeCharSet(set); // character ranges
if (inverted)
crs = invertCharSet(crs);
if (crs.Length == 0)
return @"[]";
if (crs.Length == 1 && crs[0].start == 0 && crs[0].stop == CharRange.MaxValue)
return @"(?:[\uD800-\uDBFF][\uDC00-\uDFFF]|[\s\S])";
var sC = new List<CharRange>(crs); // single char ranges
for (var i = sC.Count - 1; i >= 0; i--)
{
if (sC[i].start > 0xFFFF)
{
sC.RemoveAt(i);
continue;
}
else if (sC[i].stop > 0xFFFF)
sC[i] = new CharRange(sC[i].start, 0xFFFF);
break;
}
var mC = new List<CharRange>(crs.Length - sC.Count + 1); // multi char ranges
for (int i = 0; i < crs.Length; i++)
{
if (crs[i].start > 0xFFFF)
mC.Add(crs[i]);
else if (crs[i].stop > 0xFFFF)
mC.Add(new CharRange(0x10000, crs[i].stop));
}
var s = new StringBuilder("(?:");
if (mC.Count > 0)
{
s.Append("(?:");
for (int i = 0; i < mC.Count; i++)
{
if (i > 0)
s.Append('|');
var c = mC[i];
if (c.start == c.stop)
s.Append(Tools.CodePointToString(c.start));
else
{
var start = Tools.CodePointToString(c.start);
var stop = Tools.CodePointToString(c.stop);
// It will print each character range independent from each other.
// (This might not be the most efficient way)
// This assumes c.start <= c.stop
// (which will be true if CharRange is used correctly)
if (start[0] == stop[0])
s.Append(start[0]).Append('[').Append(start[1]).Append('-').Append(stop[1]).Append(']');
else
{
int s1 = (start[1] > '\uDC00') ? 1 : 0;
int s2 = (stop[1] < '\uDFFF') ? 1 : 0;
if (s1 != 0)
s.Append(start[0]).Append('[').Append(start[1]).Append("-\uDFFF]|");
if (stop[0] - start[0] >= s1 + s2)
{
s.Append('[');
s.Append((char)(start[0] + s1));
s.Append('-');
s.Append((char)(stop[0] - s2));
s.Append(']');
s.Append("[\uDC00-\uDFFF]|");
}
if (s2 != 0)
s.Append(stop[0]).Append("[\uDC00-").Append(stop[1]).Append(']');
}
}
}
s.Append(")");
}
if (sC.Count > 0)
{
if (mC.Count > 0)
s.Append('|');
s.Append("[");
for (int i = 0; i < sC.Count; i++)
{
var c = sC[i];
if (c.start == c.stop)
s.Append("\\u").Append(c.start.ToString("X4"));
else
{
s.Append("\\u").Append(c.start.ToString("X4"));
if (c.stop > c.start + 1)
s.Append('-');
s.Append("\\u").Append(c.stop.ToString("X4"));
}
}
s.Append("]");
}
s.Append(")");
return s.ToString();
}
private static CharRange[] analyzeCharSet(string set)
{
var r = new List<CharRange>();
char c;
int cI, dI;
for (int i = 0; i < set.Length; i++)
{
c = set[i];
cI = Tools.NextCodePoint(set, ref i);
if (c == '\\' && i + 1 < set.Length)
{
c = set[++i];
if (c == 'd')
{
r.Add(new CharRange(48, 57));
continue;
}
if (c == 'D')
{
r.Add(new CharRange(0, 47));
r.Add(new CharRange(58, CharRange.MaxValue));
continue;
}
else if (c == 's')
{
r.Add(new CharRange(9, 10));
r.Add(new CharRange(13, 13));
r.Add(new CharRange(32, 32));
continue;
}
else if (c == 'S')
{
r.Add(new CharRange(0, 8));
r.Add(new CharRange(11, 12));
r.Add(new CharRange(14, 31));
r.Add(new CharRange(33, CharRange.MaxValue));
continue;
}
else if (c == 'w')
{
r.Add(new CharRange(48, 57));
r.Add(new CharRange(65, 90));
r.Add(new CharRange(95, 95));
r.Add(new CharRange(97, 122));
continue;
}
else if (c == 'W')
{
r.Add(new CharRange(0, 47));
r.Add(new CharRange(58, 64));
r.Add(new CharRange(91, 94));
r.Add(new CharRange(96, 96));
r.Add(new CharRange(123, CharRange.MaxValue));
continue;
}
i--;
}
if (i + 2 < set.Length && set[i + 1] == '-') // -[char]
{
i += 2;
dI = Tools.NextCodePoint(set, ref i, true);
if (dI < cI)
ExceptionHelper.Throw(new SyntaxError("Range out of order in character class"));
r.Add(new CharRange(cI, dI));
continue;
}
r.Add(new CharRange(cI, cI));
}
if (r.Count <= 1)
return r.ToArray();
// sort
r.Sort(new Comparison<CharRange>(new Func<CharRange, CharRange, int>((x, y) => x.start - y.start)));
// optimize
var rNew = new List<CharRange>();
CharRange cr = r[0];
for (int i = 1; i < r.Count; i++)
{
if (r[i].stop <= cr.stop)
continue;
if (cr.stop >= r[i].start - 1)
{
cr.stop = r[i].stop;
continue;
}
rNew.Add(cr);
cr = r[i];
}
rNew.Add(cr);
return rNew.ToArray();
}
private static CharRange[] invertCharSet(CharRange[] set)
{
if (set.Length == 0)
return new CharRange[] { new CharRange(0, CharRange.MaxValue) };
var r = new List<CharRange>();
if (set[0].start > 0)
r.Add(new CharRange(0, set[0].start - 1));
for (int i = 1; i < set.Length; i++)
r.Add(new CharRange(set[i - 1].stop + 1, set[i].start - 1));
if (set[set.Length - 1].stop < CharRange.MaxValue)
r.Add(new CharRange(set[set.Length - 1].stop + 1, CharRange.MaxValue));
return r.ToArray();
}
[DoNotEnumerate]
public RegExp(Arguments args)
{
makeRegex(args);
}
[DoNotEnumerate]
public RegExp(string pattern, string flags)
{
makeRegex(pattern, flags);
}
internal bool _global;
[Field]
[ReadOnly]
[DoNotDelete]
[DoNotEnumerate]
[NotConfigurable]
public Boolean global
{
[Hidden]
get
{
return _global;
}
}
[Field]
[ReadOnly]
[DoNotDelete]
[DoNotEnumerate]
[NotConfigurable]
public Boolean ignoreCase
{
get
{
return (_regex.Options & RegexOptions.IgnoreCase) != 0;
}
}
[Field]
[ReadOnly]
[DoNotDelete]
[DoNotEnumerate]
[NotConfigurable]
public Boolean multiline
{
get
{
return (_regex.Options & RegexOptions.Multiline) != 0;
}
}
internal bool _sticky;
[Field]
[ReadOnly]
[DoNotDelete]
[DoNotEnumerate]
[NotConfigurable]
public Boolean sticky
{
[Hidden]
get
{
return _sticky;
}
}
internal bool _unicode;
[Field]
[ReadOnly]
[DoNotDelete]
[DoNotEnumerate]
[NotConfigurable]
public Boolean unicode
{
[Hidden]
get
{
return _unicode;
}
}
[Field]
[ReadOnly]
[DoNotDelete]
[DoNotEnumerate]
[NotConfigurable]
public String source
{
get
{
return new String(_source);
}
}
[Field]
[DoNotDelete]
[DoNotEnumerate]
[NotConfigurable]
public JSValue lastIndex
{
get
{
return _lastIndex ?? (_lastIndex = 0);
}
set
{
_lastIndex = (value ?? JSValue.undefined).CloneImpl(false);
}
}
[DoNotEnumerate]
public RegExp compile(Arguments args)
{
makeRegex(args);
return this;
}
[DoNotEnumerate]
public JSValue exec(JSValue arg)
{
string input = (arg ?? "null").ToString();
if (!_global && !_sticky)
{
// non-global and/or non-sticky matching doesn't use lastIndex
var m = _regex.Match(input);
if (!m.Success)
return JSValue.@null;
var res = new Array(m.Groups.Count);
for (int i = 0; i < m.Groups.Count; i++)
res._data[i] = m.Groups[i].Success ? (JSValue)m.Groups[i].Value : null;
res.DefineProperty("index").Assign(m.Index);
res.DefineProperty("input").Assign(input);
return res;
}
else
{
_lastIndex = Tools.JSObjectToNumber(_lastIndex);
if ((_lastIndex._attributes & JSValueAttributesInternal.SystemObject) != 0)
_lastIndex = _lastIndex.CloneImpl(false);
if (_lastIndex._valueType == JSValueType.Double)
{
_lastIndex._valueType = JSValueType.Integer;
_lastIndex._iValue = (int)_lastIndex._dValue;
}
int li = (_lastIndex._iValue < 0) ? 0 : _lastIndex._iValue;
_lastIndex._iValue = 0;
if (li >= input.Length && input.Length > 0)
return JSValue.@null;
var m = _regex.Match(input, li);
if (!m.Success || (_sticky && m.Index != li))
return JSValue.@null;
var res = new Array(m.Groups.Count);
for (int i = 0; i < m.Groups.Count; i++)
res._data[i] = m.Groups[i].Success ? (JSValue)m.Groups[i].Value : null;
_lastIndex._iValue = m.Index + m.Length;
res.DefineProperty("index").Assign(m.Index);
res.DefineProperty("input").Assign(input);
return res;
}
}
[DoNotEnumerate]
public JSValue test(JSValue arg)
{
// definition: exec(arg) != null
string input = (arg ?? "null").ToString();
if (!_global && !_sticky)
return _regex.IsMatch(input);
_lastIndex = Tools.JSObjectToNumber(_lastIndex);
if ((_lastIndex._attributes & JSValueAttributesInternal.SystemObject) != 0)
_lastIndex = _lastIndex.CloneImpl(false);
if (_lastIndex._valueType == JSValueType.Double)
{
_lastIndex._valueType = JSValueType.Integer;
_lastIndex._iValue = (int)_lastIndex._dValue;
}
int li = (_lastIndex._iValue < 0) ? 0 : _lastIndex._iValue;
_lastIndex._iValue = 0;
if (li >= input.Length && input.Length > 0)
return false;
var m = _regex.Match(input, li);
if (!m.Success || (_sticky && m.Index != li))
return false;
_lastIndex._iValue = m.Index + m.Length;
return true;
}
#if !WRC
[CLSCompliant(false)]
[DoNotEnumerate]
public JSValue toString()
{
return ToString();
}
#endif
[Hidden]
public override string ToString()
{
return "/" + _source + "/"
+ (_global ? "g" : "")
+ ((_regex.Options & RegexOptions.IgnoreCase) != 0 ? "i" : "")
+ ((_regex.Options & RegexOptions.Multiline) != 0 ? "m" : "")
+ (_unicode ? "u" : "")
+ (_sticky ? "y" : "");
}
}
}
| |
using System;
using Orleans.Messaging;
using System.Collections.Concurrent;
namespace Orleans.Runtime
{
internal class MessagingStatisticsGroup
{
internal class PerSocketDirectionStats
{
private readonly AverageValueStatistic averageBatchSize;
private readonly HistogramValueStatistic batchSizeBytesHistogram;
internal PerSocketDirectionStats(bool sendOrReceive, SocketDirection direction)
{
StatisticNameFormat batchSizeStatName = sendOrReceive ? StatisticNames.MESSAGING_SENT_BATCH_SIZE_PER_SOCKET_DIRECTION : StatisticNames.MESSAGING_RECEIVED_BATCH_SIZE_PER_SOCKET_DIRECTION;
StatisticNameFormat batchHistogramStatName = sendOrReceive ? StatisticNames.MESSAGING_SENT_BATCH_SIZE_BYTES_HISTOGRAM_PER_SOCKET_DIRECTION : StatisticNames.MESSAGING_RECEIVED_BATCH_SIZE_BYTES_HISTOGRAM_PER_SOCKET_DIRECTION;
averageBatchSize = AverageValueStatistic.FindOrCreate(new StatisticName(batchSizeStatName, Enum.GetName(typeof(SocketDirection), direction)));
batchSizeBytesHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(
new StatisticName(batchHistogramStatName, Enum.GetName(typeof(SocketDirection), direction)),
NUM_MSG_SIZE_HISTOGRAM_CATEGORIES);
}
internal void OnMessage(int numMsgsInBatch, int totalBytes)
{
averageBatchSize.AddValue(numMsgsInBatch);
batchSizeBytesHistogram.AddData(totalBytes);
}
}
internal static CounterStatistic MessagesSentTotal;
internal static CounterStatistic[] MessagesSentPerDirection;
internal static CounterStatistic TotalBytesSent;
internal static CounterStatistic HeaderBytesSent;
internal static CounterStatistic MessagesReceived;
internal static CounterStatistic[] MessagesReceivedPerDirection;
private static CounterStatistic totalBytesReceived;
private static CounterStatistic headerBytesReceived;
internal static CounterStatistic LocalMessagesSent;
internal static CounterStatistic[] FailedSentMessages;
internal static CounterStatistic[] DroppedSentMessages;
internal static CounterStatistic[] RejectedMessages;
internal static CounterStatistic[] ReroutedMessages;
private static CounterStatistic expiredAtSendCounter;
private static CounterStatistic expiredAtReceiveCounter;
private static CounterStatistic expiredAtDispatchCounter;
private static CounterStatistic expiredAtInvokeCounter;
private static CounterStatistic expiredAtRespondCounter;
internal static CounterStatistic ConnectedClientCount;
private static PerSocketDirectionStats[] perSocketDirectionStatsSend;
private static PerSocketDirectionStats[] perSocketDirectionStatsReceive;
private static ConcurrentDictionary<string, CounterStatistic> perSiloSendCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloReceiveCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloPingSendCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReceiveCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReplyReceivedCounters;
private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReplyMissedCounters;
internal enum Phase
{
Send,
Receive,
Dispatch,
Invoke,
Respond,
}
// Histogram of sent message size, starting from 0 in multiples of 2
// (1=2^0, 2=2^2, ... , 256=2^8, 512=2^9, 1024==2^10, ... , up to ... 2^30=1GB)
private static HistogramValueStatistic sentMsgSizeHistogram;
private static HistogramValueStatistic receiveMsgSizeHistogram;
private const int NUM_MSG_SIZE_HISTOGRAM_CATEGORIES = 31;
internal static void Init(bool silo)
{
if (silo)
{
LocalMessagesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_LOCALMESSAGES);
ConnectedClientCount = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_CONNECTED_CLIENTS, false);
}
MessagesSentTotal = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_MESSAGES_TOTAL);
MessagesSentPerDirection = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
foreach (var direction in Enum.GetValues(typeof(Message.Directions)))
{
MessagesSentPerDirection[(int)direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_SENT_MESSAGES_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
MessagesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_MESSAGES_TOTAL);
MessagesReceivedPerDirection = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
foreach (var direction in Enum.GetValues(typeof(Message.Directions)))
{
MessagesReceivedPerDirection[(int)direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_RECEIVED_MESSAGES_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
TotalBytesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_BYTES_TOTAL);
totalBytesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_BYTES_TOTAL);
HeaderBytesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_BYTES_HEADER);
headerBytesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_BYTES_HEADER);
FailedSentMessages = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
DroppedSentMessages = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
RejectedMessages = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
ReroutedMessages = new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length];
foreach (var direction in Enum.GetValues(typeof(Message.Directions)))
{
ReroutedMessages[(int)direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_REROUTED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
sentMsgSizeHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(StatisticNames.MESSAGING_SENT_MESSAGESIZEHISTOGRAM, NUM_MSG_SIZE_HISTOGRAM_CATEGORIES);
receiveMsgSizeHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(StatisticNames.MESSAGING_RECEIVED_MESSAGESIZEHISTOGRAM, NUM_MSG_SIZE_HISTOGRAM_CATEGORIES);
expiredAtSendCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATSENDER);
expiredAtReceiveCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATRECEIVER);
expiredAtDispatchCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATDISPATCH);
expiredAtInvokeCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATINVOKE);
expiredAtRespondCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATRESPOND);
perSocketDirectionStatsSend = new PerSocketDirectionStats[Enum.GetValues(typeof(SocketDirection)).Length];
perSocketDirectionStatsReceive = new PerSocketDirectionStats[Enum.GetValues(typeof(SocketDirection)).Length];
if (silo)
{
perSocketDirectionStatsSend[(int)SocketDirection.SiloToSilo] = new PerSocketDirectionStats(true, SocketDirection.SiloToSilo);
perSocketDirectionStatsSend[(int)SocketDirection.GatewayToClient] = new PerSocketDirectionStats(true, SocketDirection.GatewayToClient);
perSocketDirectionStatsReceive[(int)SocketDirection.SiloToSilo] = new PerSocketDirectionStats(false, SocketDirection.SiloToSilo);
perSocketDirectionStatsReceive[(int)SocketDirection.GatewayToClient] = new PerSocketDirectionStats(false, SocketDirection.GatewayToClient);
}
else
{
perSocketDirectionStatsSend[(int)SocketDirection.ClientToGateway] = new PerSocketDirectionStats(true, SocketDirection.ClientToGateway);
perSocketDirectionStatsReceive[(int)SocketDirection.ClientToGateway] = new PerSocketDirectionStats(false, SocketDirection.ClientToGateway);
}
perSiloSendCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloReceiveCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloPingSendCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloPingReceiveCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloPingReplyReceivedCounters = new ConcurrentDictionary<string, CounterStatistic>();
perSiloPingReplyMissedCounters = new ConcurrentDictionary<string, CounterStatistic>();
}
internal static void OnMessageSend(SiloAddress targetSilo, Message.Directions direction, int numTotalBytes, int headerBytes, SocketDirection socketDirection)
{
if (numTotalBytes < 0)
throw new ArgumentException(String.Format("OnMessageSend(numTotalBytes={0})", numTotalBytes), "numTotalBytes");
OnMessageSend_Impl(targetSilo, direction, numTotalBytes, headerBytes, 1);
}
internal static void OnMessageBatchSend(SiloAddress targetSilo, Message.Directions direction, int numTotalBytes, int headerBytes, SocketDirection socketDirection, int numMsgsInBatch)
{
if (numTotalBytes < 0)
throw new ArgumentException(String.Format("OnMessageBatchSend(numTotalBytes={0})", numTotalBytes), "numTotalBytes");
OnMessageSend_Impl(targetSilo, direction, numTotalBytes, headerBytes, numMsgsInBatch);
perSocketDirectionStatsSend[(int)socketDirection].OnMessage(numMsgsInBatch, numTotalBytes);
}
private static void OnMessageSend_Impl(SiloAddress targetSilo, Message.Directions direction, int numTotalBytes, int headerBytes, int numMsgsInBatch)
{
MessagesSentTotal.IncrementBy(numMsgsInBatch);
MessagesSentPerDirection[(int)direction].IncrementBy(numMsgsInBatch);
TotalBytesSent.IncrementBy(numTotalBytes);
HeaderBytesSent.IncrementBy(headerBytes);
sentMsgSizeHistogram.AddData(numTotalBytes);
FindCounter(perSiloSendCounters, new StatisticName(StatisticNames.MESSAGING_SENT_MESSAGES_PER_SILO, (targetSilo != null ? targetSilo.ToString() : "Null")), CounterStorage.LogOnly).IncrementBy(numMsgsInBatch);
}
private static CounterStatistic FindCounter(ConcurrentDictionary<string, CounterStatistic> counters, StatisticName name, CounterStorage storage)
{
CounterStatistic stat;
if (counters.TryGetValue(name.Name, out stat))
{
return stat;
}
stat = CounterStatistic.FindOrCreate(name, storage);
counters.TryAdd(name.Name, stat);
return stat;
}
internal static void OnMessageReceive(Message msg, int headerBytes, int bodyBytes)
{
MessagesReceived.Increment();
MessagesReceivedPerDirection[(int)msg.Direction].Increment();
totalBytesReceived.IncrementBy(headerBytes + bodyBytes);
headerBytesReceived.IncrementBy(headerBytes);
receiveMsgSizeHistogram.AddData(headerBytes + bodyBytes);
SiloAddress addr = msg.SendingSilo;
FindCounter(perSiloReceiveCounters, new StatisticName(StatisticNames.MESSAGING_RECEIVED_MESSAGES_PER_SILO, (addr != null ? addr.ToString() : "Null")), CounterStorage.LogOnly).Increment();
}
internal static void OnMessageBatchReceive(SocketDirection socketDirection, int numMsgsInBatch, int totalBytes)
{
perSocketDirectionStatsReceive[(int)socketDirection].OnMessage(numMsgsInBatch, totalBytes);
}
internal static void OnMessageExpired(Phase phase)
{
switch (phase)
{
case Phase.Send:
expiredAtSendCounter.Increment();
break;
case Phase.Receive:
expiredAtReceiveCounter.Increment();
break;
case Phase.Dispatch:
expiredAtDispatchCounter.Increment();
break;
case Phase.Invoke:
expiredAtInvokeCounter.Increment();
break;
case Phase.Respond:
expiredAtRespondCounter.Increment();
break;
}
}
internal static void OnPingSend(SiloAddress destination)
{
FindCounter(perSiloPingSendCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_SENT_PER_SILO, destination.ToString()), CounterStorage.LogOnly).Increment();
}
internal static void OnPingReceive(SiloAddress destination)
{
FindCounter(perSiloPingReceiveCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_RECEIVED_PER_SILO, destination.ToString()), CounterStorage.LogOnly).Increment();
}
internal static void OnPingReplyReceived(SiloAddress replier)
{
FindCounter(perSiloPingReplyReceivedCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_REPLYRECEIVED_PER_SILO, replier.ToString()), CounterStorage.LogOnly).Increment();
}
internal static void OnPingReplyMissed(SiloAddress replier)
{
FindCounter(perSiloPingReplyMissedCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_REPLYMISSED_PER_SILO, replier.ToString()), CounterStorage.LogOnly).Increment();
}
internal static void OnFailedSentMessage(Message msg)
{
if (msg == null || !msg.ContainsHeader(Message.Header.DIRECTION)) return;
int direction = (int)msg.Direction;
if (FailedSentMessages[direction] == null)
{
FailedSentMessages[direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_SENT_FAILED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
FailedSentMessages[direction].Increment();
}
internal static void OnDroppedSentMessage(Message msg)
{
if (msg == null || !msg.ContainsHeader(Message.Header.DIRECTION)) return;
int direction = (int)msg.Direction;
if (DroppedSentMessages[direction] == null)
{
DroppedSentMessages[direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_SENT_DROPPED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
DroppedSentMessages[direction].Increment();
}
internal static void OnRejectedMessage(Message msg)
{
if (msg == null || !msg.ContainsHeader(Message.Header.DIRECTION)) return;
int direction = (int)msg.Direction;
if (RejectedMessages[direction] == null)
{
RejectedMessages[direction] = CounterStatistic.FindOrCreate(
new StatisticName(StatisticNames.MESSAGING_REJECTED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction)));
}
RejectedMessages[direction].Increment();
}
internal static void OnMessageReRoute(Message msg)
{
ReroutedMessages[(int)msg.Direction].Increment();
}
}
}
| |
using EngineLayer;
using GuiFunctions;
using OxyPlot;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace MetaMorpheusGUI
{
/// <summary>
/// Interaction logic for MetaDraw.xaml
/// </summary>
public partial class MetaDraw : Window
{
private ParentChildScanPlotsView itemsControlSampleViewModel;
private MetaDrawLogic MetaDrawLogic;
private readonly DataTable propertyView;
private ObservableCollection<string> plotTypes;
private ObservableCollection<string> PsmStatPlotFiles;
private static List<string> AcceptedSpectraFormats = new List<string> { ".mzml", ".raw", ".mgf" };
private static List<string> AcceptedResultsFormats = new List<string> { ".psmtsv", ".tsv" };
private static List<string> AcceptedSpectralLibraryFormats = new List<string> { ".msp" };
public MetaDraw()
{
UsefulProteomicsDatabases.Loaders.LoadElements();
InitializeComponent();
MetaDrawLogic = new MetaDrawLogic();
BindingOperations.EnableCollectionSynchronization(MetaDrawLogic.PsmResultFilePaths, MetaDrawLogic.ThreadLocker);
BindingOperations.EnableCollectionSynchronization(MetaDrawLogic.SpectraFilePaths, MetaDrawLogic.ThreadLocker);
BindingOperations.EnableCollectionSynchronization(MetaDrawLogic.FilteredListOfPsms, MetaDrawLogic.ThreadLocker);
BindingOperations.EnableCollectionSynchronization(MetaDrawLogic.PsmsGroupedByFile, MetaDrawLogic.ThreadLocker);
itemsControlSampleViewModel = new ParentChildScanPlotsView();
ParentChildScanViewPlots.DataContext = itemsControlSampleViewModel;
propertyView = new DataTable();
propertyView.Columns.Add("Name", typeof(string));
propertyView.Columns.Add("Value", typeof(string));
dataGridProperties.DataContext = propertyView.DefaultView;
dataGridScanNums.DataContext = MetaDrawLogic.PeptideSpectralMatchesView;
Title = "MetaDraw: version " + GlobalVariables.MetaMorpheusVersion;
base.Closing += this.OnClosing;
ParentChildScanView.Visibility = Visibility.Collapsed;
PsmStatPlotFiles = new ObservableCollection<string>();
selectSourceFileListBox.DataContext = PsmStatPlotFiles;
plotTypes = new ObservableCollection<string>();
SetUpPlots();
plotsListBox.ItemsSource = plotTypes;
}
private void Window_Drop(object sender, DragEventArgs e)
{
string[] files = ((string[])e.Data.GetData(DataFormats.FileDrop)).OrderBy(p => p).ToArray();
if (files != null)
{
foreach (var draggedFilePath in files)
{
if (File.Exists(draggedFilePath))
{
AddFile(draggedFilePath);
}
}
}
}
private void AddFile(string filePath)
{
var theExtension = GlobalVariables.GetFileExtension(filePath).ToLowerInvariant();
if (AcceptedSpectraFormats.Contains(theExtension))
{
if (!MetaDrawLogic.SpectraFilePaths.Contains(filePath))
{
MetaDrawLogic.SpectraFilePaths.Add(filePath);
if (MetaDrawLogic.SpectraFilePaths.Count == 1)
{
spectraFileNameLabel.Text = filePath;
}
else
{
spectraFileNameLabel.Text = "[Mouse over to view files]";
}
spectraFileNameLabel.ToolTip = string.Join("\n", MetaDrawLogic.SpectraFilePaths);
resetSpectraFileButton.IsEnabled = true;
}
}
else if (AcceptedResultsFormats.Contains(theExtension))
{
if (!MetaDrawLogic.PsmResultFilePaths.Contains(filePath))
{
MetaDrawLogic.PsmResultFilePaths.Add(filePath);
if (MetaDrawLogic.PsmResultFilePaths.Count == 1)
{
psmFileNameLabel.Text = filePath;
psmFileNameLabelStat.Text = filePath;
}
else
{
psmFileNameLabel.Text = "[Mouse over to view files]";
psmFileNameLabelStat.Text = "[Mouse over to view files]";
}
psmFileNameLabel.ToolTip = string.Join("\n", MetaDrawLogic.PsmResultFilePaths);
resetPsmFileButton.IsEnabled = true;
psmFileNameLabelStat.ToolTip = string.Join("\n", MetaDrawLogic.PsmResultFilePaths);
resetPsmFileButtonStat.IsEnabled = true;
}
}
else if (AcceptedSpectralLibraryFormats.Contains(theExtension))
{
// TODO: display this somewhere in the GUI
if (!MetaDrawLogic.SpectralLibraryPaths.Contains(filePath))
{
MetaDrawLogic.SpectralLibraryPaths.Add(filePath);
}
}
else
{
MessageBox.Show("Cannot read file type: " + theExtension);
}
}
/// <summary>
/// Event triggers when a different cell is selected in the PSM data grid
/// </summary>
private void dataGridScanNums_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
if (dataGridScanNums.SelectedItem == null)
{
return;
}
PsmFromTsv psm = (PsmFromTsv)dataGridScanNums.SelectedItem;
// draw the annotated spectrum
MetaDrawLogic.DisplaySpectrumMatch(plotView, canvas, psm, itemsControlSampleViewModel, out var errors);
//draw the sequence coverage if not crosslinked
if (psm.ChildScanMatchedIons == null)
{
MetaDrawLogic.DrawSequenceCoverageMap(psm, sequenceText, map); //TODO: figure out how to show coverage on crosslinked peptides
ParentChildScanView.Visibility = Visibility.Collapsed;
SequenceCoverageAnnotationView.Visibility = Visibility.Visible;
}
else
{
ParentChildScanView.Visibility = Visibility.Visible;
SequenceCoverageAnnotationView.Visibility = Visibility.Collapsed;
}
mapViewer.Width = map.Width;
if (errors != null && errors.Any())
{
MessageBox.Show(errors.First());
return;
}
// display PSM properties
propertyView.Clear();
System.Reflection.PropertyInfo[] temp = psm.GetType().GetProperties();
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].Name == nameof(psm.MatchedIons))
{
propertyView.Rows.Add(temp[i].Name, string.Join(", ", psm.MatchedIons.Select(p => p.Annotation)));
}
else if (temp[i].Name == nameof(psm.VariantCrossingIons))
{
propertyView.Rows.Add(temp[i].Name, string.Join(", ", psm.VariantCrossingIons.Select(p => p.Annotation)));
}
else
{
propertyView.Rows.Add(temp[i].Name, temp[i].GetValue(psm, null));
}
}
}
private void selectSpectraFileButton_Click(object sender, RoutedEventArgs e)
{
string filterString = string.Join(";", AcceptedSpectraFormats.Select(p => "*" + p));
Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog
{
Filter = "Spectra Files(" + filterString + ")|" + filterString,
FilterIndex = 1,
RestoreDirectory = true,
Multiselect = true
};
if (openFileDialog1.ShowDialog() == true)
{
foreach (var filePath in openFileDialog1.FileNames.OrderBy(p => p))
{
AddFile(filePath);
}
}
}
private void selectPsmFileButton_Click(object sender, RoutedEventArgs e)
{
string filterString = string.Join(";", AcceptedResultsFormats.Concat(AcceptedSpectralLibraryFormats).Select(p => "*" + p));
Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog
{
Filter = "Result Files(" + filterString + ")|" + filterString,
FilterIndex = 1,
RestoreDirectory = true,
Multiselect = false
};
if (openFileDialog1.ShowDialog() == true)
{
foreach (var filePath in openFileDialog1.FileNames.OrderBy(p => p))
{
AddFile(filePath);
}
}
}
private void resetFilesButton_Click(object sender, RoutedEventArgs e)
{
MetaDrawLogic.CleanUpResources();
spectraFileNameLabel.Text = "None Selected";
psmFileNameLabel.Text = "None Selected";
}
private void OnClosing(object sender, CancelEventArgs e)
{
MetaDrawLogic.CleanUpResources();
}
private void settings_Click(object sender, RoutedEventArgs e)
{
var settingsWindow = new MetaDrawSettingsWindow();
var result = settingsWindow.ShowDialog();
// save current selected PSM
var selectedItem = dataGridScanNums.SelectedItem;
if (result == true)
{
// refresh chart
dataGridScanNums_SelectedCellsChanged(null, null);
// filter based on new settings
MetaDrawLogic.FilterPsms();
}
// re-select selected PSM
if (selectedItem != null)
{
dataGridScanNums.SelectedItem = selectedItem;
}
}
private async void loadFilesButton_Click(object sender, RoutedEventArgs e)
{
// check for validity
propertyView.Clear();
if (!MetaDrawLogic.SpectraFilePaths.Any())
{
MessageBox.Show("Please add a spectra file.");
return;
}
if (!MetaDrawLogic.PsmResultFilePaths.Any())
{
MessageBox.Show("Please add a search result file.");
return;
}
// load the spectra file
(sender as Button).IsEnabled = false;
selectSpectraFileButton.IsEnabled = false;
selectPsmFileButton.IsEnabled = false;
resetSpectraFileButton.IsEnabled = false;
resetPsmFileButton.IsEnabled = false;
prgsFeed.IsOpen = true;
prgsText.Content = "Loading data...";
// Add EventHandlers for popup click-in/click-out behaviour
Deactivated += new EventHandler(prgsFeed_Deactivator);
Activated += new EventHandler(prgsFeed_Reactivator);
var slowProcess = Task<List<string>>.Factory.StartNew(() => MetaDrawLogic.LoadFiles(loadSpectra: true, loadPsms: true));
await slowProcess;
var errors = slowProcess.Result;
if (errors.Any())
{
string errorList = string.Join("\n", errors);
MessageBox.Show(errorList);
}
PsmStatPlotFiles.Clear();
foreach (var item in MetaDrawLogic.PsmsGroupedByFile)
{
PsmStatPlotFiles.Add(item.Key);
}
// done loading - restore controls
this.prgsFeed.IsOpen = false;
// Remove added EventHandlers
Deactivated -= new EventHandler(prgsFeed_Deactivator);
Activated -= new EventHandler(prgsFeed_Reactivator);
(sender as Button).IsEnabled = true;
selectSpectraFileButton.IsEnabled = true;
selectPsmFileButton.IsEnabled = true;
resetSpectraFileButton.IsEnabled = true;
resetPsmFileButton.IsEnabled = true;
}
/// <summary>
/// Deactivates the "loading data" popup if one clicks out of the main window
/// </summary>
private void prgsFeed_Deactivator(object sender, EventArgs e)
{
prgsFeed.IsOpen = false;
}
/// <summary>
/// Reactivates the "loading data" popup if one clicks into the main window
/// </summary>
private void prgsFeed_Reactivator(object sender, EventArgs e)
{
prgsFeed.IsOpen = true;
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string txt = (sender as TextBox).Text;
MetaDrawLogic.FilterPsmsByString(txt);
}
private void PDFButton_Click(object sender, RoutedEventArgs e)
{
if (dataGridScanNums.SelectedCells.Count == 0)
{
MessageBox.Show("Please select at least one scan to export");
return;
}
List<PsmFromTsv> items = new List<PsmFromTsv>();
foreach (var cell in dataGridScanNums.SelectedItems)
{
var psm = (PsmFromTsv)cell;
items.Add(psm);
}
string directoryPath = Path.Combine(Path.GetDirectoryName(MetaDrawLogic.PsmResultFilePaths.First()), "MetaDrawExport",
DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture));
MetaDrawLogic.ExportToPdf(plotView, canvas, items, itemsControlSampleViewModel, directoryPath, out var errors);
if (errors.Any())
{
MessageBox.Show(errors.First());
}
else
{
MessageBox.Show("PDFs exported to: " + directoryPath);
}
}
private void SetUpPlots()
{
foreach (var plot in PlotModelStat.PlotNames)
{
plotTypes.Add(plot);
}
}
private void loadFilesButtonStat_Click(object sender, RoutedEventArgs e)
{
// check for validity
if (!MetaDrawLogic.PsmResultFilePaths.Any())
{
MessageBox.Show("Please add a search result file.");
return;
}
(sender as Button).IsEnabled = false;
selectPsmFileButtonStat.IsEnabled = false;
resetPsmFileButtonStat.IsEnabled = false;
prgsFeedStat.IsOpen = true;
// load the PSMs
this.prgsTextStat.Content = "Loading data...";
MetaDrawLogic.LoadFiles(loadSpectra: false, loadPsms: true);
PsmStatPlotFiles.Clear();
foreach (var item in MetaDrawLogic.PsmsGroupedByFile)
{
PsmStatPlotFiles.Add(item.Key);
}
// done loading - restore controls
this.prgsFeedStat.IsOpen = false;
(sender as Button).IsEnabled = true;
selectPsmFileButtonStat.IsEnabled = true;
resetPsmFileButtonStat.IsEnabled = true;
}
private void CreatePlotPdf_Click(object sender, RoutedEventArgs e)
{
var selectedItem = plotsListBox.SelectedItem;
if (selectedItem == null)
{
MessageBox.Show("Select a plot type to export!");
return;
}
if (!MetaDrawLogic.PsmResultFilePaths.Any())
{
MessageBox.Show("No PSMs are loaded!");
return;
}
if (selectSourceFileListBox.SelectedItems.Count == 0)
{
MessageBox.Show("Please select a source file.");
return;
}
var plotName = selectedItem as string;
var fileDirectory = Directory.GetParent(MetaDrawLogic.PsmResultFilePaths.First()).ToString();
var fileName = String.Concat(plotName, ".pdf");
// update font sizes to exported PDF's size
double tmpW = plotViewStat.Width;
double tmpH = plotViewStat.Height;
plotViewStat.Width = 1000;
plotViewStat.Height = 700;
plotViewStat.UpdateLayout();
PlotViewStat_SizeChanged(plotViewStat, null);
using (Stream writePDF = File.Create(Path.Combine(fileDirectory, fileName)))
{
PdfExporter.Export(plotViewStat.Model, writePDF, 1000, 700);
}
plotViewStat.Width = tmpW;
plotViewStat.Height = tmpH;
MessageBox.Show("PDF Created at " + Path.Combine(fileDirectory, fileName) + "!");
}
private async void PlotSelected(object sender, SelectionChangedEventArgs e)
{
var listview = sender as ListView;
var plotName = listview.SelectedItem as string;
if (MetaDrawLogic.FilteredListOfPsms.Count == 0)
{
MessageBox.Show("There are no PSMs to analyze.\n\nLoad the current file or choose a new file.");
return;
}
if (selectSourceFileListBox.SelectedItems.Count == 0)
{
MessageBox.Show("Please select a source file.");
return;
}
// get psms from selected source files
ObservableCollection<PsmFromTsv> psms = new ObservableCollection<PsmFromTsv>();
Dictionary<string, ObservableCollection<PsmFromTsv>> psmsBSF = new Dictionary<string, ObservableCollection<PsmFromTsv>>();
foreach (string fileName in selectSourceFileListBox.SelectedItems)
{
psmsBSF.Add(fileName, MetaDrawLogic.PsmsGroupedByFile[fileName]);
foreach (PsmFromTsv psm in MetaDrawLogic.PsmsGroupedByFile[fileName])
{
psms.Add(psm);
}
}
PlotModelStat plot = await Task.Run(() => new PlotModelStat(plotName, psms, psmsBSF));
plotViewStat.DataContext = plot;
PlotViewStat_SizeChanged(plotViewStat, null);
}
private void selectSourceFileListBox_SelectionChanged(object sender, EventArgs e)
{
// refreshes the plot using the new source file
if (plotsListBox.SelectedIndex > -1 && selectSourceFileListBox.SelectedItems.Count != 0)
{
PlotSelected(plotsListBox, null);
}
}
private void selectAllSourceFiles_Click(object sender, RoutedEventArgs e)
{
selectSourceFileListBox.SelectAll();
}
private void deselectAllSourceFiles_Click(object sender, RoutedEventArgs e)
{
selectSourceFileListBox.SelectedIndex = -1;
}
// scales the font size down for the x axis labels of the PTM histogram when the window gets too small
private void PlotViewStat_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (plotsListBox.SelectedItem == null || !plotsListBox.SelectedItem.ToString().Equals("Histogram of PTM Spectral Counts"))
{
return;
}
OxyPlot.Wpf.PlotView plot = sender as OxyPlot.Wpf.PlotView;
if (plot != null && plot.Model != null)
{
plot.Model.DefaultXAxis.TitleFontSize = plot.Model.DefaultFontSize; // stops the title from being scaled
int count = (int)plot.Model.DefaultXAxis.ActualMaximum;
int widthCountRatio = 23; // maintains this width:number of PTM types ratio
if (plot.ActualWidth / count < widthCountRatio)
{
plot.Model.DefaultXAxis.FontSize = plot.Model.DefaultFontSize * (plot.ActualWidth / (count * widthCountRatio));
}
else
{
plot.Model.DefaultXAxis.FontSize = plot.Model.DefaultFontSize;
}
}
}
private void AnnotationSizeChanged(object sender, SizeChangedEventArgs e)
{
mapViewer.Height = .8 * SequenceAnnotationGrid.ActualHeight;
mapViewer.Width = .99 * SequenceAnnotationGrid.ActualWidth;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Settings/Master/PokemonSettings.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Settings.Master {
/// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/PokemonSettings.proto</summary>
public static partial class PokemonSettingsReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Settings/Master/PokemonSettings.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PokemonSettingsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjBQT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9Qb2tlbW9uU2V0dGluZ3Mu",
"cHJvdG8SGlBPR09Qcm90b3MuU2V0dGluZ3MuTWFzdGVyGiBQT0dPUHJvdG9z",
"L0VudW1zL1Bva2Vtb25JZC5wcm90bxokUE9HT1Byb3Rvcy9FbnVtcy9Qb2tl",
"bW9uUmFyaXR5LnByb3RvGiJQT0dPUHJvdG9zL0VudW1zL1Bva2Vtb25UeXBl",
"LnByb3RvGiJQT0dPUHJvdG9zL0VudW1zL1Bva2Vtb25Nb3ZlLnByb3RvGiZQ",
"T0dPUHJvdG9zL0VudW1zL1Bva2Vtb25GYW1pbHlJZC5wcm90bxo4UE9HT1By",
"b3Rvcy9TZXR0aW5ncy9NYXN0ZXIvUG9rZW1vbi9TdGF0c0F0dHJpYnV0ZXMu",
"cHJvdG8aOVBPR09Qcm90b3MvU2V0dGluZ3MvTWFzdGVyL1Bva2Vtb24vQ2Ft",
"ZXJhQXR0cmlidXRlcy5wcm90bxo8UE9HT1Byb3Rvcy9TZXR0aW5ncy9NYXN0",
"ZXIvUG9rZW1vbi9FbmNvdW50ZXJBdHRyaWJ1dGVzLnByb3RvIs4ICg9Qb2tl",
"bW9uU2V0dGluZ3MSLwoKcG9rZW1vbl9pZBgBIAEoDjIbLlBPR09Qcm90b3Mu",
"RW51bXMuUG9rZW1vbklkEhMKC21vZGVsX3NjYWxlGAMgASgCEisKBHR5cGUY",
"BCABKA4yHS5QT0dPUHJvdG9zLkVudW1zLlBva2Vtb25UeXBlEi0KBnR5cGVf",
"MhgFIAEoDjIdLlBPR09Qcm90b3MuRW51bXMuUG9rZW1vblR5cGUSRAoGY2Ft",
"ZXJhGAYgASgLMjQuUE9HT1Byb3Rvcy5TZXR0aW5ncy5NYXN0ZXIuUG9rZW1v",
"bi5DYW1lcmFBdHRyaWJ1dGVzEkoKCWVuY291bnRlchgHIAEoCzI3LlBPR09Q",
"cm90b3MuU2V0dGluZ3MuTWFzdGVyLlBva2Vtb24uRW5jb3VudGVyQXR0cmli",
"dXRlcxJCCgVzdGF0cxgIIAEoCzIzLlBPR09Qcm90b3MuU2V0dGluZ3MuTWFz",
"dGVyLlBva2Vtb24uU3RhdHNBdHRyaWJ1dGVzEjIKC3F1aWNrX21vdmVzGAkg",
"AygOMh0uUE9HT1Byb3Rvcy5FbnVtcy5Qb2tlbW9uTW92ZRI2Cg9jaW5lbWF0",
"aWNfbW92ZXMYCiADKA4yHS5QT0dPUHJvdG9zLkVudW1zLlBva2Vtb25Nb3Zl",
"EhYKDmFuaW1hdGlvbl90aW1lGAsgAygCEjIKDWV2b2x1dGlvbl9pZHMYDCAD",
"KA4yGy5QT0dPUHJvdG9zLkVudW1zLlBva2Vtb25JZBIWCg5ldm9sdXRpb25f",
"cGlwcxgNIAEoBRIvCgZyYXJpdHkYDiABKA4yHy5QT0dPUHJvdG9zLkVudW1z",
"LlBva2Vtb25SYXJpdHkSGAoQcG9rZWRleF9oZWlnaHRfbRgPIAEoAhIZChFw",
"b2tlZGV4X3dlaWdodF9rZxgQIAEoAhI2ChFwYXJlbnRfcG9rZW1vbl9pZBgR",
"IAEoDjIbLlBPR09Qcm90b3MuRW51bXMuUG9rZW1vbklkEhYKDmhlaWdodF9z",
"dGRfZGV2GBIgASgCEhYKDndlaWdodF9zdGRfZGV2GBMgASgCEhwKFGttX2Rp",
"c3RhbmNlX3RvX2hhdGNoGBQgASgCEjQKCWZhbWlseV9pZBgVIAEoDjIhLlBP",
"R09Qcm90b3MuRW51bXMuUG9rZW1vbkZhbWlseUlkEhcKD2NhbmR5X3RvX2V2",
"b2x2ZRgWIAEoBRIZChFrbV9idWRkeV9kaXN0YW5jZRgXIAEoAhJJCgpidWRk",
"eV9zaXplGBggASgOMjUuUE9HT1Byb3Rvcy5TZXR0aW5ncy5NYXN0ZXIuUG9r",
"ZW1vblNldHRpbmdzLkJ1ZGR5U2l6ZSJSCglCdWRkeVNpemUSEAoMQlVERFlf",
"TUVESVVNEAASEgoOQlVERFlfU0hPVUxERVIQARINCglCVUREWV9CSUcQAhIQ",
"CgxCVUREWV9GTFlJTkcQA2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.PokemonIdReflection.Descriptor, global::POGOProtos.Enums.PokemonRarityReflection.Descriptor, global::POGOProtos.Enums.PokemonTypeReflection.Descriptor, global::POGOProtos.Enums.PokemonMoveReflection.Descriptor, global::POGOProtos.Enums.PokemonFamilyIdReflection.Descriptor, global::POGOProtos.Settings.Master.Pokemon.StatsAttributesReflection.Descriptor, global::POGOProtos.Settings.Master.Pokemon.CameraAttributesReflection.Descriptor, global::POGOProtos.Settings.Master.Pokemon.EncounterAttributesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.PokemonSettings), global::POGOProtos.Settings.Master.PokemonSettings.Parser, new[]{ "PokemonId", "ModelScale", "Type", "Type2", "Camera", "Encounter", "Stats", "QuickMoves", "CinematicMoves", "AnimationTime", "EvolutionIds", "EvolutionPips", "Rarity", "PokedexHeightM", "PokedexWeightKg", "ParentPokemonId", "HeightStdDev", "WeightStdDev", "KmDistanceToHatch", "FamilyId", "CandyToEvolve", "KmBuddyDistance", "BuddySize" }, null, new[]{ typeof(global::POGOProtos.Settings.Master.PokemonSettings.Types.BuddySize) }, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PokemonSettings : pb::IMessage<PokemonSettings> {
private static readonly pb::MessageParser<PokemonSettings> _parser = new pb::MessageParser<PokemonSettings>(() => new PokemonSettings());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PokemonSettings> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Settings.Master.PokemonSettingsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonSettings() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonSettings(PokemonSettings other) : this() {
pokemonId_ = other.pokemonId_;
modelScale_ = other.modelScale_;
type_ = other.type_;
type2_ = other.type2_;
Camera = other.camera_ != null ? other.Camera.Clone() : null;
Encounter = other.encounter_ != null ? other.Encounter.Clone() : null;
Stats = other.stats_ != null ? other.Stats.Clone() : null;
quickMoves_ = other.quickMoves_.Clone();
cinematicMoves_ = other.cinematicMoves_.Clone();
animationTime_ = other.animationTime_.Clone();
evolutionIds_ = other.evolutionIds_.Clone();
evolutionPips_ = other.evolutionPips_;
rarity_ = other.rarity_;
pokedexHeightM_ = other.pokedexHeightM_;
pokedexWeightKg_ = other.pokedexWeightKg_;
parentPokemonId_ = other.parentPokemonId_;
heightStdDev_ = other.heightStdDev_;
weightStdDev_ = other.weightStdDev_;
kmDistanceToHatch_ = other.kmDistanceToHatch_;
familyId_ = other.familyId_;
candyToEvolve_ = other.candyToEvolve_;
kmBuddyDistance_ = other.kmBuddyDistance_;
buddySize_ = other.buddySize_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PokemonSettings Clone() {
return new PokemonSettings(this);
}
/// <summary>Field number for the "pokemon_id" field.</summary>
public const int PokemonIdFieldNumber = 1;
private global::POGOProtos.Enums.PokemonId pokemonId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonId PokemonId {
get { return pokemonId_; }
set {
pokemonId_ = value;
}
}
/// <summary>Field number for the "model_scale" field.</summary>
public const int ModelScaleFieldNumber = 3;
private float modelScale_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float ModelScale {
get { return modelScale_; }
set {
modelScale_ = value;
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 4;
private global::POGOProtos.Enums.PokemonType type_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonType Type {
get { return type_; }
set {
type_ = value;
}
}
/// <summary>Field number for the "type_2" field.</summary>
public const int Type2FieldNumber = 5;
private global::POGOProtos.Enums.PokemonType type2_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonType Type2 {
get { return type2_; }
set {
type2_ = value;
}
}
/// <summary>Field number for the "camera" field.</summary>
public const int CameraFieldNumber = 6;
private global::POGOProtos.Settings.Master.Pokemon.CameraAttributes camera_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Settings.Master.Pokemon.CameraAttributes Camera {
get { return camera_; }
set {
camera_ = value;
}
}
/// <summary>Field number for the "encounter" field.</summary>
public const int EncounterFieldNumber = 7;
private global::POGOProtos.Settings.Master.Pokemon.EncounterAttributes encounter_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Settings.Master.Pokemon.EncounterAttributes Encounter {
get { return encounter_; }
set {
encounter_ = value;
}
}
/// <summary>Field number for the "stats" field.</summary>
public const int StatsFieldNumber = 8;
private global::POGOProtos.Settings.Master.Pokemon.StatsAttributes stats_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Settings.Master.Pokemon.StatsAttributes Stats {
get { return stats_; }
set {
stats_ = value;
}
}
/// <summary>Field number for the "quick_moves" field.</summary>
public const int QuickMovesFieldNumber = 9;
private static readonly pb::FieldCodec<global::POGOProtos.Enums.PokemonMove> _repeated_quickMoves_codec
= pb::FieldCodec.ForEnum(74, x => (int) x, x => (global::POGOProtos.Enums.PokemonMove) x);
private readonly pbc::RepeatedField<global::POGOProtos.Enums.PokemonMove> quickMoves_ = new pbc::RepeatedField<global::POGOProtos.Enums.PokemonMove>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Enums.PokemonMove> QuickMoves {
get { return quickMoves_; }
}
/// <summary>Field number for the "cinematic_moves" field.</summary>
public const int CinematicMovesFieldNumber = 10;
private static readonly pb::FieldCodec<global::POGOProtos.Enums.PokemonMove> _repeated_cinematicMoves_codec
= pb::FieldCodec.ForEnum(82, x => (int) x, x => (global::POGOProtos.Enums.PokemonMove) x);
private readonly pbc::RepeatedField<global::POGOProtos.Enums.PokemonMove> cinematicMoves_ = new pbc::RepeatedField<global::POGOProtos.Enums.PokemonMove>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Enums.PokemonMove> CinematicMoves {
get { return cinematicMoves_; }
}
/// <summary>Field number for the "animation_time" field.</summary>
public const int AnimationTimeFieldNumber = 11;
private static readonly pb::FieldCodec<float> _repeated_animationTime_codec
= pb::FieldCodec.ForFloat(90);
private readonly pbc::RepeatedField<float> animationTime_ = new pbc::RepeatedField<float>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<float> AnimationTime {
get { return animationTime_; }
}
/// <summary>Field number for the "evolution_ids" field.</summary>
public const int EvolutionIdsFieldNumber = 12;
private static readonly pb::FieldCodec<global::POGOProtos.Enums.PokemonId> _repeated_evolutionIds_codec
= pb::FieldCodec.ForEnum(98, x => (int) x, x => (global::POGOProtos.Enums.PokemonId) x);
private readonly pbc::RepeatedField<global::POGOProtos.Enums.PokemonId> evolutionIds_ = new pbc::RepeatedField<global::POGOProtos.Enums.PokemonId>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Enums.PokemonId> EvolutionIds {
get { return evolutionIds_; }
}
/// <summary>Field number for the "evolution_pips" field.</summary>
public const int EvolutionPipsFieldNumber = 13;
private int evolutionPips_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int EvolutionPips {
get { return evolutionPips_; }
set {
evolutionPips_ = value;
}
}
/// <summary>Field number for the "rarity" field.</summary>
public const int RarityFieldNumber = 14;
private global::POGOProtos.Enums.PokemonRarity rarity_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonRarity Rarity {
get { return rarity_; }
set {
rarity_ = value;
}
}
/// <summary>Field number for the "pokedex_height_m" field.</summary>
public const int PokedexHeightMFieldNumber = 15;
private float pokedexHeightM_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float PokedexHeightM {
get { return pokedexHeightM_; }
set {
pokedexHeightM_ = value;
}
}
/// <summary>Field number for the "pokedex_weight_kg" field.</summary>
public const int PokedexWeightKgFieldNumber = 16;
private float pokedexWeightKg_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float PokedexWeightKg {
get { return pokedexWeightKg_; }
set {
pokedexWeightKg_ = value;
}
}
/// <summary>Field number for the "parent_pokemon_id" field.</summary>
public const int ParentPokemonIdFieldNumber = 17;
private global::POGOProtos.Enums.PokemonId parentPokemonId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonId ParentPokemonId {
get { return parentPokemonId_; }
set {
parentPokemonId_ = value;
}
}
/// <summary>Field number for the "height_std_dev" field.</summary>
public const int HeightStdDevFieldNumber = 18;
private float heightStdDev_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float HeightStdDev {
get { return heightStdDev_; }
set {
heightStdDev_ = value;
}
}
/// <summary>Field number for the "weight_std_dev" field.</summary>
public const int WeightStdDevFieldNumber = 19;
private float weightStdDev_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float WeightStdDev {
get { return weightStdDev_; }
set {
weightStdDev_ = value;
}
}
/// <summary>Field number for the "km_distance_to_hatch" field.</summary>
public const int KmDistanceToHatchFieldNumber = 20;
private float kmDistanceToHatch_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float KmDistanceToHatch {
get { return kmDistanceToHatch_; }
set {
kmDistanceToHatch_ = value;
}
}
/// <summary>Field number for the "family_id" field.</summary>
public const int FamilyIdFieldNumber = 21;
private global::POGOProtos.Enums.PokemonFamilyId familyId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonFamilyId FamilyId {
get { return familyId_; }
set {
familyId_ = value;
}
}
/// <summary>Field number for the "candy_to_evolve" field.</summary>
public const int CandyToEvolveFieldNumber = 22;
private int candyToEvolve_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CandyToEvolve {
get { return candyToEvolve_; }
set {
candyToEvolve_ = value;
}
}
/// <summary>Field number for the "km_buddy_distance" field.</summary>
public const int KmBuddyDistanceFieldNumber = 23;
private float kmBuddyDistance_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float KmBuddyDistance {
get { return kmBuddyDistance_; }
set {
kmBuddyDistance_ = value;
}
}
/// <summary>Field number for the "buddy_size" field.</summary>
public const int BuddySizeFieldNumber = 24;
private global::POGOProtos.Settings.Master.PokemonSettings.Types.BuddySize buddySize_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Settings.Master.PokemonSettings.Types.BuddySize BuddySize {
get { return buddySize_; }
set {
buddySize_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PokemonSettings);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PokemonSettings other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PokemonId != other.PokemonId) return false;
if (ModelScale != other.ModelScale) return false;
if (Type != other.Type) return false;
if (Type2 != other.Type2) return false;
if (!object.Equals(Camera, other.Camera)) return false;
if (!object.Equals(Encounter, other.Encounter)) return false;
if (!object.Equals(Stats, other.Stats)) return false;
if(!quickMoves_.Equals(other.quickMoves_)) return false;
if(!cinematicMoves_.Equals(other.cinematicMoves_)) return false;
if(!animationTime_.Equals(other.animationTime_)) return false;
if(!evolutionIds_.Equals(other.evolutionIds_)) return false;
if (EvolutionPips != other.EvolutionPips) return false;
if (Rarity != other.Rarity) return false;
if (PokedexHeightM != other.PokedexHeightM) return false;
if (PokedexWeightKg != other.PokedexWeightKg) return false;
if (ParentPokemonId != other.ParentPokemonId) return false;
if (HeightStdDev != other.HeightStdDev) return false;
if (WeightStdDev != other.WeightStdDev) return false;
if (KmDistanceToHatch != other.KmDistanceToHatch) return false;
if (FamilyId != other.FamilyId) return false;
if (CandyToEvolve != other.CandyToEvolve) return false;
if (KmBuddyDistance != other.KmBuddyDistance) return false;
if (BuddySize != other.BuddySize) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (PokemonId != 0) hash ^= PokemonId.GetHashCode();
if (ModelScale != 0F) hash ^= ModelScale.GetHashCode();
if (Type != 0) hash ^= Type.GetHashCode();
if (Type2 != 0) hash ^= Type2.GetHashCode();
if (camera_ != null) hash ^= Camera.GetHashCode();
if (encounter_ != null) hash ^= Encounter.GetHashCode();
if (stats_ != null) hash ^= Stats.GetHashCode();
hash ^= quickMoves_.GetHashCode();
hash ^= cinematicMoves_.GetHashCode();
hash ^= animationTime_.GetHashCode();
hash ^= evolutionIds_.GetHashCode();
if (EvolutionPips != 0) hash ^= EvolutionPips.GetHashCode();
if (Rarity != 0) hash ^= Rarity.GetHashCode();
if (PokedexHeightM != 0F) hash ^= PokedexHeightM.GetHashCode();
if (PokedexWeightKg != 0F) hash ^= PokedexWeightKg.GetHashCode();
if (ParentPokemonId != 0) hash ^= ParentPokemonId.GetHashCode();
if (HeightStdDev != 0F) hash ^= HeightStdDev.GetHashCode();
if (WeightStdDev != 0F) hash ^= WeightStdDev.GetHashCode();
if (KmDistanceToHatch != 0F) hash ^= KmDistanceToHatch.GetHashCode();
if (FamilyId != 0) hash ^= FamilyId.GetHashCode();
if (CandyToEvolve != 0) hash ^= CandyToEvolve.GetHashCode();
if (KmBuddyDistance != 0F) hash ^= KmBuddyDistance.GetHashCode();
if (BuddySize != 0) hash ^= BuddySize.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 (PokemonId != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) PokemonId);
}
if (ModelScale != 0F) {
output.WriteRawTag(29);
output.WriteFloat(ModelScale);
}
if (Type != 0) {
output.WriteRawTag(32);
output.WriteEnum((int) Type);
}
if (Type2 != 0) {
output.WriteRawTag(40);
output.WriteEnum((int) Type2);
}
if (camera_ != null) {
output.WriteRawTag(50);
output.WriteMessage(Camera);
}
if (encounter_ != null) {
output.WriteRawTag(58);
output.WriteMessage(Encounter);
}
if (stats_ != null) {
output.WriteRawTag(66);
output.WriteMessage(Stats);
}
quickMoves_.WriteTo(output, _repeated_quickMoves_codec);
cinematicMoves_.WriteTo(output, _repeated_cinematicMoves_codec);
animationTime_.WriteTo(output, _repeated_animationTime_codec);
evolutionIds_.WriteTo(output, _repeated_evolutionIds_codec);
if (EvolutionPips != 0) {
output.WriteRawTag(104);
output.WriteInt32(EvolutionPips);
}
if (Rarity != 0) {
output.WriteRawTag(112);
output.WriteEnum((int) Rarity);
}
if (PokedexHeightM != 0F) {
output.WriteRawTag(125);
output.WriteFloat(PokedexHeightM);
}
if (PokedexWeightKg != 0F) {
output.WriteRawTag(133, 1);
output.WriteFloat(PokedexWeightKg);
}
if (ParentPokemonId != 0) {
output.WriteRawTag(136, 1);
output.WriteEnum((int) ParentPokemonId);
}
if (HeightStdDev != 0F) {
output.WriteRawTag(149, 1);
output.WriteFloat(HeightStdDev);
}
if (WeightStdDev != 0F) {
output.WriteRawTag(157, 1);
output.WriteFloat(WeightStdDev);
}
if (KmDistanceToHatch != 0F) {
output.WriteRawTag(165, 1);
output.WriteFloat(KmDistanceToHatch);
}
if (FamilyId != 0) {
output.WriteRawTag(168, 1);
output.WriteEnum((int) FamilyId);
}
if (CandyToEvolve != 0) {
output.WriteRawTag(176, 1);
output.WriteInt32(CandyToEvolve);
}
if (KmBuddyDistance != 0F) {
output.WriteRawTag(189, 1);
output.WriteFloat(KmBuddyDistance);
}
if (BuddySize != 0) {
output.WriteRawTag(192, 1);
output.WriteEnum((int) BuddySize);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (PokemonId != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PokemonId);
}
if (ModelScale != 0F) {
size += 1 + 4;
}
if (Type != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
if (Type2 != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type2);
}
if (camera_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Camera);
}
if (encounter_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Encounter);
}
if (stats_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Stats);
}
size += quickMoves_.CalculateSize(_repeated_quickMoves_codec);
size += cinematicMoves_.CalculateSize(_repeated_cinematicMoves_codec);
size += animationTime_.CalculateSize(_repeated_animationTime_codec);
size += evolutionIds_.CalculateSize(_repeated_evolutionIds_codec);
if (EvolutionPips != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(EvolutionPips);
}
if (Rarity != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Rarity);
}
if (PokedexHeightM != 0F) {
size += 1 + 4;
}
if (PokedexWeightKg != 0F) {
size += 2 + 4;
}
if (ParentPokemonId != 0) {
size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) ParentPokemonId);
}
if (HeightStdDev != 0F) {
size += 2 + 4;
}
if (WeightStdDev != 0F) {
size += 2 + 4;
}
if (KmDistanceToHatch != 0F) {
size += 2 + 4;
}
if (FamilyId != 0) {
size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) FamilyId);
}
if (CandyToEvolve != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(CandyToEvolve);
}
if (KmBuddyDistance != 0F) {
size += 2 + 4;
}
if (BuddySize != 0) {
size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) BuddySize);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PokemonSettings other) {
if (other == null) {
return;
}
if (other.PokemonId != 0) {
PokemonId = other.PokemonId;
}
if (other.ModelScale != 0F) {
ModelScale = other.ModelScale;
}
if (other.Type != 0) {
Type = other.Type;
}
if (other.Type2 != 0) {
Type2 = other.Type2;
}
if (other.camera_ != null) {
if (camera_ == null) {
camera_ = new global::POGOProtos.Settings.Master.Pokemon.CameraAttributes();
}
Camera.MergeFrom(other.Camera);
}
if (other.encounter_ != null) {
if (encounter_ == null) {
encounter_ = new global::POGOProtos.Settings.Master.Pokemon.EncounterAttributes();
}
Encounter.MergeFrom(other.Encounter);
}
if (other.stats_ != null) {
if (stats_ == null) {
stats_ = new global::POGOProtos.Settings.Master.Pokemon.StatsAttributes();
}
Stats.MergeFrom(other.Stats);
}
quickMoves_.Add(other.quickMoves_);
cinematicMoves_.Add(other.cinematicMoves_);
animationTime_.Add(other.animationTime_);
evolutionIds_.Add(other.evolutionIds_);
if (other.EvolutionPips != 0) {
EvolutionPips = other.EvolutionPips;
}
if (other.Rarity != 0) {
Rarity = other.Rarity;
}
if (other.PokedexHeightM != 0F) {
PokedexHeightM = other.PokedexHeightM;
}
if (other.PokedexWeightKg != 0F) {
PokedexWeightKg = other.PokedexWeightKg;
}
if (other.ParentPokemonId != 0) {
ParentPokemonId = other.ParentPokemonId;
}
if (other.HeightStdDev != 0F) {
HeightStdDev = other.HeightStdDev;
}
if (other.WeightStdDev != 0F) {
WeightStdDev = other.WeightStdDev;
}
if (other.KmDistanceToHatch != 0F) {
KmDistanceToHatch = other.KmDistanceToHatch;
}
if (other.FamilyId != 0) {
FamilyId = other.FamilyId;
}
if (other.CandyToEvolve != 0) {
CandyToEvolve = other.CandyToEvolve;
}
if (other.KmBuddyDistance != 0F) {
KmBuddyDistance = other.KmBuddyDistance;
}
if (other.BuddySize != 0) {
BuddySize = other.BuddySize;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
pokemonId_ = (global::POGOProtos.Enums.PokemonId) input.ReadEnum();
break;
}
case 29: {
ModelScale = input.ReadFloat();
break;
}
case 32: {
type_ = (global::POGOProtos.Enums.PokemonType) input.ReadEnum();
break;
}
case 40: {
type2_ = (global::POGOProtos.Enums.PokemonType) input.ReadEnum();
break;
}
case 50: {
if (camera_ == null) {
camera_ = new global::POGOProtos.Settings.Master.Pokemon.CameraAttributes();
}
input.ReadMessage(camera_);
break;
}
case 58: {
if (encounter_ == null) {
encounter_ = new global::POGOProtos.Settings.Master.Pokemon.EncounterAttributes();
}
input.ReadMessage(encounter_);
break;
}
case 66: {
if (stats_ == null) {
stats_ = new global::POGOProtos.Settings.Master.Pokemon.StatsAttributes();
}
input.ReadMessage(stats_);
break;
}
case 74:
case 72: {
quickMoves_.AddEntriesFrom(input, _repeated_quickMoves_codec);
break;
}
case 82:
case 80: {
cinematicMoves_.AddEntriesFrom(input, _repeated_cinematicMoves_codec);
break;
}
case 90:
case 93: {
animationTime_.AddEntriesFrom(input, _repeated_animationTime_codec);
break;
}
case 98:
case 96: {
evolutionIds_.AddEntriesFrom(input, _repeated_evolutionIds_codec);
break;
}
case 104: {
EvolutionPips = input.ReadInt32();
break;
}
case 112: {
rarity_ = (global::POGOProtos.Enums.PokemonRarity) input.ReadEnum();
break;
}
case 125: {
PokedexHeightM = input.ReadFloat();
break;
}
case 133: {
PokedexWeightKg = input.ReadFloat();
break;
}
case 136: {
parentPokemonId_ = (global::POGOProtos.Enums.PokemonId) input.ReadEnum();
break;
}
case 149: {
HeightStdDev = input.ReadFloat();
break;
}
case 157: {
WeightStdDev = input.ReadFloat();
break;
}
case 165: {
KmDistanceToHatch = input.ReadFloat();
break;
}
case 168: {
familyId_ = (global::POGOProtos.Enums.PokemonFamilyId) input.ReadEnum();
break;
}
case 176: {
CandyToEvolve = input.ReadInt32();
break;
}
case 189: {
KmBuddyDistance = input.ReadFloat();
break;
}
case 192: {
buddySize_ = (global::POGOProtos.Settings.Master.PokemonSettings.Types.BuddySize) input.ReadEnum();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the PokemonSettings message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
public enum BuddySize {
[pbr::OriginalName("BUDDY_MEDIUM")] BuddyMedium = 0,
[pbr::OriginalName("BUDDY_SHOULDER")] BuddyShoulder = 1,
[pbr::OriginalName("BUDDY_BIG")] BuddyBig = 2,
[pbr::OriginalName("BUDDY_FLYING")] BuddyFlying = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#region
using System;
using System.Collections.Generic;
using System.Linq;
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
#endregion
namespace NLog.UnitTests.LayoutRenderers
{
public class VariableLayoutRendererTests : NLogTestBase
{
[Fact]
public void Var_from_xml()
{
CreateConfigFromXml();
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=realgoodpassword", lastMessage);
}
[Fact]
public void Var_from_xml_and_edit()
{
CreateConfigFromXml();
LogManager.Configuration.Variables["password"] = "123";
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=123", lastMessage);
}
[Fact]
public void Var_with_layout_renderers()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='logger=${logger}' />
<variable name='password' value='realgoodpassword' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.Configuration.Variables["password"] = "123";
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and logger=A=123", lastMessage);
}
[Fact]
public void Var_with_other_var()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='${var:password}=' />
<variable name='password' value='realgoodpassword' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.Configuration.Variables["password"] = "123";
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and 123==123", lastMessage);
}
[Fact]
public void Var_from_api()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
LogManager.Configuration.Variables["user"] = "admin";
LogManager.Configuration.Variables["password"] = "123";
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=123", lastMessage);
}
[Fact]
public void Var_default()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='admin' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=unknown", lastMessage);
}
[Fact]
public void Var_default_after_clear()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='admin' />
<variable name='password' value='realgoodpassword' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password:default=unknown}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
LogManager.Configuration.Variables.Remove("password");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=unknown", lastMessage);
}
[Fact]
public void Var_default_after_set_null()
{
CreateConfigFromXml();
ILogger logger = LogManager.GetLogger("A");
LogManager.Configuration.Variables["password"] = null;
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=", lastMessage);
}
[Fact]
public void Var_default_after_set_emptyString()
{
CreateConfigFromXml();
ILogger logger = LogManager.GetLogger("A");
LogManager.Configuration.Variables["password"] = "";
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=", lastMessage);
}
[Fact]
public void Var_default_after_xml_emptyString()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='admin' />
<variable name='password' value='' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
var lastMessage = GetDebugLastMessage("debug");
Assert.Equal("msg and admin=", lastMessage);
}
[Fact]
public void null_should_be_ok()
{
Layout l = "${var:var1}";
LogManager.Configuration = new NLog.Config.LoggingConfiguration();
LogManager.Configuration.Variables["var1"] = null;
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("", result);
}
[Fact]
public void null_should_not_use_default()
{
Layout l = "${var:var1:default=x}";
LogManager.Configuration = new NLog.Config.LoggingConfiguration();
LogManager.Configuration.Variables["var1"] = null;
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("", result);
}
[Fact]
public void notset_should_use_default()
{
Layout l = "${var:var1:default=x}";
LogManager.Configuration = new NLog.Config.LoggingConfiguration();
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("x", result);
}
[Fact]
public void test_with_mockLogManager()
{
ILogger logger = MyLogManager.Instance.GetLogger("A");
logger.Debug("msg");
var t1 = _mockConfig.FindTargetByName<DebugTarget>("t1");
Assert.NotNull(t1);
Assert.NotNull(t1.LastMessage);
Assert.Equal("msg|my-mocking-manager", t1.LastMessage);
}
private static readonly LoggingConfiguration _mockConfig = new LoggingConfiguration();
static VariableLayoutRendererTests()
{
var t1 = new DebugTarget
{
Name = "t1",
Layout = "${message}|${var:var1:default=x}"
};
_mockConfig.AddTarget(t1);
_mockConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, t1));
_mockConfig.Variables["var1"] = "my-mocking-manager";
}
class MyLogManager
{
private static readonly LogFactory _instance = new LogFactory(_mockConfig);
public static LogFactory Instance
{
get { return _instance; }
}
}
private void CreateConfigFromXml()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name='user' value='admin' />
<variable name='password' value='realgoodpassword' />
<targets>
<target name='debug' type='Debug' layout= '${message} and ${var:user}=${var:password}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Xml;
using System.IO;
namespace T5Suite2
{
public partial class frmBrowseTunes : DevExpress.XtraEditors.XtraForm
{
public frmBrowseTunes()
{
InitializeComponent();
FetchFiles();
}
private void labelControl6_Click(object sender, EventArgs e)
{
}
public string GetPageHTML(string pageUrl, int timeoutSeconds)
{
System.Net.WebResponse response = null;
try
{
// Setup our Web request
System.Net.WebRequest request = System.Net.WebRequest.Create(pageUrl);
try
{
//request.Proxy = System.Net.WebProxy.GetDefaultProxy();
request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
catch (Exception proxyE)
{
Console.WriteLine("Error setting proxy server: " + proxyE.Message);
}
/* if (UseDefaultProxy)
{
request.Proxy = System.Net.WebProxy.GetDefaultProxy();
if (UseDefaultCredentials)
{
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
if (UseDefaultNetworkCredentials)
{
request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
}*/
request.Timeout = timeoutSeconds * 1000;
// Retrieve data from request
response = request.GetResponse();
System.IO.Stream streamReceive = response.GetResponseStream();
System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
System.IO.StreamReader streamRead = new System.IO.StreamReader(streamReceive, encoding);
// return the retrieved HTML
return streamRead.ReadToEnd();
}
catch (Exception ex)
{
// Error occured grabbing data, return empty string.
Console.WriteLine("An error occurred while retrieving the HTML content. " + ex.Message);
/*using (StreamWriter logfile = new StreamWriter("update.log", true, System.Text.Encoding.ASCII, 2048))
{
logfile.WriteLine("An error occurred while retrieving the HTML content. " + ex.Message);
logfile.Close();
}*/
return "";
}
finally
{
// Check if exists, then close the response.
if (response != null)
{
response.Close();
}
}
}
private void FetchFiles()
{
// load XML file
string URLString = "";
string XMLResult = "";
File.Delete(Application.StartupPath + "\\t5tunes.xml");
try
{
URLString = "http://trionic.mobixs.eu/t5tunes/t5tunes.xml";
XMLResult = GetPageHTML(URLString, 10);
using (StreamWriter xmlfile = new StreamWriter(Application.StartupPath + "\\t5tunes.xml", false, System.Text.Encoding.ASCII, 2048))
{
xmlfile.Write(XMLResult);
xmlfile.Close();
}
// document = downloaded
DataTable dt = new DataTable("T5TUNES");
dt.Columns.Add("Filename");
dt.Columns.Add("Carmodel");
dt.Columns.Add("Engine");
dt.Columns.Add("OBD");
dt.Columns.Add("Mapsensor");
dt.Columns.Add("Injectors");
dt.Columns.Add("stage");
dt.ReadXml(Application.StartupPath + "\\t5tunes.xml");
gridControl1.DataSource = dt;
}
catch (Exception tuE)
{
Console.WriteLine(tuE.Message);
}
}
private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
{
RefreshSelection();
}
private void RefreshSelection()
{
bool filteractive = false;
string filterstring = string.Empty;
// refresh based on current filtering
gridView1.ActiveFilter.Clear();
if (comboBoxEdit1.SelectedIndex > 0)
{
// add to filter
filteractive = true;
filterstring = @"([Carmodel] = '" + comboBoxEdit1.Text + "')";
DevExpress.XtraGrid.Columns.ColumnFilterInfo fltr = new DevExpress.XtraGrid.Columns.ColumnFilterInfo(filterstring, "Car model");
gridView1.ActiveFilter.Add(gcCarmodel, fltr);
}
if (comboBoxEdit2.SelectedIndex > 0)
{
// add to filter
filteractive = true;
filterstring = @"([Engine] = '" + comboBoxEdit2.Text + "')";
DevExpress.XtraGrid.Columns.ColumnFilterInfo fltr = new DevExpress.XtraGrid.Columns.ColumnFilterInfo(filterstring, "Engine");
gridView1.ActiveFilter.Add(gcEngine, fltr);
}
if (comboBoxEdit3.SelectedIndex > 0)
{
// add to filter
filteractive = true;
filterstring = @"([OBD] = '" + comboBoxEdit3.Text + "')";
DevExpress.XtraGrid.Columns.ColumnFilterInfo fltr = new DevExpress.XtraGrid.Columns.ColumnFilterInfo(filterstring, "OBD type");
gridView1.ActiveFilter.Add(gcOBD, fltr);
}
if (comboBoxEdit4.SelectedIndex > 0)
{
// add to filter
filteractive = true;
filterstring = @"([Mapsensor] = '" + comboBoxEdit4.Text + "')";
DevExpress.XtraGrid.Columns.ColumnFilterInfo fltr = new DevExpress.XtraGrid.Columns.ColumnFilterInfo(filterstring, "Mapsensor");
gridView1.ActiveFilter.Add(gcMapsensor, fltr);
}
if (comboBoxEdit5.SelectedIndex > 0)
{
// add to filter
filteractive = true;
filterstring = @"([Injectors] = '" + comboBoxEdit5.Text + "')";
DevExpress.XtraGrid.Columns.ColumnFilterInfo fltr = new DevExpress.XtraGrid.Columns.ColumnFilterInfo(filterstring, "Injectors");
gridView1.ActiveFilter.Add(gcInjectors, fltr);
}
if (comboBoxEdit6.SelectedIndex > 0)
{
// add to filter
filteractive = true;
filterstring = @"([stage] = '" + comboBoxEdit6.Text + "')";
DevExpress.XtraGrid.Columns.ColumnFilterInfo fltr = new DevExpress.XtraGrid.Columns.ColumnFilterInfo(filterstring, "Stage");
gridView1.ActiveFilter.Add(gcStage, fltr);
}
/*** set filter ***/
gridView1.ActiveFilterEnabled = filteractive;
}
private void simpleButton2_Click(object sender, EventArgs e)
{
string filename = string.Empty;
//filename =
int[] rows = gridView1.GetSelectedRows();
if (rows.Length > 0)
{
foreach (int rowindex in rows)
{
filename = gridView1.GetRowCellValue(rowindex, gcFilename).ToString();
DownloadFile(filename);
}
}
}
private void DownloadFile(string file)
{
string command = "http://trionic.mobixs.eu/t5tunes/" + file;
try
{
System.Diagnostics.Process.Start(command);
}
catch (Exception E)
{
//PumpString("Exception when checking new update(s): " + E.Message, false, false, new Version());
Console.WriteLine(E.Message);
}
}
private void simpleButton1_Click(object sender, EventArgs e)
{
this.Close();
}
private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if (e.FocusedRowHandle >= 0)
{
string filename = gridView1.GetRowCellValue(e.FocusedRowHandle, gcFilename).ToString();
filename += ".PNG";
pictureBox1.Load("http://trionic.mobixs.eu/t5tunes/" + filename);
string filenamehtm = gridView1.GetRowCellValue(e.FocusedRowHandle, gcFilename).ToString();
filenamehtm += ".htm";
webBrowser1.Navigate("http://trionic.mobixs.eu/t5tunes/" + filenamehtm);
}
else
{
pictureBox1.Load("http://trionic.mobixs.eu/T5Suite.jpg");
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NearestPointTest {
public static List<Vector3> convexHull = new List<Vector3>();
public static void triangulate(List<Vector3> v, List<Vector3> tri, Vector3 n) {
if (v.Count < 3) {
return;
}
if (v.Count == 3) {
triangulate3V(v[0],v[1],v[2],tri);
return;
}
if (v.Count == 4) {
triangulate4V(v[0],v[1],v[2],v[3],tri);
return;
}
convexHull.Clear();
DecalFramework.HullTests.ConvexHull2D(v,convexHull,ref n);
if (convexHull.Count < 3) {
return;
}
//tri.AddRange(convexHull);
triangulateNV(convexHull, tri);
}
/*public static void triangulateSafe(List<Vector3> v, List<Vector3> tri, Vector3 n) {
if (v.Count < 3) {
return;
}
if (v.Count == 3) {
triangulate3VSafe(v[0],v[1],v[2],tri);
return;
}
if (v.Count == 4) {
triangulate4VSafe(v[0],v[1],v[2],v[3],tri);
return;
}
convexHull.Clear();
convexHull2D(v,convexHull,n);
if (convexHull.Count < 3) {
return;
}
//tri.AddRange(convexHull);
triangulateNV(convexHull, tri);
}*/
// perform a triangle triangulation - uses barycentric coordinates to determine triangles
// returns result in CW order for triangles
public static void triangulate3V(Vector3 a, Vector3 b, Vector3 c, List<Vector3> tri) {
addTriClockwise(a, b, c, tri);
}
public static void triangulate3VSafe(Vector3 a, Vector3 b, Vector3 c, List<Vector3> tri) {
tri.Add(a);
tri.Add(b);
tri.Add(c);
}
// perform a quad triangulation - uses barycentric coordinates to determine triangles
// returns result in CW order for triangles
public static void triangulate4V(Vector3 a, Vector3 b, Vector3 c, Vector3 p, List<Vector3> tri) {
// check fouth point to see how to create indices according to barycentric coords
float bu = 0.0f;
float bv = 0.0f;
float bw = 0.0f;
DecalFramework.HullTests.Barycentric(ref a,ref b,ref c,ref p, ref bu, ref bv, ref bw);
// coordinate lies inside the triangle, quick exit, we don't need extra triangles
if (bu > 0.0f && bv > 0.0f && bw > 0.0f) {
addTriClockwise(a, b, c, tri);
return;
}
// if coordinate lies on edges, a bigger triangle exists between new point, so take that point and exit
// if true, take a-c-p discarding b
if (bu < 0.0f && bv > 0.0f && bw < 0.0f) {
addTriClockwise(a, c, p, tri);
return;
}
// if true, take a-b-p, discarding c
if (bu < 0.0f && bv < 0.0f && bw > 0.0f) {
addTriClockwise(a, b, p, tri);
return;
}
// if true, take b-c-p, discarding a
if (bu > 0.0f && bv < 0.0f && bw < 0.0f) {
addTriClockwise(b, c, p, tri);
return;
}
// coordinate needed, we will form two triangles in such a way that they don't overlap - register triangle a-b-c
addTriClockwise(a, b, c, tri);
// if true, form another triangle b-c-p and exit
if (bu < 0.0f && bv > 0.0f && bw > 0.0f) {
addTriClockwise(b, c, p, tri);
return;
}
// if true, form another triangle b-a-p and exit
if (bu > 0.0f && bv > 0.0f && bw < 0.0f) {
addTriClockwise(a, b, p, tri);
return;
}
// if true, form another triangle a-c-p and exit
if (bu > 0.0f && bv < 0.0f && bw > 0.0f) {
addTriClockwise(a, c, p, tri);
return;
}
}
public static void triangulateNV(List<Vector3> pt, List<Vector3> tri) {
Vector3 line1 = pt[0];
for (int i = 1; i < pt.Count - 1; i++) {
tri.Add(line1);
tri.Add(pt[i]);
tri.Add(pt[i + 1]);
}
}
/*public static void triangulate4VSafe(Vector3 a, Vector3 b, Vector3 c, Vector3 p, List<Vector3> tri) {
// check fouth point to see how to create indices according to barycentric coords
float bu = 0.0f;
float bv = 0.0f;
float bw = 0.0f;
barycentric(a,b,c,p, ref bu, ref bv, ref bw);
bu = Mathf.Sign(bu);
bv = Mathf.Sign(bv);
bw = Mathf.Sign(bw);
// coordinate lies inside the triangle, quick exit, we don't need extra triangles
if (bu > 0.0f && bv > 0.0f && bw > 0.0f) {
tri.Add(a);
tri.Add(b);
tri.Add(c);
return;
}
// if coordinate lies on edges, a bigger triangle exists between new point, so take that point and exit
// if true, take a-c-p discarding b
if (bu < 0.0f && bv > 0.0f && bw < 0.0f) {
tri.Add(a);
tri.Add(c);
tri.Add(p);
return;
}
// if true, take a-b-p, discarding c
if (bu < 0.0f && bv < 0.0f && bw > 0.0f) {
tri.Add(a);
tri.Add(b);
tri.Add(p);
return;
}
// if true, take b-c-p, discarding a
if (bu > 0.0f && bv < 0.0f && bw < 0.0f) {
tri.Add(a);
tri.Add(c);
tri.Add(p);
return;
}
// coordinate needed, we will form two triangles in such a way that they don't overlap - register triangle a-b-c
tri.Add(a);
tri.Add(b);
tri.Add(c);
// if true, form another triangle b-c-p and exit
if (bu < 0.0f && bv > 0.0f && bw > 0.0f) {
tri.Add(b);
tri.Add(c);
tri.Add(p);
return;
}
// if true, form another triangle b-a-p and exit
if (bu > 0.0f && bv > 0.0f && bw < 0.0f) {
tri.Add(a);
tri.Add(b);
tri.Add(p);
return;
}
// if true, form another triangle a-c-p and exit
if (bu > 0.0f && bv < 0.0f && bw > 0.0f) {
tri.Add(a);
tri.Add(c);
tri.Add(p);
return;
}
}/*
public static void triangulateNV(List<Vector3> pt, List<Vector3> tri) {
Vector3 line1 = pt[0];
for (int i = 1; i < pt.Count - 1; i++) {
tri.Add(line1);
tri.Add(pt[i]);
tri.Add(pt[i + 1]);
}
}
/*public static void mapPlanar3D2D(List<Vector3> p3, List<Vector2> p2, Vector3 n) {
Vector3 r = Mathf.Abs(n.x) > Mathf.Abs(n.y) ? r = new Vector3(0,1,0) : r = new Vector3(1,0,0);
Vector3 v = Vector3.Normalize(Vector3.Cross(r,n));
Vector3 u = Vector3.Cross(n,v);
for (int i = 0; i < p3.Count; i++) {
p2.Add(new Vector2(Vector3.Dot(p3[i],u), Vector3.Dot(p3[i], v)));
}
}*/
/*public static Vector2 cubeMap3DV(Vector3 vec, Vector3 n) {
Vector3 r = Mathf.Abs(n.x) > Mathf.Abs(n.y) ? r = new Vector3(0,1,0) : r = new Vector3(1,0,0);
Vector3 v = Vector3.Normalize(Vector3.Cross(r,n));
Vector3 u = Vector3.Cross(n,v);
return new Vector2((Vector3.Dot(vec,u) + 1) / 2, (Vector3.Dot(vec,v) + 1) / 2);
}
private static List<Vector2> genUV = new List<Vector2>();
private static List<MapPoint2D> genUVM = new List<MapPoint2D>();*/
/*public static List<Vector2> genUVFromVertex(List<Vector3> vertices, Vector3 n) {
genUV.Clear();
genUVM.Clear();
mapPlanar3D2D(vertices, genUVM, n);
// we now have 2D points, lets generate our UV coordinates
// find the largest point in either X or Y coordinate to bring everything back to UV space
float divX = 1.0f;
float divY = 1.0f;
for (int i = 0; i < genUVM.Count; i++) {
if (genUVM[i].map.x > divX) {
divX = genUVM[i].map.x;
}
if (genUVM[i].map.y > divY) {
divY = genUVM[i].map.y;
}
}
divX = (divX + 1 / 2);
divY = (divY + 1 / 2);
// now its a simple manner, U = x / div, V = y / div
for (int i = 0; i < genUVM.Count; i++) {
genUV.Add(new Vector2(genUVM[i].map.x / divX - 0.5f, genUVM[i].map.y / divY - 0.5f));
}
// each UV maps to its respective 3D coordinate
return genUV;
}*/
/*public static float cross2D(MapPoint2D O, MapPoint2D A, MapPoint2D B) {
return (A.Map.x - O.Map.x) * (B.Map.y - O.Map.y) - (A.Map.y - O.Map.y) * (B.Map.x - O.Map.x);
}*/
// check if triangle specified by a-b-c is clockwise. true if so, false otherwise
public static bool isTriClockwise(Vector3 a, Vector3 b, Vector3 c) {
return (a.x * (b.y * c.z - b.z * c.y) - a.y * (b.x * c.z - b.z * c.x) + a.z * (b.x * c.y - b.y * c.x)) >= 0;
}
public static bool isTriClockwise(Vector3 a, Vector3 b, Vector3 c, Vector3 normal) {
Vector3 n = Vector3.Cross(b - a, c - a);
//n.Normalize();
//Debug.Log(Vector3.Dot(normal,n));
return Vector3.Dot(normal,n) >= 0;
}
/*public static float triArea3D(Vector3 a, Vector3 b, Vector3 c) {
return Vector3.Cross(a - b, a - c).magnitude * 0.5f;
}*/
public static void addTriClockwise(Vector3 a, Vector3 b, Vector3 c, List<Vector3> tri) {
if (isTriClockwise(a,b,c)) {
tri.Add(a);
tri.Add(b);
tri.Add(c);
}
else {
tri.Add(a);
tri.Add(c);
tri.Add(b);
}
}
// helper function
/*public static bool pointOutsideOfPlane(Vector3 p, Vector3 a, Vector3 b, Vector3 c) {
return Vector3.Dot(p - a, Vector3.Cross(b - a, c - a)) >= 0.0f;
}*/
public static bool valueWithinRange(float a, float b, float c) {
return b > a ? c > a && c < b : c > b && c < a;
}
// this function will test to see if pt is approximetly equal to any of the points in points
// according to some tolerance value, if so, true is returned and index is stored in a reference
// otherwise it is added and index is stored while returning false
public static bool approxContains(List<Vector3> points, Vector3 pt, float tol, ref int index) {
//Debug.Log("PASS");
float tolSQ = (tol * tol);
for (int i = 0; i < points.Count; i++) {
if (Vector3.SqrMagnitude(points[i] - pt) <= tolSQ) {
//Debug.Log("SQR: " + Vector3.SqrMagnitude(points[i] - pt) + " PT: " + tolSQ);
// found a vector, store index and return true
points[i] = (points[i] + pt) / 2;
index = i;
return true;
}
}
// nothing found, return false
points.Add(pt);
index = points.Count - 1;
return false;
}
// this function will test to see if pt is approximetly equal to any of the points in points
// according to some tolerance value, if so, true is returned and index is stored in a reference
// otherwise it is added and index is stored while returning false
public static bool approxContainsSafe(List<Vector3> points, Vector3 pt, float tol, ref int index) {
//Debug.Log("PASS");
float tolSQ = (tol * tol);
for (int i = 0; i < points.Count; i++) {
if (Vector3.SqrMagnitude(points[i] - pt) <= tolSQ) {
//Debug.Log("SQR: " + Vector3.SqrMagnitude(points[i] - pt) + " PT: " + tolSQ);
// found a vector, store index and return true
index = i;
return true;
}
}
// nothing found, return false
return false;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Web.Script.Serialization;
// Note: To enable JSON (JavaScriptSerializer) add following reference: System.Web.Extensions
namespace PositionPolling
{
public class hftRequest
{
public getAuthorizationChallengeRequest getAuthorizationChallenge { get; set; }
public getAuthorizationTokenRequest getAuthorizationToken { get; set; }
public getPositionRequest getPosition { get; set; }
}
public class hftResponse
{
public getAuthorizationChallengeResponse getAuthorizationChallengeResponse { get; set; }
public getAuthorizationTokenResponse getAuthorizationTokenResponse { get; set; }
public getPositionResponse getPositionResponse { get; set; }
}
public class getAuthorizationChallengeRequest
{
public string user { get; set; }
public getAuthorizationChallengeRequest(String user)
{
this.user = user;
}
}
public class getAuthorizationChallengeResponse
{
public string challenge { get; set; }
public string timestamp { get; set; }
}
public class getAuthorizationTokenRequest
{
public string user { get; set; }
public string challengeresp { get; set; }
public getAuthorizationTokenRequest(String user, String challengeresp)
{
this.user = user;
this.challengeresp = challengeresp;
}
}
public class getAuthorizationTokenResponse
{
public string token { get; set; }
public string timestamp { get; set; }
}
public class getPositionRequest
{
public string user { get; set; }
public string token { get; set; }
public List<string> asset { get; set; }
public List<string> security { get; set; }
public List<string> account { get; set; }
public getPositionRequest(string user, string token, List<string> asset, List<string> security, List<string> account)
{
this.user = user;
this.token = token;
this.asset = asset;
this.security = security;
this.account = account;
}
}
public class getPositionResponse
{
public int result { get; set; }
public string message { get; set; }
public List<assetPositionTick> assetposition { get; set; }
public List<securityPositionTick> securityposition { get; set; }
public accountingTick accounting { get; set; }
public positionHeartbeat heartbeat { get; set; }
public string timestamp { get; set; }
}
public class assetPositionTick
{
public string account { get; set; }
public string asset { get; set; }
public double exposure { get; set; }
public double totalrisk { get; set; }
public double pl { get; set; }
}
public class securityPositionTick
{
public string account { get; set; }
public string security { get; set; }
public double exposure { get; set; }
public string side { get; set; }
public double price { get; set; }
public int pips { get; set; }
public double equity { get; set; }
public double freemargin { get; set; }
public double pl { get; set; }
}
public class accountingTick
{
public double strategyPL { get; set; }
public double totalequity { get; set; }
public double usedmargin { get; set; }
public double freemargin { get; set; }
public string m2mcurrency { get; set; }
}
public class positionHeartbeat
{
public List<string> asset { get; set; }
public List<string> security { get; set; }
public List<string> account { get; set; }
}
class PositionPolling
{
private static bool ssl = true;
private static String URL = "/getPosition";
private static String domain;
//private static String url_stream;
private static String url_polling;
private static String url_challenge;
private static String url_token;
private static String user;
private static String password;
private static String authentication_port;
private static String request_port;
private static String ssl_cert;
private static String challenge;
private static String token;
//private static int interval;
public static void Exec()
{
// get properties from file
getProperties();
HttpWebRequest httpWebRequest;
JavaScriptSerializer serializer;
HttpWebResponse httpResponse;
X509Certificate certificate1 = null;
if (ssl)
{
using (WebClient client = new WebClient())
{
client.DownloadFile(ssl_cert, "ssl.cert");
}
certificate1 = new X509Certificate("ssl.cert");
}
// get challenge
httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_challenge);
serializer = new JavaScriptSerializer();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (ssl)
{
httpWebRequest.ClientCertificates.Add(certificate1);
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
hftRequest request = new hftRequest();
request.getAuthorizationChallenge = new getAuthorizationChallengeRequest(user);
streamWriter.WriteLine(serializer.Serialize(request));
}
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
hftResponse response;
try
{
response = serializer.Deserialize<hftResponse>(streamReader.ReadLine());
challenge = response.getAuthorizationChallengeResponse.challenge;
}
catch (SocketException ex) { Console.WriteLine(ex.Message); }
catch (IOException ioex) { Console.WriteLine(ioex.Message); }
}
// create challenge response
String res = challenge;
char[] passwordArray = password.ToCharArray();
foreach (byte passwordLetter in passwordArray)
{
int value = Convert.ToInt32(passwordLetter);
string hexOutput = String.Format("{0:X}", value);
res = res + hexOutput;
}
int NumberChars = res.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(res.Substring(i, 2), 16);
}
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] tokenArray = sha.ComputeHash(bytes);
string challengeresp = BitConverter.ToString(tokenArray);
challengeresp = challengeresp.Replace("-", "");
// get token with challenge response
httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_token);
serializer = new JavaScriptSerializer();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (ssl)
{
httpWebRequest.ClientCertificates.Add(certificate1);
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
hftRequest request = new hftRequest();
request.getAuthorizationToken = new getAuthorizationTokenRequest(user, challengeresp);
streamWriter.WriteLine(serializer.Serialize(request));
}
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
hftResponse response;
try
{
response = serializer.Deserialize<hftResponse>(streamReader.ReadLine());
token = response.getAuthorizationTokenResponse.token;
}
catch (SocketException ex) { Console.WriteLine(ex.Message); }
catch (IOException ioex) { Console.WriteLine(ioex.Message); }
}
// -----------------------------------------
// Prepare and send a position request
// -----------------------------------------
httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + request_port + url_polling + URL);
serializer = new JavaScriptSerializer();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (ssl)
{
httpWebRequest.ClientCertificates.Add(certificate1);
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
hftRequest request = new hftRequest();
request.getPosition = new getPositionRequest(user, token, null, new List<string> { "EUR/USD", "GBP/USD" }, null);
streamWriter.WriteLine(serializer.Serialize(request));
}
// --------------------------------------------------------------
// Wait for response from server (polling)
// --------------------------------------------------------------
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
hftResponse response;
String line;
try
{
while ((line = streamReader.ReadLine()) != null)
{
response = serializer.Deserialize<hftResponse>(line);
if (response.getPositionResponse != null)
{
if (response.getPositionResponse.timestamp != null)
{
Console.WriteLine("Response timestamp: " + response.getPositionResponse.timestamp + " Contents:");
}
if (response.getPositionResponse.accounting != null)
{
accountingTick tick = response.getPositionResponse.accounting;
Console.WriteLine("m2mcurrency: " + tick.m2mcurrency + " StrategyPL: " + tick.strategyPL + " TotalEquity: " + tick.totalequity + " UsedMargin: " + tick.usedmargin + " FreeMargin: " + tick.freemargin);
}
if (response.getPositionResponse.assetposition != null)
{
foreach (assetPositionTick tick in response.getPositionResponse.assetposition)
{
Console.WriteLine("Asset: " + tick.asset + " Account: " + tick.account + " Exposure: " + tick.exposure + " PL: " + tick.pl);
}
}
if (response.getPositionResponse.securityposition != null)
{
foreach (securityPositionTick tick in response.getPositionResponse.securityposition)
{
Console.WriteLine("Security: " + tick.security + " Account: " + tick.account + " Exposure: " + tick.exposure + " Price: " + tick.price + " Pips: " + tick.pips + " PL: " + tick.pl);
}
}
if (response.getPositionResponse.heartbeat != null)
{
Console.WriteLine("Heartbeat!");
}
if (response.getPositionResponse.message != null)
{
Console.WriteLine("Message from server: " + response.getPositionResponse.message);
}
}
}
}
catch (SocketException ex) { Console.WriteLine(ex.Message); }
catch (IOException ioex) { Console.WriteLine(ioex.Message); }
}
}
private static void getProperties()
{
try
{
foreach (var row in File.ReadAllLines("config.properties"))
{
//Console.WriteLine(row);
/*
if ("url-stream".Equals(row.Split('=')[0]))
{
url_stream = row.Split('=')[1];
}
*/
if ("url-polling".Equals(row.Split('=')[0]))
{
url_polling = row.Split('=')[1];
}
if ("url-challenge".Equals(row.Split('=')[0]))
{
url_challenge = row.Split('=')[1];
}
if ("url-token".Equals(row.Split('=')[0]))
{
url_token = row.Split('=')[1];
}
if ("user".Equals(row.Split('=')[0]))
{
user = row.Split('=')[1];
}
if ("password".Equals(row.Split('=')[0]))
{
password = row.Split('=')[1];
}
/*
if ("interval".Equals(row.Split('=')[0]))
{
interval = Int32.Parse(row.Split('=')[1]);
}
*/
if (ssl)
{
if ("ssl-domain".Equals(row.Split('=')[0]))
{
domain = row.Split('=')[1];
}
if ("ssl-authentication-port".Equals(row.Split('=')[0]))
{
authentication_port = row.Split('=')[1];
}
if ("ssl-request-port".Equals(row.Split('=')[0]))
{
request_port = row.Split('=')[1];
}
if ("ssl-cert".Equals(row.Split('=')[0]))
{
ssl_cert = row.Split('=')[1];
}
}
else
{
if ("domain".Equals(row.Split('=')[0]))
{
domain = row.Split('=')[1];
}
if ("authentication-port".Equals(row.Split('=')[0]))
{
authentication_port = row.Split('=')[1];
}
if ("request-port".Equals(row.Split('=')[0]))
{
request_port = row.Split('=')[1];
}
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using EasyApi.Utils;
namespace EasyApi.Storages
{
public class Storage<TKey> : IStorage<TKey>, IDestroyableStorage
{
private const int MaxGetOrSetAttemptCount = 100;
private static Exception StorageDestroyedException()
{
return new InvalidOperationException("Storage is destroyed.");
}
private readonly ConcurrentDictionary<TKey, ExpirableEntry> _items;
private readonly AtomicFlag _isDestroyed;
public Storage(IEqualityComparer<TKey> keyComparer)
{
Argument.IsNotNull(keyComparer, nameof(keyComparer));
_items = new ConcurrentDictionary<TKey, ExpirableEntry>(keyComparer);
_isDestroyed = new AtomicFlag();
}
public Storage()
: this(EqualityComparer<TKey>.Default)
{
}
private void EnsureIsNotDestroyed()
{
if (_isDestroyed)
{
throw StorageDestroyedException();
}
}
public bool TryGetValue<TValue>(TKey key, out TValue value)
{
Argument.IsNotNull(key, nameof(key));
EnsureIsNotDestroyed();
if (_items.TryGetValue(key, out var entry))
{
return entry.TryGetValue(out value);
}
value = default;
return false;
}
private void RemoveEntry(object key, ExpirableEntry entry)
{
((ICollection<KeyValuePair<TKey, ExpirableEntry>>)_items).Remove(new KeyValuePair<TKey, ExpirableEntry>((TKey)key, entry));
}
private ExpirableEntry CreateEntry(TKey key, object value, IEntryExpirationStrategy expirationStrategy, IRemovedEntryHandler removedEntryHandler)
{
return new ExpirableEntry(value, key, RemoveEntry, expirationStrategy, removedEntryHandler);
}
public void SetValue<TValue>(TKey key, TValue value, IEntryExpirationStrategy expirationStrategy, IRemovedEntryHandler removedEntryHandler)
{
Argument.IsNotNull(key, nameof(key));
Argument.IsNotNull(expirationStrategy, nameof(expirationStrategy));
Argument.IsNotNull(removedEntryHandler, nameof(removedEntryHandler));
EnsureIsNotDestroyed();
var newEntry = CreateEntry(key, value, expirationStrategy, removedEntryHandler);
ExpirableEntry oldEntry = null;
bool? valueUpdated = null;
_items.AddOrUpdate(
key,
k =>
{
valueUpdated = false;
return newEntry;
},
(k, entry) =>
{
oldEntry = entry;
valueUpdated = true;
return newEntry;
}
);
if (valueUpdated == true && oldEntry != null)
{
oldEntry.Remove(EntryRemovalReason.Overridden);
}
if (_isDestroyed)
{
newEntry.Remove(EntryRemovalReason.Destroyed);
throw StorageDestroyedException();
}
}
public TValue GetOrSet<TValue>(TKey key, Func<TKey, TValue> valueFactory, IEntryExpirationStrategy expirationStrategy, IRemovedEntryHandler removedEntryHandler)
{
Argument.IsNotNull(key, nameof(key));
Argument.IsNotNull(valueFactory, nameof(valueFactory));
Argument.IsNotNull(expirationStrategy, nameof(expirationStrategy));
Argument.IsNotNull(removedEntryHandler, nameof(removedEntryHandler));
EnsureIsNotDestroyed();
TValue value;
ExpirableEntry entry;
var iterationCount = 0;
do
{
if (iterationCount++ > MaxGetOrSetAttemptCount)
{
throw new InvalidOperationException("Generated value is always expired. Try to check the specified expiration strategy.")
.SetData("StringifiedKey", key.ToString())
.SetData("ExpirationStrategyType", expirationStrategy.GetType().FullName);
}
ExpirableEntry createdEntry = null;
entry = _items.GetOrAdd(key, k =>
{
createdEntry = CreateEntry(k, valueFactory(k), expirationStrategy, removedEntryHandler);
return createdEntry;
});
if (createdEntry != null && createdEntry != entry)
{
createdEntry.Remove(EntryRemovalReason.Overridden);
}
} while (!entry.TryGetValue(out value));
if (_isDestroyed)
{
entry.Remove(EntryRemovalReason.Destroyed);
throw StorageDestroyedException();
}
return value;
}
public bool Contains(TKey key)
{
Argument.IsNotNull(key, nameof(key));
EnsureIsNotDestroyed();
return _items.TryGetValue(key, out var entry) && entry.HasValue();
}
public bool TryRemove(TKey key)
{
Argument.IsNotNull(key, nameof(key));
EnsureIsNotDestroyed();
if (_items.TryRemove(key, out var entry))
{
return entry.Remove(EntryRemovalReason.Removed);
}
return false;
}
public void Destroy()
{
if (_isDestroyed.TrySet())
{
var entries = _items.Values.ToArray();
_items.Clear();
foreach (var entry in entries)
{
entry.Remove(EntryRemovalReason.Destroyed);
}
}
}
public int Count
{
get
{
var count = _items.Count;
EnsureIsNotDestroyed();
return count;
}
}
public IReadOnlyCollection<TKey> Keys
{
get
{
var result = _items.Keys.ToArray();
EnsureIsNotDestroyed();
return result;
}
}
}
}
| |
// ------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------
using Amqp;
using Amqp.Framing;
using Amqp.Types;
using System;
using System.Text;
using System.Threading;
using Amqp.Handler;
#if NETFX || NETFX35 || DOTNET
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#endif
namespace Test.Amqp
{
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestClass]
#endif
public class LinkTests
{
TestTarget testTarget = new TestTarget();
static LinkTests()
{
Connection.DisableServerCertValidation = true;
// uncomment the following to write frame traces
//Trace.TraceLevel = TraceLevel.Frame;
//Trace.TraceListener = (l, f, a) => System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_BasicSendReceive()
{
string testName = "BasicSendReceive";
const int nMsgs = 200;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message("msg" + i);
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_InterfaceSendReceive()
{
string testName = "InterfaceSendReceive";
const int nMsgs = 200;
IConnection connection = new Connection(testTarget.Address);
ISession session = connection.CreateSession();
ISenderLink sender = session.CreateSender("sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message("msg" + i);
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_InterfaceSendReceiveOnAttach()
{
string testName = "InterfaceSendReceiveOnAttach";
const int nMsgs = 200;
int nAttaches = 0;
OnAttached onAttached = (link, attach) => {
nAttaches++;
};
IConnection connection = new Connection(testTarget.Address);
ISession session = connection.CreateSession();
ISenderLink sender = session.CreateSender("sender-" + testName, new Target() { Address = testTarget.Path }, onAttached);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message("msg" + i);
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, new Source() { Address = testTarget.Path }, onAttached);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
Assert.AreEqual(2, nAttaches);
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_MessageDeliveryAccept()
{
string testName = "MessageDeliveryAccept";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message message = new Message("msg accept");
sender.Send(message, null, null);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
message = receiver.Receive();
MessageDelivery messageDelivery = message.GetDelivery();
message.Dispose();
receiver.Accept(messageDelivery);
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_MessageDeliveryRelease()
{
string testName = "MessageDeliveryRelease";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message message = new Message("msg release");
sender.Send(message, null, null);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
message = receiver.Receive();
MessageDelivery messageDelivery = message.GetDelivery();
message.Dispose();
receiver.Release(messageDelivery);
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_MessageDeliveryReject()
{
string testName = "MessageDeliveryReject";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message message = new Message("msg reject");
sender.Send(message, null, null);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
message = receiver.Receive();
MessageDelivery messageDelivery = message.GetDelivery();
message.Dispose();
receiver.Reject(messageDelivery);
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_MessageDeliveryModify()
{
string testName = "MessageDeliveryModify";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message message = new Message("msg modify");
sender.Send(message, null, null);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
message = receiver.Receive();
MessageDelivery messageDelivery = message.GetDelivery();
message.Dispose();
receiver.Modify(messageDelivery, true);
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_MessageDeliveryResend()
{
string testName = "MessageDeliveryResend";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message message = new Message("msg resend");
sender.Send(message, null, null);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
message = receiver.Receive();
MessageDelivery messageDelivery = message.GetDelivery();
message.Properties = new Properties() { GroupId = "abcdefg" };
sender.Send(message, null, null);
message.Dispose();
receiver.Accept(messageDelivery);
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionFrameSize()
{
string testName = "ConnectionFrameSize";
const int nMsgs = 200;
int frameSize = 4 * 1024;
Connection connection = new Connection(testTarget.Address, null, new Open() { ContainerId = "c1", MaxFrameSize = (uint)frameSize }, null);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message(new string('A', frameSize + (i - nMsgs / 2)));
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
string value = (string)message.Body;
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}x{1}", value[0], value.Length);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionChannelMax()
{
ushort channelMax = 5;
Connection connection = new Connection(
testTarget.Address,
null,
new Open() { ContainerId = "ConnectionChannelMax", HostName = testTarget.Address.Host, ChannelMax = channelMax },
(c, o) => Trace.WriteLine(TraceLevel.Verbose, "{0}", o));
for (int i = 0; i <= channelMax; i++)
{
Session session = new Session(connection);
}
try
{
Session session = new Session(connection);
Fx.Assert(false, "Created more sessions than allowed.");
}
catch (AmqpException exception)
{
Fx.Assert(exception.Error.Condition.Equals((Symbol)ErrorCode.NotAllowed), "Wrong error code");
}
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionWithIPAddress()
{
string testName = "ConnectionWithIPAddress";
const int nMsgs = 20;
// If the test target is 'localhost' then verify that '127.0.0.1' also works.
if (testTarget.Address.Host != "localhost")
{
Trace.WriteLine(TraceLevel.Verbose,
"Test {0} skipped. Test target '{1}' is not 'localhost'.",
testName, testTarget.Address.Host);
return;
}
Address address2 = new Address("127.0.0.1", testTarget.Address.Port,
testTarget.Address.User, testTarget.Address.Password,
testTarget.Address.Path, testTarget.Address.Scheme);
Connection connection = new Connection(address2);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message("msg" + i);
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionRemoteProperties()
{
string testName = "ConnectionRemoteProperties";
ManualResetEvent opened = new ManualResetEvent(false);
Open remoteOpen = null;
OnOpened onOpen = (c, o) =>
{
remoteOpen = o;
opened.Set();
};
Open open = new Open()
{
ContainerId = testName,
Properties = new Fields() { { new Symbol("p1"), "abcd" } },
DesiredCapabilities = new Symbol[] { new Symbol("dc1"), new Symbol("dc2") },
OfferedCapabilities = new Symbol[] { new Symbol("oc") }
};
Connection connection = new Connection(testTarget.Address, null, open, onOpen);
opened.WaitOne(10000);
connection.Close();
Assert.IsTrue(remoteOpen != null, "remote open not set");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_OnMessage()
{
string testName = "OnMessage";
const int nMsgs = 200;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
ManualResetEvent done = new ManualResetEvent(false);
int received = 0;
receiver.Start(10, (link, m) =>
{
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", m.ApplicationProperties["sn"]);
link.Accept(m);
received++;
if (received == nMsgs)
{
done.Set();
}
});
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message()
{
BodySection = new Data() { Binary = Encoding.UTF8.GetBytes("msg" + i) }
};
message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
int last = -1;
while (!done.WaitOne(10000) && received > last)
{
last = received;
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
Assert.AreEqual(nMsgs, received, "not all messages are received.");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_CloseBusyReceiver()
{
string testName = "CloseBusyReceiver";
const int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
ManualResetEvent closed = new ManualResetEvent(false);
receiver.Closed += (o, e) => closed.Set();
receiver.Start(
nMsgs,
(r, m) =>
{
if (m.Properties.MessageId == "msg0") r.Close(TimeSpan.Zero, null);
});
Assert.IsTrue(closed.WaitOne(10000));
ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver2.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
receiver2.Accept(message);
}
receiver2.Close();
sender.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReleaseMessage()
{
string testName = "ReleaseMessage";
const int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
if (i % 2 == 0)
{
receiver.Accept(message);
}
else
{
receiver.Release(message);
}
}
receiver.Close();
ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs / 2; ++i)
{
Message message = receiver2.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
receiver2.Accept(message);
}
receiver2.Close();
sender.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ModifyMessage()
{
string testName = "ModifyMessage";
const int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.MessageAnnotations = new MessageAnnotations();
message.MessageAnnotations[(Symbol)"a1"] = 12345L;
message.Properties = new Properties() { MessageId = "msg" + i };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
if (i % 2 == 0)
{
receiver.Accept(message);
}
else
{
receiver.Modify(message, true, false, new Fields() { { (Symbol)"reason", "app offline" } });
}
}
receiver.Close();
ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs / 2; ++i)
{
Message message = receiver2.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
Assert.IsTrue(message.Header != null, "header is null");
Assert.IsTrue(message.Header.DeliveryCount > 0, "delivery-count is 0");
Assert.IsTrue(message.MessageAnnotations != null, "annotation is null");
Assert.IsTrue(message.MessageAnnotations[(Symbol)"a1"].Equals(12345L));
Assert.IsTrue(message.MessageAnnotations[(Symbol)"reason"].Equals("app offline"));
receiver2.Accept(message);
}
receiver2.Close();
sender.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SendAck()
{
string testName = "SendAck";
const int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
ManualResetEvent done = new ManualResetEvent(false);
OutcomeCallback callback = (l, m, o, s) =>
{
Trace.WriteLine(TraceLevel.Verbose, "send complete: sn {0} outcome {1}", m.ApplicationProperties["sn"], o.Descriptor.Name);
if ((int)m.ApplicationProperties["sn"] == (nMsgs - 1))
{
done.Set();
}
};
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, callback, null);
}
done.WaitOne(10000);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_MessageId()
{
string testName = "MessageId";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
object[] idList = new object[] { null, "string-id", 20000UL, Guid.NewGuid(), Encoding.UTF8.GetBytes("binary-id") };
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < idList.Length; ++i)
{
Message message = new Message() { Properties = new Properties() };
message.Properties.SetMessageId(idList[i]);
message.Properties.SetCorrelationId(idList[(i + 2) % idList.Length]);
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < idList.Length; ++i)
{
Message message = receiver.Receive();
receiver.Accept(message);
Assert.AreEqual(idList[i], message.Properties.GetMessageId());
Assert.AreEqual(idList[(i + 2) % idList.Length], message.Properties.GetCorrelationId());
}
connection.Close();
// invalid types
Properties prop = new Properties();
try
{
prop.SetMessageId(0);
Assert.IsTrue(false, "not a valid identifier type");
}
catch (AmqpException ae)
{
Assert.AreEqual(ErrorCode.NotAllowed, (string)ae.Error.Condition);
}
try
{
prop.SetCorrelationId(new Symbol("symbol"));
Assert.IsTrue(false, "not a valid identifier type");
}
catch (AmqpException ae)
{
Assert.AreEqual(ErrorCode.NotAllowed, (string)ae.Error.Condition);
}
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReceiveWaiter()
{
string testName = "ReceiveWaiter";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
ManualResetEvent gotMessage = new ManualResetEvent(false);
StartThread(() =>
{
Message message = receiver.Receive(TimeSpan.MaxValue);
if (message != null)
{
receiver.Accept(message);
gotMessage.Set();
}
});
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message msg = new Message() { Properties = new Properties() { MessageId = "123456" } };
sender.Send(msg, null, null);
Assert.IsTrue(gotMessage.WaitOne(5000), "No message was received");
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReceiveDrain()
{
string testName = "ReceiveDrain";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message msg = new Message() { Properties = new Properties() { MessageId = "12345" } };
sender.Send(msg);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
receiver.SetCredit(2, CreditMode.Drain);
msg = receiver.Receive();
Assert.IsTrue(msg != null);
msg = new Message() { Properties = new Properties() { MessageId = "67890" } };
sender.Send(msg);
msg = receiver.Receive(TimeSpan.FromTicks(600 * TimeSpan.TicksPerMillisecond));
Assert.IsTrue(msg == null);
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReceiveReceiveSend()
{
string testName = "ReceiveReceiveSend";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
Message msg = receiver.Receive(TimeSpan.FromTicks(500 * TimeSpan.TicksPerMillisecond));
Assert.IsTrue(msg == null);
receiver.Close();
session.Close();
session = new Session(connection);
receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
msg = receiver.Receive(TimeSpan.FromTicks(500 * TimeSpan.TicksPerMillisecond));
Assert.IsTrue(msg == null);
Connection connection2 = new Connection(testTarget.Address);
Session session2 = new Session(connection2);
SenderLink sender = new SenderLink(session2, "sender-" + testName, testTarget.Path);
msg = new Message() { Properties = new Properties() { MessageId = "12345" } };
sender.Send(msg);
msg = receiver.Receive(TimeSpan.FromTicks(6000 * TimeSpan.TicksPerMillisecond));
Assert.IsTrue(msg != null);
receiver.Accept(msg);
connection2.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReceiveWaiterZero()
{
string testName = "ReceiveWaiterZero";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
Message msg = receiver.Receive(TimeSpan.Zero);
Assert.IsTrue(msg == null);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
msg = new Message() { Properties = new Properties() { MessageId = "123456" } };
sender.Send(msg, null, null);
for (int i = 0; i < 1000; i++)
{
msg = receiver.Receive(TimeSpan.Zero);
if (msg != null)
{
receiver.Accept(msg);
break;
}
#if NETFX_CORE
System.Threading.Tasks.Task.Delay(10).Wait();
#else
Thread.Sleep(10);
#endif
}
Assert.IsTrue(msg != null, "Message not received");
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReceiveWithFilter()
{
string testName = "ReceiveWithFilter";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
Message message = new Message("I can match a filter");
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = 100;
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
sender.Send(message, null, null);
// update the filter descriptor and expression according to the broker
Map filters = new Map();
// JMS selector filter: code = 0x0000468C00000004L, symbol="apache.org:selector-filter:string"
filters.Add(new Symbol("f1"), new DescribedValue(new Symbol("apache.org:selector-filter:string"), "sn = 100"));
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Address = testTarget.Path, FilterSet = filters }, null);
Message message2 = receiver.Receive();
receiver.Accept(message2);
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_LinkCloseWithSettledSend()
{
string testName = "LinkCloseWithSettledSend";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message message = new Message(testName);
sender.Send(message, null, null);
sender.Close();
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
message = receiver.Receive(new TimeSpan(0, 0, 10));
Assert.IsTrue(message != null, "no message was received.");
receiver.Accept(message);
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SynchronousSend()
{
string testName = "SynchronousSend";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
Message message = new Message("hello");
sender.Send(message);
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
message = receiver.Receive();
Assert.IsTrue(message != null, "no message was received.");
receiver.Accept(message);
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_DynamicSenderLink()
{
string testName = "DynamicSenderLink";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
string targetAddress = null;
OnAttached onAttached = (link, attach) =>
{
targetAddress = ((Target)attach.Target).Address;
};
SenderLink sender = new SenderLink(session, "sender-" + testName, new Target() { Dynamic = true }, onAttached);
Message message = new Message("hello");
sender.Send(message);
Assert.IsTrue(targetAddress != null, "dynamic target not attached");
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, targetAddress);
message = receiver.Receive();
Assert.IsTrue(message != null, "no message was received.");
receiver.Accept(message);
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_DynamicReceiverLink()
{
string testName = "DynamicReceiverLink";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
string remoteSource = null;
ManualResetEvent attached = new ManualResetEvent(false);
OnAttached onAttached = (link, attach) => { remoteSource = ((Source)attach.Source).Address; attached.Set(); };
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Dynamic = true }, onAttached);
attached.WaitOne(10000);
Assert.IsTrue(remoteSource != null, "dynamic source not attached");
SenderLink sender = new SenderLink(session, "sender-" + testName, remoteSource);
Message message = new Message("hello");
sender.Send(message);
message = receiver.Receive();
Assert.IsTrue(message != null, "no message was received.");
receiver.Accept(message);
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_RequestResponse()
{
string testName = "RequestResponse";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
// server app: the request handler
ReceiverLink requestLink = new ReceiverLink(session, "srv.requester-" + testName, testTarget.Path);
requestLink.Start(10, (l, m) =>
{
l.Accept(m);
// got a request, send back a reply
SenderLink sender = new SenderLink(session, "srv.replier-" + testName, m.Properties.ReplyTo);
Message reply = new Message("received");
reply.Properties = new Properties() { CorrelationId = m.Properties.MessageId };
sender.Send(reply, (a, b, c, d) => ((Link)a).Close(TimeSpan.Zero), sender);
});
// client: setup a temp queue and waits for responses
OnAttached onAttached = (l, at) =>
{
// client: sends a request to the request queue, specifies the temp queue as the reply queue
SenderLink sender = new SenderLink(session, "cli.requester-" + testName, testTarget.Path);
Message request = new Message("hello");
request.Properties = new Properties() { MessageId = "request1", ReplyTo = ((Source)at.Source).Address };
sender.Send(request, (a, b, c, d) => ((Link)a).Close(TimeSpan.Zero), sender);
};
ReceiverLink responseLink = new ReceiverLink(session, "cli.responder-" + testName, new Source() { Dynamic = true }, onAttached);
Message response = responseLink.Receive();
Assert.IsTrue(response != null, "no response was received");
responseLink.Accept(response);
requestLink.Close();
responseLink.Close();
session.Close();
connection.Close();
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_AdvancedLinkFlowControl()
{
string testName = "AdvancedLinkFlowControl";
int nMsgs = 20;
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i };
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
receiver.SetCredit(2, false);
Message m1 = receiver.Receive();
Message m2 = receiver.Receive();
Assert.AreEqual("msg0", m1.Properties.MessageId);
Assert.AreEqual("msg1", m2.Properties.MessageId);
receiver.Accept(m1);
receiver.Accept(m2);
ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path);
receiver2.SetCredit(2, false);
Message m3 = receiver2.Receive();
Message m4 = receiver2.Receive();
Assert.AreEqual("msg2", m3.Properties.MessageId);
Assert.AreEqual("msg3", m4.Properties.MessageId);
receiver2.Accept(m3);
receiver2.Accept(m4);
receiver.SetCredit(4);
for (int i = 4; i < nMsgs; i++)
{
Message m = receiver.Receive();
Assert.AreEqual("msg" + i, m.Properties.MessageId);
receiver.Accept(m);
}
sender.Close();
receiver.Close();
receiver2.Close();
session.Close();
connection.Close();
}
#if !NETMF && !NETFX_CORE
[TestMethod]
public void TestMethod_ProtocolHandler()
{
string testName = "ProtocolHandler";
int nMsgs = 5;
var handler = new TestHandler(e =>
{
if (e.Id == EventId.SocketConnect)
{
((System.Net.Sockets.Socket)e.Context).SendBufferSize = 4096;
}
else if (e.Id == EventId.SslAuthenticate)
{
((System.Net.Security.SslStream)e.Context).AuthenticateAsClient("localhost");
}
});
Connection.DisableServerCertValidation = true;
Address sslAddress = new Address("amqps://guest:guest@localhost:5671");
Connection connection = new Connection(sslAddress, handler);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message("msg" + i);
message.Properties = new Properties() { GroupId = "abcdefg" };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
sender.Send(message, null, null);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
for (int i = 0; i < nMsgs; ++i)
{
Message message = receiver.Receive();
Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
sender.Close();
receiver.Close();
session.Close();
connection.Close();
}
#endif
/// <summary>
/// This test proves that issue #14 is fixed.
/// https://github.com/Azure/amqpnetlite/issues/14
/// </summary>
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SendEmptyMessage()
{
string testName = "SendEmptyMessage";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
bool threwArgEx = false;
try
{
sender.Send(new Message());
}
catch (ArgumentException)
{
threwArgEx = true;
}
finally
{
sender.Close();
session.Close();
connection.Close();
}
Assert.IsTrue(threwArgEx, "Should throw an argument exception when sending an empty message.");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SendToNonExistingNode()
{
string testName = "SendToNonExistingNode";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "$explicit:sender-" + testName, Guid.NewGuid().ToString());
try
{
sender.Send(new Message("test"));
Assert.IsTrue(false, "Send does not fail");
}
catch (AmqpException exception)
{
Assert.AreEqual((Symbol)ErrorCode.NotFound, exception.Error.Condition);
}
finally
{
connection.Close();
}
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ReceiveFromNonExistingNode()
{
string testName = "ReceiveFromNonExistingNode";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
ReceiverLink receiver = new ReceiverLink(session, "$explicit:receiver-" + testName, Guid.NewGuid().ToString());
try
{
receiver.Receive();
Assert.IsTrue(false, "receive does not fail");
}
catch (AmqpException exception)
{
Assert.AreEqual((Symbol)ErrorCode.NotFound, exception.Error.Condition);
}
finally
{
connection.Close();
}
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_ConnectionCreateClose()
{
Connection connection = new Connection(testTarget.Address);
connection.Close();
Assert.IsTrue(connection.Error == null, "connection has error!");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_SessionCreateClose()
{
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
session.Close(TimeSpan.Zero);
connection.Close();
Assert.IsTrue(connection.Error == null, "connection has error!");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_LinkCreateClose()
{
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender", testTarget.Path);
ReceiverLink receiver = new ReceiverLink(session, "receiver", testTarget.Path);
sender.Close(TimeSpan.Zero);
receiver.Close(TimeSpan.Zero);
session.Close(TimeSpan.Zero);
connection.Close();
Assert.IsTrue(connection.Error == null, "connection has error!");
}
#if NETFX || NETFX35 || NETFX_CORE || DOTNET
[TestMethod]
#endif
public void TestMethod_LinkReopen()
{
string testName = "LinkReopen";
Connection connection = new Connection(testTarget.Address);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender", testTarget.Path);
sender.Send(new Message("test") { Properties = new Properties() { MessageId = testName } });
sender.Close();
sender = new SenderLink(session, "sender", testTarget.Path);
sender.Send(new Message("test2") { Properties = new Properties() { MessageId = testName } });
sender.Close();
ReceiverLink receiver = new ReceiverLink(session, "receiver", testTarget.Path);
for (int i = 1; i <= 2; i++)
{
var m = receiver.Receive();
Assert.IsTrue(m != null, "Didn't receive message " + i);
receiver.Accept(m);
}
session.Close(TimeSpan.Zero);
connection.Close();
Assert.IsTrue(connection.Error == null, "connection has error!");
}
#if NETFX_CORE
static void StartThread(Action action)
{
System.Threading.Tasks.Task.Factory.StartNew(action);
}
#elif NETMF
static void StartThread(ThreadStart threadStart)
{
new Thread(threadStart).Start();
}
#else
static void StartThread(ThreadStart threadStart)
{
ThreadPool.QueueUserWorkItem(
o => { ((ThreadStart)o)(); },
threadStart);
}
#endif
}
#if NETMF
static class Extensions
{
internal static bool WaitOne(this ManualResetEvent mre, int milliseconds)
{
return mre.WaitOne(milliseconds, false);
}
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Threading.Tests
{
public class EventWaitHandleTests
{
[Theory]
[InlineData(false, EventResetMode.AutoReset)]
[InlineData(false, EventResetMode.ManualReset)]
[InlineData(true, EventResetMode.AutoReset)]
[InlineData(true, EventResetMode.ManualReset)]
public void Ctor_StateMode(bool initialState, EventResetMode mode)
{
using (var ewh = new EventWaitHandle(initialState, mode))
Assert.Equal(initialState, ewh.WaitOne(0));
}
[Fact]
public void Ctor_InvalidMode()
{
AssertExtensions.Throws<ArgumentException>("mode", null, () => new EventWaitHandle(true, (EventResetMode)12345));
}
[PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix
[Theory]
[MemberData(nameof(GetValidNames))]
public void Ctor_ValidNames(string name)
{
bool createdNew;
using (var ewh = new EventWaitHandle(true, EventResetMode.AutoReset, name, out createdNew))
{
Assert.True(createdNew);
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // names aren't supported on Unix
[Fact]
public void Ctor_NamesArentSupported_Unix()
{
Assert.Throws<PlatformNotSupportedException>(() => new EventWaitHandle(false, EventResetMode.AutoReset, "anything"));
bool createdNew;
Assert.Throws<PlatformNotSupportedException>(() => new EventWaitHandle(false, EventResetMode.AutoReset, "anything", out createdNew));
}
[PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix
[Theory]
[InlineData(false, EventResetMode.AutoReset)]
[InlineData(false, EventResetMode.ManualReset)]
[InlineData(true, EventResetMode.AutoReset)]
[InlineData(true, EventResetMode.ManualReset)]
public void Ctor_StateModeNameCreatedNew_Windows(bool initialState, EventResetMode mode)
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (var ewh = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew))
{
Assert.True(createdNew);
using (new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew))
{
Assert.False(createdNew);
}
}
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Theory]
[InlineData(EventResetMode.AutoReset)]
[InlineData(EventResetMode.ManualReset)]
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows(EventResetMode mode)
{
string name = Guid.NewGuid().ToString("N");
using (Mutex m = new Mutex(false, name))
Assert.Throws<WaitHandleCannotBeOpenedException>(() => new EventWaitHandle(false, mode, name));
}
[Fact]
public void SetReset()
{
using (EventWaitHandle are = new EventWaitHandle(false, EventResetMode.AutoReset))
{
Assert.False(are.WaitOne(0));
are.Set();
Assert.True(are.WaitOne(0));
Assert.False(are.WaitOne(0));
are.Set();
are.Reset();
Assert.False(are.WaitOne(0));
}
using (EventWaitHandle mre = new EventWaitHandle(false, EventResetMode.ManualReset))
{
Assert.False(mre.WaitOne(0));
mre.Set();
Assert.True(mre.WaitOne(0));
Assert.True(mre.WaitOne(0));
mre.Set();
Assert.True(mre.WaitOne(0));
mre.Reset();
Assert.False(mre.WaitOne(0));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix
[Theory]
[MemberData(nameof(GetValidNames))]
public void OpenExisting_Windows(string name)
{
EventWaitHandle resultHandle;
Assert.False(EventWaitHandle.TryOpenExisting(name, out resultHandle));
Assert.Null(resultHandle);
using (EventWaitHandle are1 = new EventWaitHandle(false, EventResetMode.AutoReset, name))
{
using (EventWaitHandle are2 = EventWaitHandle.OpenExisting(name))
{
are1.Set();
Assert.True(are2.WaitOne(0));
Assert.False(are1.WaitOne(0));
Assert.False(are2.WaitOne(0));
are2.Set();
Assert.True(are1.WaitOne(0));
Assert.False(are2.WaitOne(0));
Assert.False(are1.WaitOne(0));
}
Assert.True(EventWaitHandle.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_NotSupported_Unix()
{
Assert.Throws<PlatformNotSupportedException>(() => EventWaitHandle.OpenExisting("anything"));
EventWaitHandle ewh;
Assert.Throws<PlatformNotSupportedException>(() => EventWaitHandle.TryOpenExisting("anything", out ewh));
}
[PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_InvalidNames_Windows()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => EventWaitHandle.OpenExisting(null));
AssertExtensions.Throws<ArgumentException>("name", null, () => EventWaitHandle.OpenExisting(string.Empty));
}
[PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_UnavailableName_Windows()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => EventWaitHandle.OpenExisting(name));
EventWaitHandle ignored;
Assert.False(EventWaitHandle.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(TestPlatforms.Windows)] // OpenExisting not supported on Unix
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Mutex mtx = new Mutex(true, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => EventWaitHandle.OpenExisting(name));
EventWaitHandle ignored;
Assert.False(EventWaitHandle.TryOpenExisting(name, out ignored));
}
}
[PlatformSpecific(TestPlatforms.Windows)] // names aren't supported on Unix
[Theory]
[InlineData(EventResetMode.ManualReset)]
[InlineData(EventResetMode.AutoReset)]
public void PingPong(EventResetMode mode)
{
// Create names for the two events
string outboundName = Guid.NewGuid().ToString("N");
string inboundName = Guid.NewGuid().ToString("N");
// Create the two events and the other process with which to synchronize
using (var inbound = new EventWaitHandle(true, mode, inboundName))
using (var outbound = new EventWaitHandle(false, mode, outboundName))
using (var remote = RemoteExecutor.Invoke(PingPong_OtherProcess, mode.ToString(), outboundName, inboundName))
{
// Repeatedly wait for one event and then set the other
for (int i = 0; i < 10; i++)
{
Assert.True(inbound.WaitOne(RemoteExecutor.FailWaitTimeoutMilliseconds));
if (mode == EventResetMode.ManualReset)
{
inbound.Reset();
}
outbound.Set();
}
}
}
private static int PingPong_OtherProcess(string modeName, string inboundName, string outboundName)
{
EventResetMode mode = (EventResetMode)Enum.Parse(typeof(EventResetMode), modeName);
// Open the two events
using (var inbound = EventWaitHandle.OpenExisting(inboundName))
using (var outbound = EventWaitHandle.OpenExisting(outboundName))
{
// Repeatedly wait for one event and then set the other
for (int i = 0; i < 10; i++)
{
Assert.True(inbound.WaitOne(RemoteExecutor.FailWaitTimeoutMilliseconds));
if (mode == EventResetMode.ManualReset)
{
inbound.Reset();
}
outbound.Set();
}
}
return RemoteExecutor.SuccessExitCode;
}
public static TheoryData<string> GetValidNames()
{
var names = new TheoryData<string>() { Guid.NewGuid().ToString("N") };
names.Add(Guid.NewGuid().ToString("N") + new string('a', 1000));
return names;
}
}
}
| |
/*
* [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 Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime
{
[System.Serializable]
public class CommonToken : IWritableToken
{
private const long serialVersionUID = -6708843461296520577L;
/// <summary>
/// An empty
/// <see cref="Tuple{T1, T2}"/>
/// which is used as the default value of
/// <see cref="source"/>
/// for tokens that do not have a source.
/// </summary>
protected internal static readonly Tuple<ITokenSource, ICharStream> EmptySource = Tuple.Create<ITokenSource, ICharStream>(null, null);
/// <summary>
/// This is the backing field for the <see cref="Type"/> property.
/// </summary>
private int _type;
/// <summary>
/// This is the backing field for the <see cref="Line"/> property.
/// </summary>
private int _line;
/// <summary>
/// This is the backing field for the <see cref="Column"/> property.
/// </summary>
protected internal int charPositionInLine = -1;
/// <summary>
/// This is the backing field for the <see cref="Channel"/> property.
/// </summary>
private int _channel = TokenConstants.DefaultChannel;
/// <summary>
/// This is the backing field for
/// <see cref="TokenSource()"/>
/// and
/// <see cref="InputStream()"/>
/// .
/// <p>
/// These properties share a field to reduce the memory footprint of
/// <see cref="CommonToken"/>
/// . Tokens created by a
/// <see cref="CommonTokenFactory"/>
/// from
/// the same source and input stream share a reference to the same
/// <see cref="Tuple{T1, T2}"/>
/// containing these values.</p>
/// </summary>
[NotNull]
protected internal Tuple<ITokenSource, ICharStream> source;
/// <summary>
/// This is the backing field for the <see cref="Text"/> property.
/// </summary>
/// <seealso cref="Text"/>
private string _text;
/// <summary>
/// This is the backing field for the <see cref="TokenIndex"/> property.
/// </summary>
protected internal int index = -1;
/// <summary>
/// This is the backing field for the <see cref="StartIndex"/> property.
/// </summary>
protected internal int start;
/// <summary>
/// This is the backing field for the <see cref="StopIndex"/> property.
/// </summary>
protected internal int stop;
/// <summary>
/// Constructs a new
/// <see cref="CommonToken"/>
/// with the specified token type.
/// </summary>
/// <param name="type">The token type.</param>
public CommonToken(int type)
{
// set to invalid position
this._type = type;
this.source = EmptySource;
}
public CommonToken(Tuple<ITokenSource, ICharStream> source, int type, int channel, int start, int stop)
{
this.source = source;
this._type = type;
this._channel = channel;
this.start = start;
this.stop = stop;
if (source.Item1 != null)
{
this._line = source.Item1.Line;
this.charPositionInLine = source.Item1.Column;
}
}
/// <summary>
/// Constructs a new
/// <see cref="CommonToken"/>
/// with the specified token type and
/// text.
/// </summary>
/// <param name="type">The token type.</param>
/// <param name="text">The text of the token.</param>
public CommonToken(int type, string text)
{
this._type = type;
this._channel = TokenConstants.DefaultChannel;
this._text = text;
this.source = EmptySource;
}
/// <summary>
/// Constructs a new
/// <see cref="CommonToken"/>
/// as a copy of another
/// <see cref="IToken"/>
/// .
/// <p>
/// If
/// <paramref name="oldToken"/>
/// is also a
/// <see cref="CommonToken"/>
/// instance, the newly
/// constructed token will share a reference to the
/// <see cref="Text()"/>
/// field and
/// the
/// <see cref="Tuple{T1, T2}"/>
/// stored in
/// <see cref="source"/>
/// . Otherwise,
/// <see cref="Text()"/>
/// will
/// be assigned the result of calling
/// <see cref="Text()"/>
/// , and
/// <see cref="source"/>
/// will be constructed from the result of
/// <see cref="IToken.TokenSource()"/>
/// and
/// <see cref="IToken.InputStream()"/>
/// .</p>
/// </summary>
/// <param name="oldToken">The token to copy.</param>
public CommonToken(IToken oldToken)
{
_type = oldToken.Type;
_line = oldToken.Line;
index = oldToken.TokenIndex;
charPositionInLine = oldToken.Column;
_channel = oldToken.Channel;
start = oldToken.StartIndex;
stop = oldToken.StopIndex;
if (oldToken is Antlr4.Runtime.CommonToken)
{
_text = ((Antlr4.Runtime.CommonToken)oldToken)._text;
source = ((Antlr4.Runtime.CommonToken)oldToken).source;
}
else
{
_text = oldToken.Text;
source = Tuple.Create(oldToken.TokenSource, oldToken.InputStream);
}
}
public virtual int Type
{
get
{
return _type;
}
set
{
this._type = value;
}
}
public virtual int Line
{
get
{
return _line;
}
set
{
this._line = value;
}
}
/// <summary>Explicitly set the text for this token.</summary>
/// <remarks>
/// Explicitly set the text for this token. If {code text} is not
/// <see langword="null"/>
/// , then
/// <see cref="Text()"/>
/// will return this value rather than
/// extracting the text from the input.
/// </remarks>
/// <value>
/// The explicit text of the token, or
/// <see langword="null"/>
/// if the text
/// should be obtained from the input along with the start and stop indexes
/// of the token.
/// </value>
public virtual string Text
{
get
{
if (_text != null)
{
return _text;
}
ICharStream input = InputStream;
if (input == null)
{
return null;
}
int n = input.Size;
if (start < n && stop < n)
{
return input.GetText(Interval.Of(start, stop));
}
else
{
return "<EOF>";
}
}
set
{
this._text = value;
}
}
public virtual int Column
{
get
{
return charPositionInLine;
}
set
{
int charPositionInLine = value;
this.charPositionInLine = charPositionInLine;
}
}
public virtual int Channel
{
get
{
return _channel;
}
set
{
this._channel = value;
}
}
public virtual int StartIndex
{
get
{
return start;
}
set
{
int start = value;
this.start = start;
}
}
public virtual int StopIndex
{
get
{
return stop;
}
set
{
int stop = value;
this.stop = stop;
}
}
public virtual int TokenIndex
{
get
{
return index;
}
set
{
int index = value;
this.index = index;
}
}
public virtual ITokenSource TokenSource
{
get
{
return source.Item1;
}
}
public virtual ICharStream InputStream
{
get
{
return source.Item2;
}
}
public override string ToString()
{
string channelStr = string.Empty;
if (_channel > 0)
{
channelStr = ",channel=" + _channel;
}
string txt = Text;
if (txt != null)
{
txt = txt.Replace("\n", "\\n");
txt = txt.Replace("\r", "\\r");
txt = txt.Replace("\t", "\\t");
}
else
{
txt = "<no text>";
}
return "[@" + TokenIndex + "," + start + ":" + stop + "='" + txt + "',<" + _type + ">" + channelStr + "," + _line + ":" + Column + "]";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System.Reflection;
using System.Collections;
using System.IO;
using System.Xml.Schema;
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Security;
using System.Xml.Serialization.Configuration;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Xml;
using System.Xml.Serialization;
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public struct XmlDeserializationEvents
{
private XmlNodeEventHandler _onUnknownNode;
private XmlAttributeEventHandler _onUnknownAttribute;
private XmlElementEventHandler _onUnknownElement;
private UnreferencedObjectEventHandler _onUnreferencedObject;
internal object sender;
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownNode"]/*' />
public XmlNodeEventHandler OnUnknownNode
{
get
{
return _onUnknownNode;
}
set
{
_onUnknownNode = value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownAttribute"]/*' />
public XmlAttributeEventHandler OnUnknownAttribute
{
get
{
return _onUnknownAttribute;
}
set
{
_onUnknownAttribute = value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownElement"]/*' />
public XmlElementEventHandler OnUnknownElement
{
get
{
return _onUnknownElement;
}
set
{
_onUnknownElement = value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnreferencedObject"]/*' />
public UnreferencedObjectEventHandler OnUnreferencedObject
{
get
{
return _onUnreferencedObject;
}
set
{
_onUnreferencedObject = value;
}
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract class XmlSerializerImplementation
{
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' />
public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' />
public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' />
public virtual Hashtable ReadMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' />
public virtual Hashtable WriteMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' />
public virtual Hashtable TypedSerializers { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' />
public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' />
public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); }
}
// This enum is intentionally kept outside of the XmlSerializer class since if it would be a subclass
// of XmlSerializer, then any access to this enum would be treated by AOT compilers as access to the XmlSerializer
// as well, which has a large static ctor which brings in a lot of code. So keeping the enum separate
// makes sure that using just the enum itself doesn't bring in the whole of serialization code base.
#if FEATURE_SERIALIZATION_UAPAOT
public enum SerializationMode
#else
internal enum SerializationMode
#endif
{
CodeGenOnly,
ReflectionOnly,
ReflectionAsBackup,
PreGenOnly
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSerializer
{
#if FEATURE_SERIALIZATION_UAPAOT
public static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup;
#else
internal static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup;
#endif
private static bool ReflectionMethodEnabled
{
get
{
return Mode == SerializationMode.ReflectionOnly || Mode == SerializationMode.ReflectionAsBackup;
}
}
private TempAssembly _tempAssembly;
#pragma warning disable 0414
private bool _typedSerializer;
#pragma warning restore 0414
private Type _primitiveType;
private XmlMapping _mapping;
private XmlDeserializationEvents _events = new XmlDeserializationEvents();
#if FEATURE_SERIALIZATION_UAPAOT
private XmlSerializer innerSerializer;
public string DefaultNamespace = null;
#else
internal string DefaultNamespace = null;
#endif
private Type _rootType;
private static TempAssemblyCache s_cache = new TempAssemblyCache();
private static volatile XmlSerializerNamespaces s_defaultNamespaces;
private static XmlSerializerNamespaces DefaultNamespaces
{
get
{
if (s_defaultNamespaces == null)
{
XmlSerializerNamespaces nss = new XmlSerializerNamespaces();
nss.AddInternal("xsi", XmlSchema.InstanceNamespace);
nss.AddInternal("xsd", XmlSchema.Namespace);
if (s_defaultNamespaces == null)
{
s_defaultNamespaces = nss;
}
}
return s_defaultNamespaces;
}
}
private static readonly Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>>();
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' />
///<internalonly/>
protected XmlSerializer()
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) :
this(type, overrides, extraTypes, root, defaultNamespace, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(XmlTypeMapping xmlTypeMapping)
{
if (xmlTypeMapping == null)
throw new ArgumentNullException(nameof(xmlTypeMapping));
#if !FEATURE_SERIALIZATION_UAPAOT
_tempAssembly = GenerateTempAssembly(xmlTypeMapping);
#endif
_mapping = xmlTypeMapping;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type) : this(type, (string)null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, string defaultNamespace)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
DefaultNamespace = defaultNamespace;
_rootType = type;
_mapping = GetKnownMapping(type, defaultNamespace);
if (_mapping != null)
{
_primitiveType = type;
return;
}
#if !FEATURE_SERIALIZATION_UAPAOT
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
lock (s_cache)
{
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
{
XmlSerializerImplementation contract = null;
Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract);
if (assembly == null)
{
if (Mode == SerializationMode.PreGenOnly)
{
AssemblyName name = type.Assembly.GetName();
var serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName));
}
// need to reflect and generate new serialization assembly
XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace);
_mapping = importer.ImportTypeMapping(type, null, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
}
else
{
// we found the pre-generated assembly, now make sure that the assembly has the right serializer
// try to avoid the reflection step, need to get ElementName, namespace and the Key form the type
_mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
_tempAssembly = new TempAssembly(new XmlMapping[] { _mapping }, assembly, contract);
}
}
}
s_cache.Add(defaultNamespace, type, _tempAssembly);
}
}
if (_mapping == null)
{
_mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
#else
XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly();
if (contract != null)
{
this.innerSerializer = contract.GetSerializer(type);
}
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
DefaultNamespace = defaultNamespace;
_rootType = type;
_mapping = GenerateXmlTypeMapping(type, overrides, extraTypes, root, defaultNamespace);
#if !FEATURE_SERIALIZATION_UAPAOT
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location);
#endif
}
private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace)
{
XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
if (extraTypes != null)
{
for (int i = 0; i < extraTypes.Length; i++)
importer.IncludeType(extraTypes[i]);
}
return importer.ImportTypeMapping(type, root, defaultNamespace);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping)
{
return GenerateTempAssembly(xmlMapping, null, null);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace)
{
return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location)
{
if (xmlMapping == null)
{
throw new ArgumentNullException(nameof(xmlMapping));
}
xmlMapping.CheckShallow();
if (xmlMapping.IsSoap)
{
return null;
}
return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o)
{
Serialize(textWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 2;
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o)
{
Serialize(stream, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces)
{
XmlTextWriter xmlWriter = new XmlTextWriter(stream, null);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 2;
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(xmlWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
Serialize(xmlWriter, o, namespaces, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
{
Serialize(xmlWriter, o, namespaces, encodingStyle, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
try
{
if (_primitiveType != null)
{
if (encodingStyle != null && encodingStyle.Length > 0)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle));
}
SerializePrimitive(xmlWriter, o, namespaces);
}
else if (ShouldUseReflectionBasedSerialization(_mapping))
{
SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id);
}
#if !FEATURE_SERIALIZATION_UAPAOT
else if (_tempAssembly == null || _typedSerializer)
{
// The contion for the block is never true, thus the block is never hit.
XmlSerializationWriter writer = CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
try
{
Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
else
_tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
#else
else
{
if (this.innerSerializer != null)
{
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
try
{
this.innerSerializer.Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
else if (ReflectionMethodEnabled)
{
SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id);
}
else
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this._rootType, typeof(XmlSerializer).Name));
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
throw new InvalidOperationException(SR.XmlGenError, e);
}
xmlWriter.Flush();
}
private void SerializeUsingReflection(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
XmlMapping mapping = GetMapping();
var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
writer.WriteObject(o);
}
private XmlMapping GetMapping()
{
if (_mapping == null || !_mapping.GenerateSerializer)
{
_mapping = GenerateXmlTypeMapping(_rootType, null, null, null, DefaultNamespace);
}
return _mapping;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(Stream stream)
{
XmlTextReader xmlReader = new XmlTextReader(stream);
xmlReader.WhitespaceHandling = WhitespaceHandling.Significant;
xmlReader.Normalization = true;
xmlReader.XmlResolver = null;
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(TextReader textReader)
{
XmlTextReader xmlReader = new XmlTextReader(textReader);
xmlReader.WhitespaceHandling = WhitespaceHandling.Significant;
xmlReader.Normalization = true;
xmlReader.XmlResolver = null;
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(XmlReader xmlReader)
{
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize3"]/*' />
public object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events)
{
return Deserialize(xmlReader, null, events);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
public object Deserialize(XmlReader xmlReader, string encodingStyle)
{
return Deserialize(xmlReader, encodingStyle, _events);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' />
public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
{
events.sender = this;
try
{
if (_primitiveType != null)
{
if (encodingStyle != null && encodingStyle.Length > 0)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle));
}
return DeserializePrimitive(xmlReader, events);
}
else if (ShouldUseReflectionBasedSerialization(_mapping))
{
return DeserializeUsingReflection(xmlReader, encodingStyle, events);
}
#if !FEATURE_SERIALIZATION_UAPAOT
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationReader reader = CreateReader();
reader.Init(xmlReader, events, encodingStyle, _tempAssembly);
try
{
return Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
else
{
return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle);
}
#else
else
{
if (this.innerSerializer != null)
{
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationReader reader = this.innerSerializer.CreateReader();
reader.Init(xmlReader, events, encodingStyle);
try
{
return this.innerSerializer.Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
else if (ReflectionMethodEnabled)
{
return DeserializeUsingReflection(xmlReader, encodingStyle, events);
}
else
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this._rootType, typeof(XmlSerializer).Name));
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
if (xmlReader is IXmlLineInfo)
{
IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader;
throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e);
}
else
{
throw new InvalidOperationException(SR.XmlSerializeError, e);
}
}
}
private object DeserializeUsingReflection(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
{
XmlMapping mapping = GetMapping();
var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle);
return reader.ReadObject();
}
private static bool ShouldUseReflectionBasedSerialization(XmlMapping mapping)
{
return Mode == SerializationMode.ReflectionOnly
|| (mapping != null && mapping.IsSoap);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual bool CanDeserialize(XmlReader xmlReader)
{
if (_primitiveType != null)
{
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType];
return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty);
}
#if !FEATURE_SERIALIZATION_UAPAOT
else if (_tempAssembly != null)
{
return _tempAssembly.CanRead(_mapping, xmlReader);
}
else
{
return false;
}
#else
if (this.innerSerializer != null)
{
return this.innerSerializer.CanDeserialize(xmlReader);
}
else
{
return ReflectionMethodEnabled;
}
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings)
{
return FromMappings(mappings, (Type)null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
{
if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>();
#if FEATURE_SERIALIZATION_UAPAOT
XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type);
return serializers;
#else
bool anySoapMapping = false;
foreach (var mapping in mappings)
{
if (mapping.IsSoap)
{
anySoapMapping = true;
}
}
if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly)
{
XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type);
return serializers;
}
XmlSerializerImplementation contract = null;
Assembly assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract);
TempAssembly tempAssembly = null;
if (assembly == null)
{
if (Mode == SerializationMode.PreGenOnly)
{
AssemblyName name = type.Assembly.GetName();
string serializerName = Compiler.GetTempAssemblyName(name, null);
throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName));
}
if (XmlMapping.IsShallow(mappings))
{
return Array.Empty<XmlSerializer>();
}
else
{
if (type == null)
{
tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null);
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
contract = tempAssembly.Contract;
for (int i = 0; i < serializers.Length; i++)
{
serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
serializers[i].SetTempAssembly(tempAssembly, mappings[i]);
}
return serializers;
}
else
{
// Use XmlSerializer cache when the type is not null.
return GetSerializersFromCache(mappings, type);
}
}
}
else
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
for (int i = 0; i < serializers.Length; i++)
serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
return serializers;
}
#endif
}
private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type type)
{
var serializers = new XmlSerializer[mappings.Length];
for (int i = 0; i < serializers.Length; i++)
{
serializers[i] = new XmlSerializer();
serializers[i]._rootType = type;
serializers[i]._mapping = mappings[i];
}
return serializers;
}
#if !FEATURE_SERIALIZATION_UAPAOT
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
public static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Stream stream)
{
if (types == null || types.Length == 0)
return false;
if (mappings == null)
throw new ArgumentNullException(nameof(mappings));
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (XmlMapping.IsShallow(mappings))
{
throw new InvalidOperationException(SR.Format(SR.XmlMelformMapping));
}
Assembly assembly = null;
for (int i = 0; i < types.Length; i++)
{
Type type = types[i];
if (DynamicAssemblies.IsTypeDynamic(type))
{
throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, type.FullName));
}
if (assembly == null)
{
assembly = type.Assembly;
}
else if (type.Assembly != assembly)
{
throw new ArgumentException(SR.Format(SR.XmlPregenOrphanType, type.FullName, assembly.Location), "types");
}
}
return TempAssembly.GenerateSerializerToStream(mappings, types, null, assembly, new Hashtable(), stream);
}
#endif
private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
Dictionary<XmlSerializerMappingKey, XmlSerializer> typedMappingTable = null;
lock (s_xmlSerializerTable)
{
if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable))
{
typedMappingTable = new Dictionary<XmlSerializerMappingKey, XmlSerializer>();
s_xmlSerializerTable[type] = typedMappingTable;
}
}
lock (typedMappingTable)
{
var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>();
for (int i = 0; i < mappings.Length; i++)
{
XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]);
if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i]))
{
pendingKeys.Add(mappingKey, i);
}
}
if (pendingKeys.Count > 0)
{
XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count];
int index = 0;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
pendingMappings[index++] = mappingKey.Mapping;
}
TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null);
XmlSerializerImplementation contract = tempAssembly.Contract;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
index = pendingKeys[mappingKey];
serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key];
serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping);
typedMappingTable[mappingKey] = serializers[index];
}
}
}
return serializers;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromTypes(Type[] types)
{
if (types == null)
return Array.Empty<XmlSerializer>();
#if FEATURE_SERIALIZATION_UAPAOT
var serializers = new XmlSerializer[types.Length];
for (int i = 0; i < types.Length; i++)
{
serializers[i] = new XmlSerializer(types[i]);
}
return serializers;
#else
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length];
for (int i = 0; i < types.Length; i++)
{
mappings[i] = importer.ImportTypeMapping(types[i]);
}
return FromMappings(mappings);
#endif
}
#if FEATURE_SERIALIZATION_UAPAOT
// this the global XML serializer contract introduced for multi-file
private static XmlSerializerImplementation xmlSerializerContract;
internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly()
{
// hack to pull in SetXmlSerializerContract which is only referenced from the
// code injected by MainMethodInjector transform
// there's probably also a way to do this via [DependencyReductionRoot],
// but I can't get the compiler to find that...
if (xmlSerializerContract == null)
SetXmlSerializerContract(null);
// this method body used to be rewritten by an IL transform
// with the restructuring for multi-file, it has become a regular method
return xmlSerializerContract;
}
public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation)
{
xmlSerializerContract = xmlSerializerImplementation;
}
#endif
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string GetXmlSerializerAssemblyName(Type type)
{
return GetXmlSerializerAssemblyName(type, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return Compiler.GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownNode"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public event XmlNodeEventHandler UnknownNode
{
add
{
_events.OnUnknownNode += value;
}
remove
{
_events.OnUnknownNode -= value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownAttribute"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public event XmlAttributeEventHandler UnknownAttribute
{
add
{
_events.OnUnknownAttribute += value;
}
remove
{
_events.OnUnknownAttribute -= value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownElement"]/*' />
public event XmlElementEventHandler UnknownElement
{
add
{
_events.OnUnknownElement += value;
}
remove
{
_events.OnUnknownElement -= value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnreferencedObject"]/*' />
public event UnreferencedObjectEventHandler UnreferencedObject
{
add
{
_events.OnUnreferencedObject += value;
}
remove
{
_events.OnUnreferencedObject -= value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' />
///<internalonly/>
protected virtual XmlSerializationReader CreateReader() { throw new NotImplementedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
///<internalonly/>
protected virtual object Deserialize(XmlSerializationReader reader) { throw new NotImplementedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' />
///<internalonly/>
protected virtual XmlSerializationWriter CreateWriter() { throw new NotImplementedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' />
///<internalonly/>
protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new NotImplementedException(); }
internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping)
{
_tempAssembly = tempAssembly;
_mapping = mapping;
_typedSerializer = true;
}
private static XmlTypeMapping GetKnownMapping(Type type, string ns)
{
if (ns != null && ns != string.Empty)
return null;
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type];
if (typeDesc == null)
return null;
ElementAccessor element = new ElementAccessor();
element.Name = typeDesc.DataType.Name;
XmlTypeMapping mapping = new XmlTypeMapping(null, element);
mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null));
return mapping;
}
private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter();
writer.Init(xmlWriter, namespaces, null, null, null);
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
writer.Write_string(o);
break;
case TypeCode.Int32:
writer.Write_int(o);
break;
case TypeCode.Boolean:
writer.Write_boolean(o);
break;
case TypeCode.Int16:
writer.Write_short(o);
break;
case TypeCode.Int64:
writer.Write_long(o);
break;
case TypeCode.Single:
writer.Write_float(o);
break;
case TypeCode.Double:
writer.Write_double(o);
break;
case TypeCode.Decimal:
writer.Write_decimal(o);
break;
case TypeCode.DateTime:
writer.Write_dateTime(o);
break;
case TypeCode.Char:
writer.Write_char(o);
break;
case TypeCode.Byte:
writer.Write_unsignedByte(o);
break;
case TypeCode.SByte:
writer.Write_byte(o);
break;
case TypeCode.UInt16:
writer.Write_unsignedShort(o);
break;
case TypeCode.UInt32:
writer.Write_unsignedInt(o);
break;
case TypeCode.UInt64:
writer.Write_unsignedLong(o);
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
writer.Write_QName(o);
}
else if (_primitiveType == typeof(byte[]))
{
writer.Write_base64Binary(o);
}
else if (_primitiveType == typeof(Guid))
{
writer.Write_guid(o);
}
else if (_primitiveType == typeof(TimeSpan))
{
writer.Write_TimeSpan(o);
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
}
private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events)
{
XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader();
reader.Init(xmlReader, events, null, null);
object o;
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
o = reader.Read_string();
break;
case TypeCode.Int32:
o = reader.Read_int();
break;
case TypeCode.Boolean:
o = reader.Read_boolean();
break;
case TypeCode.Int16:
o = reader.Read_short();
break;
case TypeCode.Int64:
o = reader.Read_long();
break;
case TypeCode.Single:
o = reader.Read_float();
break;
case TypeCode.Double:
o = reader.Read_double();
break;
case TypeCode.Decimal:
o = reader.Read_decimal();
break;
case TypeCode.DateTime:
o = reader.Read_dateTime();
break;
case TypeCode.Char:
o = reader.Read_char();
break;
case TypeCode.Byte:
o = reader.Read_unsignedByte();
break;
case TypeCode.SByte:
o = reader.Read_byte();
break;
case TypeCode.UInt16:
o = reader.Read_unsignedShort();
break;
case TypeCode.UInt32:
o = reader.Read_unsignedInt();
break;
case TypeCode.UInt64:
o = reader.Read_unsignedLong();
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
o = reader.Read_QName();
}
else if (_primitiveType == typeof(byte[]))
{
o = reader.Read_base64Binary();
}
else if (_primitiveType == typeof(Guid))
{
o = reader.Read_guid();
}
else if (_primitiveType == typeof(TimeSpan))
{
o = reader.Read_TimeSpan();
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
return o;
}
private class XmlSerializerMappingKey
{
public XmlMapping Mapping;
public XmlSerializerMappingKey(XmlMapping mapping)
{
this.Mapping = mapping;
}
public override bool Equals(object obj)
{
XmlSerializerMappingKey other = obj as XmlSerializerMappingKey;
if (other == null)
return false;
if (this.Mapping.Key != other.Mapping.Key)
return false;
if (this.Mapping.ElementName != other.Mapping.ElementName)
return false;
if (this.Mapping.Namespace != other.Mapping.Namespace)
return false;
if (this.Mapping.IsSoap != other.Mapping.IsSoap)
return false;
return true;
}
public override int GetHashCode()
{
int hashCode = this.Mapping.IsSoap ? 0 : 1;
if (this.Mapping.Key != null)
hashCode ^= this.Mapping.Key.GetHashCode();
if (this.Mapping.ElementName != null)
hashCode ^= this.Mapping.ElementName.GetHashCode();
if (this.Mapping.Namespace != null)
hashCode ^= this.Mapping.Namespace.GetHashCode();
return hashCode;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Shipping;
using Nop.Services.Helpers;
namespace Nop.Services.Orders
{
/// <summary>
/// Order report service
/// </summary>
public partial class OrderReportService : IOrderReportService
{
#region Fields
private readonly IRepository<Order> _orderRepository;
private readonly IRepository<OrderItem> _orderItemRepository;
private readonly IRepository<Product> _productRepository;
private readonly IDateTimeHelper _dateTimeHelper;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="orderRepository">Order repository</param>
/// <param name="orderItemRepository">Order item repository</param>
/// <param name="productRepository">Product repository</param>
/// <param name="dateTimeHelper">Datetime helper</param>
public OrderReportService(IRepository<Order> orderRepository,
IRepository<OrderItem> orderItemRepository,
IRepository<Product> productRepository,
IDateTimeHelper dateTimeHelper)
{
this._orderRepository = orderRepository;
this._orderItemRepository = orderItemRepository;
this._productRepository = productRepository;
this._dateTimeHelper = dateTimeHelper;
}
#endregion
#region Methods
/// <summary>
/// Get "order by country" report
/// </summary>
/// <param name="storeId">Store identifier</param>
/// <param name="os">Order status</param>
/// <param name="ps">Payment status</param>
/// <param name="ss">Shipping status</param>
/// <param name="startTimeUtc">Start date</param>
/// <param name="endTimeUtc">End date</param>
/// <returns>Result</returns>
public virtual IList<OrderByCountryReportLine> GetCountryReport(int storeId, OrderStatus? os,
PaymentStatus? ps, ShippingStatus? ss, DateTime? startTimeUtc, DateTime? endTimeUtc)
{
int? orderStatusId = null;
if (os.HasValue)
orderStatusId = (int)os.Value;
int? paymentStatusId = null;
if (ps.HasValue)
paymentStatusId = (int)ps.Value;
int? shippingStatusId = null;
if (ss.HasValue)
shippingStatusId = (int)ss.Value;
var query = _orderRepository.Table;
query = query.Where(o => !o.Deleted);
if (storeId > 0)
query = query.Where(o => o.StoreId == storeId);
if (orderStatusId.HasValue)
query = query.Where(o => o.OrderStatusId == orderStatusId.Value);
if (paymentStatusId.HasValue)
query = query.Where(o => o.PaymentStatusId == paymentStatusId.Value);
if (shippingStatusId.HasValue)
query = query.Where(o => o.ShippingStatusId == shippingStatusId.Value);
if (startTimeUtc.HasValue)
query = query.Where(o => startTimeUtc.Value <= o.CreatedOnUtc);
if (endTimeUtc.HasValue)
query = query.Where(o => endTimeUtc.Value >= o.CreatedOnUtc);
var report = (from oq in query
group oq by oq.BillingAddress.CountryId into result
select new
{
CountryId = result.Key,
TotalOrders = result.Count(),
SumOrders = result.Sum(o => o.OrderTotal)
}
)
.OrderByDescending(x => x.SumOrders)
.Select(r => new OrderByCountryReportLine
{
CountryId = r.CountryId,
TotalOrders = r.TotalOrders,
SumOrders = r.SumOrders
})
.ToList();
return report;
}
/// <summary>
/// Get order average report
/// </summary>
/// <param name="storeId">Store identifier</param>
/// <param name="vendorId">Vendor identifier</param>
/// <param name="os">Order status</param>
/// <param name="ps">Payment status</param>
/// <param name="ss">Shipping status</param>
/// <param name="startTimeUtc">Start date</param>
/// <param name="endTimeUtc">End date</param>
/// <param name="billingEmail">Billing email. Leave empty to load all records.</param>
/// <param name="ignoreCancelledOrders">A value indicating whether to ignore cancelled orders</param>
/// <returns>Result</returns>
public virtual OrderAverageReportLine GetOrderAverageReportLine(int storeId, int vendorId, OrderStatus? os,
PaymentStatus? ps, ShippingStatus? ss, DateTime? startTimeUtc, DateTime? endTimeUtc,
string billingEmail, bool ignoreCancelledOrders = false)
{
int? orderStatusId = null;
if (os.HasValue)
orderStatusId = (int)os.Value;
int? paymentStatusId = null;
if (ps.HasValue)
paymentStatusId = (int)ps.Value;
int? shippingStatusId = null;
if (ss.HasValue)
shippingStatusId = (int)ss.Value;
var query = _orderRepository.Table;
query = query.Where(o => !o.Deleted);
if (storeId > 0)
query = query.Where(o => o.StoreId == storeId);
if (vendorId > 0)
{
query = query
.Where(o => o.OrderItems
.Any(orderItem => orderItem.Product.VendorId == vendorId));
}
if (ignoreCancelledOrders)
{
var cancelledOrderStatusId = (int)OrderStatus.Cancelled;
query = query.Where(o => o.OrderStatusId != cancelledOrderStatusId);
}
if (orderStatusId.HasValue)
query = query.Where(o => o.OrderStatusId == orderStatusId.Value);
if (paymentStatusId.HasValue)
query = query.Where(o => o.PaymentStatusId == paymentStatusId.Value);
if (shippingStatusId.HasValue)
query = query.Where(o => o.ShippingStatusId == shippingStatusId.Value);
if (startTimeUtc.HasValue)
query = query.Where(o => startTimeUtc.Value <= o.CreatedOnUtc);
if (endTimeUtc.HasValue)
query = query.Where(o => endTimeUtc.Value >= o.CreatedOnUtc);
if (!String.IsNullOrEmpty(billingEmail))
query = query.Where(o => o.BillingAddress != null && !String.IsNullOrEmpty(o.BillingAddress.Email) && o.BillingAddress.Email.Contains(billingEmail));
var item = (from oq in query
group oq by 1 into result
select new
{
OrderCount = result.Count(),
OrderShippingExclTaxSum = result.Sum(o => o.OrderShippingExclTax),
OrderTaxSum = result.Sum(o => o.OrderTax),
OrderTotalSum = result.Sum(o => o.OrderTotal)
}
).Select(r => new OrderAverageReportLine
{
CountOrders = r.OrderCount,
SumShippingExclTax = r.OrderShippingExclTaxSum,
SumTax = r.OrderTaxSum,
SumOrders = r.OrderTotalSum
})
.FirstOrDefault();
item = item ?? new OrderAverageReportLine
{
CountOrders = 0,
SumShippingExclTax = decimal.Zero,
SumTax = decimal.Zero,
SumOrders = decimal.Zero,
};
return item;
}
/// <summary>
/// Get order average report
/// </summary>
/// <param name="storeId">Store identifier</param>
/// <param name="os">Order status</param>
/// <returns>Result</returns>
public virtual OrderAverageReportLineSummary OrderAverageReport(int storeId, OrderStatus os)
{
var item = new OrderAverageReportLineSummary();
item.OrderStatus = os;
DateTime nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now);
TimeZoneInfo timeZone = _dateTimeHelper.CurrentTimeZone;
//today
var t1 = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day);
if (!timeZone.IsInvalidTime(t1))
{
DateTime? startTime1 = _dateTimeHelper.ConvertToUtcTime(t1, timeZone);
DateTime? endTime1 = null;
var todayResult = GetOrderAverageReportLine(storeId, 0, os, null,null, startTime1, endTime1, null);
item.SumTodayOrders = todayResult.SumOrders;
item.CountTodayOrders = todayResult.CountOrders;
}
//week
DayOfWeek fdow = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
var today = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day);
DateTime t2 = today.AddDays(-(today.DayOfWeek - fdow));
if (!timeZone.IsInvalidTime(t2))
{
DateTime? startTime2 = _dateTimeHelper.ConvertToUtcTime(t2, timeZone);
DateTime? endTime2 = null;
var weekResult = GetOrderAverageReportLine(storeId, 0, os, null, null, startTime2, endTime2, null);
item.SumThisWeekOrders = weekResult.SumOrders;
item.CountThisWeekOrders = weekResult.CountOrders;
}
//month
var t3 = new DateTime(nowDt.Year, nowDt.Month, 1);
if (!timeZone.IsInvalidTime(t3))
{
DateTime? startTime3 = _dateTimeHelper.ConvertToUtcTime(t3, timeZone);
DateTime? endTime3 = null;
var monthResult = GetOrderAverageReportLine(storeId, 0, os, null, null, startTime3, endTime3, null);
item.SumThisMonthOrders = monthResult.SumOrders;
item.CountThisMonthOrders = monthResult.CountOrders;
}
//year
var t4 = new DateTime(nowDt.Year, 1, 1);
if (!timeZone.IsInvalidTime(t4))
{
DateTime? startTime4 = _dateTimeHelper.ConvertToUtcTime(t4, timeZone);
DateTime? endTime4 = null;
var yearResult = GetOrderAverageReportLine(storeId, 0, os, null, null, startTime4, endTime4, null);
item.SumThisYearOrders = yearResult.SumOrders;
item.CountThisYearOrders = yearResult.CountOrders;
}
//all time
DateTime? startTime5 = null;
DateTime? endTime5 = null;
var allTimeResult = GetOrderAverageReportLine(storeId, 0, os, null, null, startTime5, endTime5, null);
item.SumAllTimeOrders = allTimeResult.SumOrders;
item.CountAllTimeOrders = allTimeResult.CountOrders;
return item;
}
/// <summary>
/// Get best sellers report
/// </summary>
/// <param name="storeId">Store identifier; 0 to load all records</param>
/// <param name="vendorId">Vendor identifier; 0 to load all records</param>
/// <param name="categoryId">Category identifier; 0 to load all records</param>
/// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param>
/// <param name="createdFromUtc">Order created date from (UTC); null to load all records</param>
/// <param name="createdToUtc">Order created date to (UTC); null to load all records</param>
/// <param name="os">Order status; null to load all records</param>
/// <param name="ps">Order payment status; null to load all records</param>
/// <param name="ss">Shipping status; null to load all records</param>
/// <param name="billingCountryId">Billing country identifier; 0 to load all records</param>
/// <param name="orderBy">1 - order by quantity, 2 - order by total amount</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Result</returns>
public virtual IPagedList<BestsellersReportLine> BestSellersReport(
int categoryId = 0, int manufacturerId = 0,
int storeId = 0, int vendorId = 0,
DateTime? createdFromUtc = null, DateTime? createdToUtc = null,
OrderStatus? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,
int billingCountryId = 0,
int orderBy = 1,
int pageIndex = 0, int pageSize = int.MaxValue,
bool showHidden = false)
{
int? orderStatusId = null;
if (os.HasValue)
orderStatusId = (int)os.Value;
int? paymentStatusId = null;
if (ps.HasValue)
paymentStatusId = (int)ps.Value;
int? shippingStatusId = null;
if (ss.HasValue)
shippingStatusId = (int)ss.Value;
var query1 = from orderItem in _orderItemRepository.Table
join o in _orderRepository.Table on orderItem.OrderId equals o.Id
join p in _productRepository.Table on orderItem.ProductId equals p.Id
//join pc in _productCategoryRepository.Table on p.Id equals pc.ProductId into p_pc from pc in p_pc.DefaultIfEmpty()
//join pm in _productManufacturerRepository.Table on p.Id equals pm.ProductId into p_pm from pm in p_pm.DefaultIfEmpty()
where (storeId == 0 || storeId == o.StoreId) &&
(!createdFromUtc.HasValue || createdFromUtc.Value <= o.CreatedOnUtc) &&
(!createdToUtc.HasValue || createdToUtc.Value >= o.CreatedOnUtc) &&
(!orderStatusId.HasValue || orderStatusId == o.OrderStatusId) &&
(!paymentStatusId.HasValue || paymentStatusId == o.PaymentStatusId) &&
(!shippingStatusId.HasValue || shippingStatusId == o.ShippingStatusId) &&
(!o.Deleted) &&
(!p.Deleted) &&
(vendorId == 0 || p.VendorId == vendorId) &&
//(categoryId == 0 || pc.CategoryId == categoryId) &&
//(manufacturerId == 0 || pm.ManufacturerId == manufacturerId) &&
(categoryId == 0 || p.ProductCategories.Count(pc => pc.CategoryId == categoryId) > 0) &&
(manufacturerId == 0 || p.ProductManufacturers.Count(pm => pm.ManufacturerId == manufacturerId) > 0) &&
(billingCountryId == 0 || o.BillingAddress.CountryId == billingCountryId) &&
(showHidden || p.Published)
select orderItem;
IQueryable<BestsellersReportLine> query2 =
//group by products
from orderItem in query1
group orderItem by orderItem.ProductId into g
select new BestsellersReportLine
{
ProductId = g.Key,
TotalAmount = g.Sum(x => x.PriceExclTax),
TotalQuantity = g.Sum(x => x.Quantity),
}
;
switch (orderBy)
{
case 1:
{
query2 = query2.OrderByDescending(x => x.TotalQuantity);
}
break;
case 2:
{
query2 = query2.OrderByDescending(x => x.TotalAmount);
}
break;
default:
throw new ArgumentException("Wrong orderBy parameter", "orderBy");
}
var result = new PagedList<BestsellersReportLine>(query2, pageIndex, pageSize);
return result;
}
/// <summary>
/// Gets a list of products (identifiers) purchased by other customers who purchased a specified product
/// </summary>
/// <param name="storeId">Store identifier</param>
/// <param name="productId">Product identifier</param>
/// <param name="recordsToReturn">Records to return</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Products</returns>
public virtual int[] GetAlsoPurchasedProductsIds(int storeId, int productId,
int recordsToReturn = 5, bool showHidden = false)
{
if (productId == 0)
throw new ArgumentException("Product ID is not specified");
//this inner query should retrieve all orders that contains a specified product ID
var query1 = from orderItem in _orderItemRepository.Table
where orderItem.ProductId == productId
select orderItem.OrderId;
var query2 = from orderItem in _orderItemRepository.Table
join p in _productRepository.Table on orderItem.ProductId equals p.Id
where (query1.Contains(orderItem.OrderId)) &&
(p.Id != productId) &&
(showHidden || p.Published) &&
(!orderItem.Order.Deleted) &&
(storeId == 0 || orderItem.Order.StoreId == storeId) &&
(!p.Deleted) &&
(showHidden || p.Published)
select new { orderItem, p };
var query3 = from orderItem_p in query2
group orderItem_p by orderItem_p.p.Id into g
select new
{
ProductId = g.Key,
ProductsPurchased = g.Sum(x => x.orderItem.Quantity),
};
query3 = query3.OrderByDescending(x => x.ProductsPurchased);
if (recordsToReturn > 0)
query3 = query3.Take(recordsToReturn);
var report = query3.ToList();
var ids = new List<int>();
foreach (var reportLine in report)
ids.Add(reportLine.ProductId);
return ids.ToArray();
}
/// <summary>
/// Gets a list of products that were never sold
/// </summary>
/// <param name="vendorId">Vendor identifier</param>
/// <param name="createdFromUtc">Order created date from (UTC); null to load all records</param>
/// <param name="createdToUtc">Order created date to (UTC); null to load all records</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Products</returns>
public virtual IPagedList<Product> ProductsNeverSold(int vendorId,
DateTime? createdFromUtc, DateTime? createdToUtc,
int pageIndex, int pageSize, bool showHidden = false)
{
//this inner query should retrieve all purchased order product varint identifiers
var query1 = (from orderItem in _orderItemRepository.Table
join o in _orderRepository.Table on orderItem.OrderId equals o.Id
where (!createdFromUtc.HasValue || createdFromUtc.Value <= o.CreatedOnUtc) &&
(!createdToUtc.HasValue || createdToUtc.Value >= o.CreatedOnUtc) &&
(!o.Deleted)
select orderItem.ProductId).Distinct();
var simpleProductTypeId = (int)ProductType.SimpleProduct;
var query2 = from p in _productRepository.Table
orderby p.Name
where (!query1.Contains(p.Id)) &&
//include only simple products
(p.ProductTypeId == simpleProductTypeId) &&
(!p.Deleted) &&
(vendorId == 0 || p.VendorId == vendorId) &&
(showHidden || p.Published)
select p;
var products = new PagedList<Product>(query2, pageIndex, pageSize);
return products;
}
/// <summary>
/// Get profit report
/// </summary>
/// <param name="storeId">Store identifier</param>
/// <param name="vendorId">Vendor identifier</param>
/// <param name="startTimeUtc">Start date</param>
/// <param name="endTimeUtc">End date</param>
/// <param name="os">Order status; null to load all records</param>
/// <param name="ps">Order payment status; null to load all records</param>
/// <param name="ss">Shipping status; null to load all records</param>
/// <param name="billingEmail">Billing email. Leave empty to load all records.</param>
/// <returns>Result</returns>
public virtual decimal ProfitReport(int storeId, int vendorId,
OrderStatus? os, PaymentStatus? ps, ShippingStatus? ss,
DateTime? startTimeUtc, DateTime? endTimeUtc,
string billingEmail)
{
int? orderStatusId = null;
if (os.HasValue)
orderStatusId = (int)os.Value;
int? paymentStatusId = null;
if (ps.HasValue)
paymentStatusId = (int)ps.Value;
int? shippingStatusId = null;
if (ss.HasValue)
shippingStatusId = (int)ss.Value;
//We cannot use String.IsNullOrEmpty(billingEmail) in SQL Compact
bool dontSearchEmail = String.IsNullOrEmpty(billingEmail);
var query = from orderItem in _orderItemRepository.Table
join o in _orderRepository.Table on orderItem.OrderId equals o.Id
where (storeId == 0 || storeId == o.StoreId) &&
(!startTimeUtc.HasValue || startTimeUtc.Value <= o.CreatedOnUtc) &&
(!endTimeUtc.HasValue || endTimeUtc.Value >= o.CreatedOnUtc) &&
(!orderStatusId.HasValue || orderStatusId == o.OrderStatusId) &&
(!paymentStatusId.HasValue || paymentStatusId == o.PaymentStatusId) &&
(!shippingStatusId.HasValue || shippingStatusId == o.ShippingStatusId) &&
(!o.Deleted) &&
(vendorId == 0 || orderItem.Product.VendorId == vendorId) &&
//we do not ignore deleted products when calculating order reports
//(!p.Deleted) &&
//(!pv.Deleted) &&
(dontSearchEmail || (o.BillingAddress != null && !String.IsNullOrEmpty(o.BillingAddress.Email) && o.BillingAddress.Email.Contains(billingEmail)))
select orderItem;
var productCost = Convert.ToDecimal(query.Sum(orderItem => (decimal?)orderItem.OriginalProductCost * orderItem.Quantity));
var reportSummary = GetOrderAverageReportLine(storeId, vendorId, os, ps, ss, startTimeUtc, endTimeUtc, billingEmail);
var profit = reportSummary.SumOrders - reportSummary.SumShippingExclTax - reportSummary.SumTax - productCost;
return profit;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Windows.Forms;
using Microsoft.NodejsTools.Npm;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
namespace Microsoft.NodejsTools.Project
{
internal class DependencyNode : HierarchyNode
{
private readonly NodejsProjectNode _projectNode;
private readonly DependencyNode _parent;
private readonly string _displayString;
public DependencyNode(
NodejsProjectNode root,
DependencyNode parent,
IPackage package)
: base(root)
{
this._projectNode = root;
this._parent = parent;
this.Package = package;
this._displayString = GetInitialPackageDisplayString(package);
this.ExcludeNodeFromScc = true;
}
public IPackage Package { get; internal set; }
internal INpmController NpmController
{
get
{
if (null != this._projectNode)
{
var modulesNode = this._projectNode.ModulesNode;
if (null != modulesNode)
{
return modulesNode.NpmController;
}
}
return null;
}
}
#region HierarchyNode implementation
private string GetRelativeUrlFragment()
{
var buff = new StringBuilder();
if (null != this._parent)
{
buff.Append(this._parent.GetRelativeUrlFragment());
buff.Append('/');
}
buff.Append("node_modules/");
buff.Append(this.Package.Name);
return buff.ToString();
}
public override string Url => new Url(this.ProjectMgr.BaseURI, GetRelativeUrlFragment()).AbsoluteUrl;
public override string Caption => this._displayString;
public override Guid ItemTypeGuid => VSConstants.GUID_ItemType_VirtualFolder;
public override Guid MenuGroupId => Guids.NodejsNpmCmdSet;
public override int MenuCommandId => PkgCmdId.menuIdNpm;
[Obsolete]
public override object GetIconHandle(bool open)
{
var imageIndex = this._projectNode.ImageIndexFromNameDictionary[NodejsProjectImageName.Dependency];
if (this.Package.IsMissing)
{
imageIndex = this._projectNode.ImageIndexFromNameDictionary[NodejsProjectImageName.DependencyMissing];
}
else
{
if (!this.Package.IsListedInParentPackageJson)
{
imageIndex = this._projectNode.ImageIndexFromNameDictionary[NodejsProjectImageName.DependencyNotListed];
}
else
{
imageIndex = this._projectNode.ImageIndexFromNameDictionary[NodejsProjectImageName.Dependency];
}
}
return this._projectNode.ImageHandler.GetIconHandle(imageIndex);
}
public override string GetEditLabel()
{
return null;
}
protected override NodeProperties CreatePropertiesObject()
{
return new DependencyNodeProperties(this);
}
internal DependencyNodeProperties GetPropertiesObject()
{
return CreatePropertiesObject() as DependencyNodeProperties;
}
#endregion
#region Command handling
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
// Latter condition is because it's only valid to carry out npm operations
// on top level dependencies of the user's project, not sub-dependencies.
// Performing operations on sub-dependencies would just break things.
if (cmdGroup == Guids.NodejsNpmCmdSet)
{
switch (cmd)
{
case PkgCmdId.cmdidNpmOpenModuleHomepage:
if (this.Package.Homepages != null)
{
using (var enumerator = this.Package.Homepages.GetEnumerator())
{
if (enumerator.MoveNext() && !string.IsNullOrEmpty(enumerator.Current))
{
result = QueryStatusResult.ENABLED | QueryStatusResult.SUPPORTED;
}
else
{
result = QueryStatusResult.SUPPORTED;
}
}
}
return VSConstants.S_OK;
}
if (null == this._parent)
{
switch (cmd)
{
case PkgCmdId.cmdidNpmInstallSingleMissingModule:
if (null == this._projectNode.ModulesNode
|| this._projectNode.ModulesNode.IsCurrentStateASuppressCommandsMode())
{
result = QueryStatusResult.SUPPORTED;
}
else
{
if (null != this.Package && this.Package.IsMissing)
{
result = QueryStatusResult.ENABLED | QueryStatusResult.SUPPORTED;
}
else
{
result = QueryStatusResult.SUPPORTED;
}
}
return VSConstants.S_OK;
case PkgCmdId.cmdidNpmUpdateSingleModule:
case PkgCmdId.cmdidNpmUninstallModule:
if (null != this._projectNode.ModulesNode &&
!this._projectNode.ModulesNode.IsCurrentStateASuppressCommandsMode())
{
result = QueryStatusResult.ENABLED | QueryStatusResult.SUPPORTED;
}
else
{
result = QueryStatusResult.SUPPORTED;
}
return VSConstants.S_OK;
case PkgCmdId.cmdidNpmInstallModules:
case PkgCmdId.cmdidNpmUpdateModules:
result = QueryStatusResult.SUPPORTED | QueryStatusResult.INVISIBLE;
return VSConstants.S_OK;
}
}
}
else if (cmdGroup == Microsoft.VisualStudioTools.Project.VsMenus.guidStandardCommandSet2K)
{
switch ((VsCommands2K)cmd)
{
case CommonConstants.OpenFolderInExplorerCmdId:
result = QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (cmdGroup == Guids.NodejsNpmCmdSet)
{
switch (cmd)
{
case PkgCmdId.cmdidNpmOpenModuleHomepage:
if (this.Package.Homepages != null)
{
using (var enumerator = this.Package.Homepages.GetEnumerator())
{
if (enumerator.MoveNext() && !string.IsNullOrEmpty(enumerator.Current))
{
Process.Start(enumerator.Current);
}
}
}
return VSConstants.S_OK;
}
if (null == this._parent)
{
switch (cmd)
{
case PkgCmdId.cmdidNpmInstallSingleMissingModule:
if (null != this._projectNode.ModulesNode)
{
var t = this._projectNode.ModulesNode.InstallMissingModule(this);
}
return VSConstants.S_OK;
case PkgCmdId.cmdidNpmUninstallModule:
if (null != this._projectNode.ModulesNode)
{
var t = this._projectNode.ModulesNode.UninstallModule(this);
}
return VSConstants.S_OK;
case PkgCmdId.cmdidNpmUpdateSingleModule:
if (null != this._projectNode.ModulesNode)
{
var t = this._projectNode.ModulesNode.UpdateModule(this);
}
return VSConstants.S_OK;
}
}
}
else if (cmdGroup == Microsoft.VisualStudioTools.Project.VsMenus.guidStandardCommandSet2K)
{
switch ((VsCommands2K)cmd)
{
case CommonConstants.OpenFolderInExplorerCmdId:
var path = this.Package.Path;
try
{
Process.Start(path);
}
catch (Exception ex)
{
if (ex is InvalidOperationException || ex is Win32Exception)
{
MessageBox.Show(
string.Format(CultureInfo.CurrentCulture, Resources.DependencyNodeModuleDoesNotExist, path),
SR.ProductName,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return VSConstants.S_FALSE;
}
throw;
}
return VSConstants.S_OK;
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
#endregion
private static string GetInitialPackageDisplayString(IPackage package)
{
var buff = new StringBuilder(package.Name);
if (package.IsMissing)
{
buff.Append(string.Format(CultureInfo.CurrentCulture, " ({0})", Resources.DependencyNodeLabelMissing));
}
else
{
buff.Append('@');
buff.Append(package.Version);
if (!package.IsListedInParentPackageJson)
{
buff.AppendFormat(string.Format(CultureInfo.CurrentCulture, " ({0})",
string.Format(CultureInfo.CurrentCulture, Resources.DependencyNodeLabelNotListed, NodejsConstants.PackageJsonFile)));
}
else
{
var dependencyTypes = GetDependencyTypeNames(package);
if (package.IsDevDependency || package.IsOptionalDependency)
{
buff.Append(" (");
buff.Append(string.Join(", ", dependencyTypes.ToArray()));
buff.Append(")");
}
}
}
if (package.IsBundledDependency)
{
buff.Append(string.Format(CultureInfo.CurrentCulture, "[{0}]",
Resources.DependencyNodeLabelBundled));
}
return buff.ToString();
}
private static List<string> GetDependencyTypeNames(IPackage package)
{
var dependencyTypes = new List<string>(3);
if (package.IsDependency)
{
dependencyTypes.Add("standard");
}
if (package.IsDevDependency)
{
dependencyTypes.Add("dev");
}
if (package.IsOptionalDependency)
{
dependencyTypes.Add("optional");
}
return dependencyTypes;
}
}
}
| |
namespace AspNetWebApi.Areas.HelpPage
{
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;
/// <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()
{
this.ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
this.ActionSamples = new Dictionary<HelpPageSampleKey, object>();
this.SampleObjects = new Dictionary<Type, object>();
}
/// <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 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 this.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 this.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 = this.ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = this.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 = this.GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = this.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 = this.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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (this.ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
this.ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
this.ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), 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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!this.SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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 (this.ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
this.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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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 static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
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 this.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;
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace Aurora.Modules.Land
{
public class ParcelCounts
{
public int Group;
public Dictionary<UUID, ISceneEntity> Objects = new Dictionary<UUID, ISceneEntity>();
public int Others;
public int Owner;
public int Selected;
public int Temporary;
public Dictionary<UUID, int> Users =
new Dictionary<UUID, int>();
}
public class PrimCountModule : IPrimCountModule, INonSharedRegionModule
{
private readonly Dictionary<UUID, UUID> m_OwnerMap =
new Dictionary<UUID, UUID>();
private readonly Dictionary<UUID, ParcelCounts> m_ParcelCounts =
new Dictionary<UUID, ParcelCounts>();
private readonly Dictionary<UUID, PrimCounts> m_PrimCounts =
new Dictionary<UUID, PrimCounts>();
private readonly Dictionary<UUID, int> m_SimwideCounts =
new Dictionary<UUID, int>();
// For now, a simple simwide taint to get this up. Later parcel based
// taint to allow recounting a parcel if only ownership has changed
// without recounting the whole sim.
private readonly Object m_TaintLock = new Object();
private IScene m_Scene;
private bool m_Tainted = true;
#region INonSharedRegionModule Members
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
}
public void AddRegion(IScene scene)
{
m_Scene = scene;
scene.RegisterModuleInterface<IPrimCountModule>(this);
m_Scene.EventManager.OnObjectBeingAddedToScene +=
OnPrimCountAdd;
m_Scene.EventManager.OnObjectBeingRemovedFromScene +=
OnObjectBeingRemovedFromScene;
m_Scene.EventManager.OnLandObjectAdded += OnLandObjectAdded;
m_Scene.EventManager.OnLandObjectRemoved += OnLandObjectRemoved;
m_Scene.AuroraEventManager.RegisterEventHandler("ObjectChangedOwner", OnGenericEvent);
m_Scene.AuroraEventManager.RegisterEventHandler("ObjectEnteringNewParcel", OnGenericEvent);
}
public void RegionLoaded(IScene scene)
{
}
public void RemoveRegion(IScene scene)
{
m_Scene.UnregisterModuleInterface<IPrimCountModule>(this);
m_Scene.EventManager.OnObjectBeingAddedToScene -=
OnPrimCountAdd;
m_Scene.EventManager.OnObjectBeingRemovedFromScene -=
OnObjectBeingRemovedFromScene;
m_Scene.EventManager.OnLandObjectAdded -= OnLandObjectAdded;
m_Scene.EventManager.OnLandObjectRemoved -= OnLandObjectRemoved;
m_Scene.AuroraEventManager.UnregisterEventHandler("ObjectChangedOwner", OnGenericEvent);
m_Scene.AuroraEventManager.UnregisterEventHandler("ObjectEnteringNewParcel", OnGenericEvent);
m_Scene = null;
}
public void Close()
{
}
public string Name
{
get { return "PrimCountModule"; }
}
#endregion
#region IPrimCountModule Members
public void TaintPrimCount(ILandObject land)
{
lock (m_TaintLock)
m_Tainted = true;
}
public void TaintPrimCount(int x, int y)
{
lock (m_TaintLock)
m_Tainted = true;
}
public void TaintPrimCount()
{
lock (m_TaintLock)
m_Tainted = true;
}
public int GetParcelMaxPrimCount(ILandObject thisObject)
{
// Normal Calculations
return (int) Math.Round(((float) thisObject.LandData.Area/
(256*256))*
m_Scene.RegionInfo.ObjectCapacity*
(float) m_Scene.RegionInfo.RegionSettings.ObjectBonus);
}
public IPrimCounts GetPrimCounts(UUID parcelID)
{
PrimCounts primCounts;
lock (m_PrimCounts)
{
if (m_PrimCounts.TryGetValue(parcelID, out primCounts))
return primCounts;
primCounts = new PrimCounts(parcelID, this);
m_PrimCounts[parcelID] = primCounts;
}
return primCounts;
}
#endregion
private void OnPrimCountAdd(ISceneEntity obj)
{
// If we're tainted already, don't bother to add. The next
// access will cause a recount anyway
lock (m_TaintLock)
{
if (!m_Tainted)
AddObject(obj);
}
}
private void OnObjectBeingRemovedFromScene(ISceneEntity obj)
{
// Don't bother to update tainted counts
lock (m_TaintLock)
{
if (!m_Tainted)
RemoveObject(obj);
}
}
private void OnParcelPrimCountTainted()
{
lock (m_TaintLock)
m_Tainted = true;
}
private void SelectObject(ISceneEntity obj, bool IsNowSelected)
{
if (obj.IsAttachment)
return;
if (((obj.RootChild.Flags & PrimFlags.TemporaryOnRez) != 0))
return;
Vector3 pos = obj.AbsolutePosition;
ILandObject landObject = m_Scene.RequestModuleInterface<IParcelManagementModule>().GetLandObject(pos.X,
pos.Y);
LandData landData = landObject.LandData;
ParcelCounts parcelCounts;
if (m_ParcelCounts.TryGetValue(landData.GlobalID, out parcelCounts))
{
int partCount = obj.ChildrenEntities().Count;
if (IsNowSelected)
parcelCounts.Selected += partCount;
else
parcelCounts.Selected -= partCount;
}
}
// NOTE: Call under Taint Lock
private void AddObject(ISceneEntity obj)
{
if (obj.IsAttachment)
return;
if (((obj.RootChild.Flags & PrimFlags.TemporaryOnRez) != 0))
return;
Vector3 pos = obj.AbsolutePosition;
ILandObject landObject = m_Scene.RequestModuleInterface<IParcelManagementModule>().GetLandObject(pos.X,
pos.Y);
if (landObject == null)
return;
LandData landData = landObject.LandData;
ParcelCounts parcelCounts;
if (m_ParcelCounts.TryGetValue(landData.GlobalID, out parcelCounts))
{
UUID landOwner = landData.OwnerID;
parcelCounts.Objects[obj.UUID] = obj;
m_SimwideCounts[landOwner] += obj.PrimCount;
if (parcelCounts.Users.ContainsKey(obj.OwnerID))
parcelCounts.Users[obj.OwnerID] += obj.PrimCount;
else
parcelCounts.Users[obj.OwnerID] = obj.PrimCount;
if (landData.IsGroupOwned)
{
if (obj.OwnerID == landData.GroupID)
parcelCounts.Owner += obj.PrimCount;
else if (obj.GroupID == landData.GroupID)
parcelCounts.Group += obj.PrimCount;
else
parcelCounts.Others += obj.PrimCount;
}
else
{
if (obj.OwnerID == landData.OwnerID)
parcelCounts.Owner += obj.PrimCount;
else if (obj.GroupID == landData.GroupID)
parcelCounts.Group += obj.PrimCount;
else
parcelCounts.Others += obj.PrimCount;
}
}
}
// NOTE: Call under Taint Lock
private void RemoveObject(ISceneEntity obj)
{
if (obj.IsAttachment)
return;
if (((obj.RootChild.Flags & PrimFlags.TemporaryOnRez) != 0))
return;
Vector3 pos = obj.AbsolutePosition;
ILandObject landObject = m_Scene.RequestModuleInterface<IParcelManagementModule>().GetLandObject(pos.X,
pos.Y);
if (landObject == null)
landObject = m_Scene.RequestModuleInterface<IParcelManagementModule>().GetNearestAllowedParcel(
UUID.Zero, pos.X, pos.Y);
if (landObject == null)
return;
LandData landData = landObject.LandData;
ParcelCounts parcelCounts;
if (m_ParcelCounts.TryGetValue(landData.GlobalID, out parcelCounts))
{
UUID landOwner = landData.OwnerID;
foreach (ISceneChildEntity child in obj.ChildrenEntities())
{
if (!parcelCounts.Objects.ContainsKey(child.UUID))
{
//Well... now what?
}
else
{
parcelCounts.Objects.Remove(child.UUID);
if (m_SimwideCounts.ContainsKey(landOwner))
m_SimwideCounts[landOwner] -= 1;
if (parcelCounts.Users.ContainsKey(obj.OwnerID))
parcelCounts.Users[obj.OwnerID] -= 1;
if (landData.IsGroupOwned)
{
if (obj.OwnerID == landData.GroupID)
parcelCounts.Owner -= 1;
else if (obj.GroupID == landData.GroupID)
parcelCounts.Group -= 1;
else
parcelCounts.Others -= 1;
}
else
{
if (obj.OwnerID == landData.OwnerID)
parcelCounts.Owner -= 1;
else if (obj.GroupID == landData.GroupID)
parcelCounts.Group -= 1;
else
parcelCounts.Others -= 1;
}
}
}
}
}
public Dictionary<UUID, int> GetAllUserCounts(UUID parcelID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
{
return new Dictionary<UUID, int>(counts.Users);
}
}
return new Dictionary<UUID, int>();
}
public List<ISceneEntity> GetParcelObjects(UUID parcelID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
{
return new List<ISceneEntity>(counts.Objects.Values);
}
}
return new List<ISceneEntity>();
}
public int GetOwnerCount(UUID parcelID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
return counts.Owner;
}
return 0;
}
public int GetGroupCount(UUID parcelID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
return counts.Group;
}
return 0;
}
public int GetOthersCount(UUID parcelID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
return counts.Others;
}
return 0;
}
public int GetSelectedCount(UUID parcelID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
return counts.Selected;
}
return 0;
}
public int GetSimulatorCount(UUID parcelID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
UUID owner;
if (m_OwnerMap.TryGetValue(parcelID, out owner))
{
int val;
if (m_SimwideCounts.TryGetValue(owner, out val))
return val;
}
}
return 0;
}
public int GetTemporaryCount(UUID parcelID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
return counts.Temporary;
}
return 0;
}
public int GetUserCount(UUID parcelID, UUID userID)
{
lock (m_TaintLock)
{
if (m_Tainted)
Recount();
ParcelCounts counts;
if (m_ParcelCounts.TryGetValue(parcelID, out counts))
{
int val;
if (counts.Users.TryGetValue(userID, out val))
return val;
}
}
return 0;
}
// NOTE: This method MUST be called while holding the taint lock!
private void Recount()
{
m_OwnerMap.Clear();
m_SimwideCounts.Clear();
m_ParcelCounts.Clear();
List<ILandObject> land = m_Scene.RequestModuleInterface<IParcelManagementModule>().AllParcels();
#if (!ISWIN)
foreach (ILandObject l in land)
{
LandData landData = l.LandData;
m_OwnerMap[landData.GlobalID] = landData.OwnerID;
m_SimwideCounts[landData.OwnerID] = 0;
m_ParcelCounts[landData.GlobalID] = new ParcelCounts();
}
#else
foreach (LandData landData in land.Select(l => l.LandData))
{
m_OwnerMap[landData.GlobalID] = landData.OwnerID;
m_SimwideCounts[landData.OwnerID] = 0;
m_ParcelCounts[landData.GlobalID] = new ParcelCounts();
}
#endif
ISceneEntity[] objlist = m_Scene.Entities.GetEntities();
foreach (ISceneEntity obj in objlist)
{
try
{
if (obj is SceneObjectGroup)
AddObject(obj);
}
catch (Exception e)
{
// Catch it and move on. This includes situations where splist has inconsistent info
MainConsole.Instance.WarnFormat("[ParcelPrimCountModule]: Problem processing action in Recount: {0}", e);
}
}
List<UUID> primcountKeys = new List<UUID>(m_PrimCounts.Keys);
#if (!ISWIN)
foreach (UUID k in primcountKeys)
{
if (!m_OwnerMap.ContainsKey(k))
{
m_PrimCounts.Remove(k);
}
}
#else
foreach (UUID k in primcountKeys.Where(k => !m_OwnerMap.ContainsKey(k)))
{
m_PrimCounts.Remove(k);
}
#endif
m_Tainted = false;
}
private void OnLandObjectRemoved(UUID RegionID, UUID globalID)
{
//Taint everything... we don't know what might have hapened
TaintPrimCount();
}
private void OnLandObjectAdded(LandData newParcel)
{
//Taint it!
TaintPrimCount(m_Scene.RequestModuleInterface<IParcelManagementModule>().GetLandObject(newParcel.GlobalID));
}
private object OnGenericEvent(string FunctionName, object parameters)
{
//The 'select' part of prim counts isn't for this type of selection
//if (FunctionName == "ObjectSelected" || FunctionName == "ObjectDeselected")
//{
// //Select the object now
// SelectObject(((SceneObjectPart)parameters).ParentGroup, FunctionName == "ObjectSelected");
//}
if (FunctionName == "ObjectChangedOwner")
{
TaintPrimCount((int) ((SceneObjectGroup) parameters).AbsolutePosition.X,
(int) ((SceneObjectGroup) parameters).AbsolutePosition.Y);
}
else if (FunctionName == "ObjectEnteringNewParcel")
{
//Taint the parcels
//SceneObjectGroup grp = (((Object[])parameters)[0]) as SceneObjectGroup;
UUID newParcel = (UUID) (((Object[]) parameters)[1]);
UUID oldParcel = (UUID) (((Object[]) parameters)[2]);
ILandObject oldlandObject =
m_Scene.RequestModuleInterface<IParcelManagementModule>().GetLandObject(oldParcel);
ILandObject newlandObject =
m_Scene.RequestModuleInterface<IParcelManagementModule>().GetLandObject(newParcel);
TaintPrimCount(oldlandObject);
TaintPrimCount(newlandObject);
}
return null;
}
}
public class PrimCounts : IPrimCounts
{
private readonly UUID m_ParcelID;
private readonly PrimCountModule m_Parent;
private readonly UserPrimCounts m_UserPrimCounts;
public PrimCounts(UUID parcelID, PrimCountModule parent)
{
m_ParcelID = parcelID;
m_Parent = parent;
m_UserPrimCounts = new UserPrimCounts(this);
}
#region IPrimCounts Members
public int Owner
{
get { return m_Parent.GetOwnerCount(m_ParcelID); }
}
public int Group
{
get { return m_Parent.GetGroupCount(m_ParcelID); }
}
public List<ISceneEntity> Objects
{
get { return m_Parent.GetParcelObjects(m_ParcelID); }
}
public int Others
{
get { return m_Parent.GetOthersCount(m_ParcelID); }
}
public int Selected
{
get { return m_Parent.GetSelectedCount(m_ParcelID); }
}
public int Simulator
{
get { return m_Parent.GetSimulatorCount(m_ParcelID); }
}
public int Temporary
{
get { return m_Parent.GetTemporaryCount(m_ParcelID); }
}
public int Total
{
get { return this.Group + this.Owner + this.Others; }
}
public IUserPrimCounts Users
{
get { return m_UserPrimCounts; }
}
public Dictionary<UUID, int> GetAllUserCounts()
{
return m_Parent.GetAllUserCounts(m_ParcelID);
}
#endregion
public int GetUserCount(UUID userID)
{
return m_Parent.GetUserCount(m_ParcelID, userID);
}
}
public class UserPrimCounts : IUserPrimCounts
{
private readonly PrimCounts m_Parent;
public UserPrimCounts(PrimCounts parent)
{
m_Parent = parent;
}
#region IUserPrimCounts Members
public int this[UUID userID]
{
get { return m_Parent.GetUserCount(userID); }
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using BulletSharp.Math;
namespace BulletSharp
{
public class MultiBody : IDisposable
{
internal IntPtr _native;
MultiBodyLink[] _links;
internal MultiBody(IntPtr native)
{
_native = native;
}
public MultiBody(int nLinks, float mass, Vector3 inertia, bool fixedBase, bool canSleep)
{
_native = btMultiBody_new(nLinks, mass, ref inertia, fixedBase, canSleep);
}
public void AddBaseConstraintForce(Vector3 f)
{
btMultiBody_addBaseConstraintForce(_native, ref f);
}
public void AddBaseConstraintTorque(Vector3 t)
{
btMultiBody_addBaseConstraintTorque(_native, ref t);
}
public void AddBaseForce(Vector3 f)
{
btMultiBody_addBaseForce(_native, ref f);
}
public void AddBaseTorque(Vector3 t)
{
btMultiBody_addBaseTorque(_native, ref t);
}
public void AddJointTorque(int i, float q)
{
btMultiBody_addJointTorque(_native, i, q);
}
public void AddJointTorqueMultiDof(int i, float[] q)
{
btMultiBody_addJointTorqueMultiDof(_native, i, q);
}
public void AddJointTorqueMultiDof(int i, int dof, float q)
{
btMultiBody_addJointTorqueMultiDof2(_native, i, dof, q);
}
public void AddLinkConstraintForce(int i, Vector3 f)
{
btMultiBody_addLinkConstraintForce(_native, i, ref f);
}
public void AddLinkConstraintTorque(int i, Vector3 t)
{
btMultiBody_addLinkConstraintTorque(_native, i, ref t);
}
public void AddLinkForce(int i, Vector3 f)
{
btMultiBody_addLinkForce(_native, i, ref f);
}
public void AddLinkTorque(int i, Vector3 t)
{
btMultiBody_addLinkTorque(_native, i, ref t);
}
/*
public void ApplyDeltaVeeMultiDof(float deltaVee, float multiplier)
{
btMultiBody_applyDeltaVeeMultiDof(_native, deltaVee._native, multiplier);
}
public void ApplyDeltaVeeMultiDof2(float deltaVee, float multiplier)
{
btMultiBody_applyDeltaVeeMultiDof2(_native, deltaVee._native, multiplier);
}
public void CalcAccelerationDeltasMultiDof(float force, float output, AlignedObjectArray scratchR, AlignedObjectArray scratchV)
{
btMultiBody_calcAccelerationDeltasMultiDof(_native, force._native, output._native, scratchR._native, scratchV._native);
}
*/
public int CalculateSerializeBufferSize()
{
return btMultiBody_calculateSerializeBufferSize(_native);
}
public void CheckMotionAndSleepIfRequired(float timestep)
{
btMultiBody_checkMotionAndSleepIfRequired(_native, timestep);
}
public void ClearConstraintForces()
{
btMultiBody_clearConstraintForces(_native);
}
public void ClearForcesAndTorques()
{
btMultiBody_clearForcesAndTorques(_native);
}
public void ClearVelocities()
{
btMultiBody_clearVelocities(_native);
}
/*
public void ComputeAccelerationsArticulatedBodyAlgorithmMultiDof(float deltaTime, AlignedObjectArray scratchR, AlignedObjectArray scratchV, AlignedObjectArray scratchM)
{
btMultiBody_computeAccelerationsArticulatedBodyAlgorithmMultiDof(_native, deltaTime, scratchR._native, scratchV._native, scratchM._native);
}
public void ComputeAccelerationsArticulatedBodyAlgorithmMultiDof(float deltaTime, AlignedObjectArray scratchR, AlignedObjectArray scratchV, AlignedObjectArray scratchM, bool isConstraintPass)
{
btMultiBody_computeAccelerationsArticulatedBodyAlgorithmMultiDof2(_native, deltaTime, scratchR._native, scratchV._native, scratchM._native, isConstraintPass);
}
public void FillConstraintJacobianMultiDof(int link, Vector3 contactPoint, Vector3 normalAng, Vector3 normalLin, float jac, AlignedObjectArray scratchR, AlignedObjectArray scratchV, AlignedObjectArray scratchM)
{
btMultiBody_fillConstraintJacobianMultiDof(_native, link, ref contactPoint, ref normalAng, ref normalLin, jac._native, scratchR._native, scratchV._native, scratchM._native);
}
public void FillContactJacobianMultiDof(int link, Vector3 contactPoint, Vector3 normal, float jac, AlignedObjectArray scratchR, AlignedObjectArray scratchV, AlignedObjectArray scratchM)
{
btMultiBody_fillContactJacobianMultiDof(_native, link, ref contactPoint, ref normal, jac._native, scratchR._native, scratchV._native, scratchM._native);
}
*/
public void FinalizeMultiDof()
{
btMultiBody_finalizeMultiDof(_native);
}
/*
public void ForwardKinematics(AlignedObjectArray scratchQ, AlignedObjectArray scratchM)
{
btMultiBody_forwardKinematics(_native, scratchQ._native, scratchM._native);
}
*/
public float GetJointPos(int i)
{
return btMultiBody_getJointPos(_native, i);
}
/*
public float GetJointPosMultiDof(int i)
{
return btMultiBody_getJointPosMultiDof(_native, i);
}
*/
public float GetJointTorque(int i)
{
return btMultiBody_getJointTorque(_native, i);
}
/*
public float GetJointTorqueMultiDof(int i)
{
return btMultiBody_getJointTorqueMultiDof(_native, i);
}
*/
public float GetJointVel(int i)
{
return btMultiBody_getJointVel(_native, i);
}
/*
public float GetJointVelMultiDof(int i)
{
return btMultiBody_getJointVelMultiDof(_native, i);
}
*/
public MultiBodyLink GetLink(int index)
{
if (_links == null) {
_links = new MultiBodyLink[NumLinks];
}
if (_links[index] == null) {
_links[index] = new MultiBodyLink(btMultiBody_getLink(_native, index));
}
return _links[index];
}
public Vector3 GetLinkForce(int i)
{
Vector3 value;
btMultiBody_getLinkForce(_native, i, out value);
return value;
}
public Vector3 GetLinkInertia(int i)
{
Vector3 value;
btMultiBody_getLinkInertia(_native, i, out value);
return value;
}
public float GetLinkMass(int i)
{
return btMultiBody_getLinkMass(_native, i);
}
public Vector3 GetLinkTorque(int i)
{
Vector3 value;
btMultiBody_getLinkTorque(_native, i, out value);
return value;
}
public int GetParent(int linkNum)
{
return btMultiBody_getParent(_native, linkNum);
}
public Quaternion GetParentToLocalRot(int i)
{
Quaternion value;
btMultiBody_getParentToLocalRot(_native, i, out value);
return value;
}
public Vector3 GetRVector(int i)
{
Vector3 value;
btMultiBody_getRVector(_native, i, out value);
return value;
}
public void GoToSleep()
{
btMultiBody_goToSleep(_native);
}
public bool InternalNeedsJointFeedback()
{
return btMultiBody_internalNeedsJointFeedback(_native);
}
public Vector3 LocalDirToWorld(int i, Vector3 vec)
{
Vector3 value;
btMultiBody_localDirToWorld(_native, i, ref vec, out value);
return value;
}
public Vector3 LocalPosToWorld(int i, Vector3 vec)
{
Vector3 value;
btMultiBody_localPosToWorld(_native, i, ref vec, out value);
return value;
}
public void ProcessDeltaVeeMultiDof2()
{
btMultiBody_processDeltaVeeMultiDof2(_native);
}
public string Serialize(IntPtr dataBuffer, Serializer serializer)
{
return Marshal.PtrToStringAnsi(btMultiBody_serialize(_native, dataBuffer, serializer._native));
}
public void SetJointPos(int i, float q)
{
btMultiBody_setJointPos(_native, i, q);
}
public void SetJointPosMultiDof(int i, float[] q)
{
btMultiBody_setJointPosMultiDof(_native, i, q);
}
public void SetJointVel(int i, float qdot)
{
btMultiBody_setJointVel(_native, i, qdot);
}
public void SetJointVelMultiDof(int i, float[] qdot)
{
btMultiBody_setJointVelMultiDof(_native, i, qdot);
}
public void SetPosUpdated(bool updated)
{
btMultiBody_setPosUpdated(_native, updated);
}
public void SetupFixed(int linkIndex, float mass, Vector3 inertia, int parent, Quaternion rotParentToThis, Vector3 parentComToThisPivotOffset, Vector3 thisPivotToThisComOffset)
{
btMultiBody_setupFixed(_native, linkIndex, mass, ref inertia, parent, ref rotParentToThis, ref parentComToThisPivotOffset, ref thisPivotToThisComOffset);
}
public void SetupPlanar(int i, float mass, Vector3 inertia, int parent, Quaternion rotParentToThis, Vector3 rotationAxis, Vector3 parentComToThisComOffset)
{
btMultiBody_setupPlanar(_native, i, mass, ref inertia, parent, ref rotParentToThis, ref rotationAxis, ref parentComToThisComOffset);
}
public void SetupPlanar(int i, float mass, Vector3 inertia, int parent, Quaternion rotParentToThis, Vector3 rotationAxis, Vector3 parentComToThisComOffset, bool disableParentCollision)
{
btMultiBody_setupPlanar2(_native, i, mass, ref inertia, parent, ref rotParentToThis, ref rotationAxis, ref parentComToThisComOffset, disableParentCollision);
}
public void SetupPrismatic(int i, float mass, Vector3 inertia, int parent, Quaternion rotParentToThis, Vector3 jointAxis, Vector3 parentComToThisPivotOffset, Vector3 thisPivotToThisComOffset, bool disableParentCollision)
{
btMultiBody_setupPrismatic(_native, i, mass, ref inertia, parent, ref rotParentToThis, ref jointAxis, ref parentComToThisPivotOffset, ref thisPivotToThisComOffset, disableParentCollision);
}
public void SetupRevolute(int linkIndex, float mass, Vector3 inertia, int parentIndex, Quaternion rotParentToThis, Vector3 jointAxis, Vector3 parentComToThisPivotOffset, Vector3 thisPivotToThisComOffset)
{
btMultiBody_setupRevolute(_native, linkIndex, mass, ref inertia, parentIndex, ref rotParentToThis, ref jointAxis, ref parentComToThisPivotOffset, ref thisPivotToThisComOffset);
}
public void SetupRevolute(int linkIndex, float mass, Vector3 inertia, int parentIndex, Quaternion rotParentToThis, Vector3 jointAxis, Vector3 parentComToThisPivotOffset, Vector3 thisPivotToThisComOffset, bool disableParentCollision)
{
btMultiBody_setupRevolute2(_native, linkIndex, mass, ref inertia, parentIndex, ref rotParentToThis, ref jointAxis, ref parentComToThisPivotOffset, ref thisPivotToThisComOffset, disableParentCollision);
}
public void SetupSpherical(int linkIndex, float mass, Vector3 inertia, int parent, Quaternion rotParentToThis, Vector3 parentComToThisPivotOffset, Vector3 thisPivotToThisComOffset)
{
btMultiBody_setupSpherical(_native, linkIndex, mass, ref inertia, parent, ref rotParentToThis, ref parentComToThisPivotOffset, ref thisPivotToThisComOffset);
}
public void SetupSpherical(int linkIndex, float mass, Vector3 inertia, int parent, Quaternion rotParentToThis, Vector3 parentComToThisPivotOffset, Vector3 thisPivotToThisComOffset, bool disableParentCollision)
{
btMultiBody_setupSpherical2(_native, linkIndex, mass, ref inertia, parent, ref rotParentToThis, ref parentComToThisPivotOffset, ref thisPivotToThisComOffset, disableParentCollision);
}
public void StepPositionsMultiDof(float deltaTime)
{
btMultiBody_stepPositionsMultiDof(_native, deltaTime);
}
public void StepPositionsMultiDof(float deltaTime, float[] pq)
{
btMultiBody_stepPositionsMultiDof2(_native, deltaTime, pq);
}
public void StepPositionsMultiDof(float deltaTime, float[] pq, float[] pqd)
{
btMultiBody_stepPositionsMultiDof3(_native, deltaTime, pq, pqd);
}
/*
public void UpdateCollisionObjectWorldTransforms(AlignedObjectArray scratchQ, AlignedObjectArray scratchM)
{
btMultiBody_updateCollisionObjectWorldTransforms(_native, scratchQ._native, scratchM._native);
}
*/
public void WakeUp()
{
btMultiBody_wakeUp(_native);
}
public Vector3 WorldDirToLocal(int i, Vector3 vec)
{
Vector3 value;
btMultiBody_worldDirToLocal(_native, i, ref vec, out value);
return value;
}
public Vector3 WorldPosToLocal(int i, Vector3 vec)
{
Vector3 value;
btMultiBody_worldPosToLocal(_native, i, ref vec, out value);
return value;
}
public float AngularDamping
{
get { return btMultiBody_getAngularDamping(_native); }
set { btMultiBody_setAngularDamping(_native, value); }
}
public Vector3 AngularMomentum
{
get
{
Vector3 value;
btMultiBody_getAngularMomentum(_native, out value);
return value;
}
}
public MultiBodyLinkCollider BaseCollider
{
get { return CollisionObject.GetManaged(btMultiBody_getBaseCollider(_native)) as MultiBodyLinkCollider; }
set { btMultiBody_setBaseCollider(_native, value._native); }
}
public Vector3 BaseForce
{
get
{
Vector3 value;
btMultiBody_getBaseForce(_native, out value);
return value;
}
}
public Vector3 BaseInertia
{
get
{
Vector3 value;
btMultiBody_getBaseInertia(_native, out value);
return value;
}
set { btMultiBody_setBaseInertia(_native, ref value); }
}
public float BaseMass
{
get { return btMultiBody_getBaseMass(_native); }
set { btMultiBody_setBaseMass(_native, value); }
}
/*
public char BaseName
{
get { return btMultiBody_getBaseName(_native); }
set { btMultiBody_setBaseName(_native, value._native); }
}
*/
public Vector3 BaseOmega
{
get
{
Vector3 value;
btMultiBody_getBaseOmega(_native, out value);
return value;
}
set { btMultiBody_setBaseOmega(_native, ref value); }
}
public Vector3 BasePosition
{
get
{
Vector3 value;
btMultiBody_getBasePos(_native, out value);
return value;
}
set { btMultiBody_setBasePos(_native, ref value); }
}
public Vector3 BaseTorque
{
get
{
Vector3 value;
btMultiBody_getBaseTorque(_native, out value);
return value;
}
}
public Vector3 BaseVelocity
{
get
{
Vector3 value;
btMultiBody_getBaseVel(_native, out value);
return value;
}
set { btMultiBody_setBaseVel(_native, ref value); }
}
public Matrix BaseWorldTransform
{
get
{
Matrix value;
btMultiBody_getBaseWorldTransform(_native, out value);
return value;
}
set { btMultiBody_setBaseWorldTransform(_native, ref value); }
}
public bool CanSleep
{
get { return btMultiBody_getCanSleep(_native); }
set { btMultiBody_setCanSleep(_native, value); }
}
public int CompanionId
{
get { return btMultiBody_getCompanionId(_native); }
set { btMultiBody_setCompanionId(_native, value); }
}
public bool HasFixedBase
{
get { return btMultiBody_hasFixedBase(_native); }
}
public bool HasSelfCollision
{
get { return btMultiBody_hasSelfCollision(_native); }
set { btMultiBody_setHasSelfCollision(_native, value); }
}
public bool IsAwake
{
get { return btMultiBody_isAwake(_native); }
}
public bool IsPosUpdated
{
get { return btMultiBody_isPosUpdated(_native); }
}
public bool IsUsingGlobalVelocities
{
get { return btMultiBody_isUsingGlobalVelocities(_native); }
set { btMultiBody_useGlobalVelocities(_native, value); }
}
public bool IsUsingRK4Integration
{
get { return btMultiBody_isUsingRK4Integration(_native); }
set { btMultiBody_useRK4Integration(_native, value); }
}
public float KineticEnergy
{
get { return btMultiBody_getKineticEnergy(_native); }
}
public float LinearDamping
{
get { return btMultiBody_getLinearDamping(_native); }
set { btMultiBody_setLinearDamping(_native, value); }
}
public float MaxAppliedImpulse
{
get { return btMultiBody_getMaxAppliedImpulse(_native); }
set { btMultiBody_setMaxAppliedImpulse(_native, value); }
}
public float MaxCoordinateVelocity
{
get { return btMultiBody_getMaxCoordinateVelocity(_native); }
set { btMultiBody_setMaxCoordinateVelocity(_native, value); }
}
public int NumDofs
{
get { return btMultiBody_getNumDofs(_native); }
}
public int NumLinks
{
get { return btMultiBody_getNumLinks(_native); }
set
{
btMultiBody_setNumLinks(_native, value);
if (_links != null)
{
Array.Resize(ref _links, value);
}
}
}
public int NumPosVars
{
get { return btMultiBody_getNumPosVars(_native); }
}
public bool UseGyroTerm
{
get { return btMultiBody_getUseGyroTerm(_native); }
set { btMultiBody_setUseGyroTerm(_native, value); }
}
/*
public float VelocityVector
{
get { return btMultiBody_getVelocityVector(_native); }
}
*/
public Quaternion WorldToBaseRot
{
get
{
Quaternion value;
btMultiBody_getWorldToBaseRot(_native, out value);
return value;
}
set { btMultiBody_setWorldToBaseRot(_native, ref value); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
btMultiBody_delete(_native);
_native = IntPtr.Zero;
}
}
~MultiBody()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_new(int n_links, float mass, [In] ref Vector3 inertia, bool fixedBase, bool canSleep);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addBaseConstraintForce(IntPtr obj, [In] ref Vector3 f);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addBaseConstraintTorque(IntPtr obj, [In] ref Vector3 t);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addBaseForce(IntPtr obj, [In] ref Vector3 f);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addBaseTorque(IntPtr obj, [In] ref Vector3 t);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addJointTorque(IntPtr obj, int i, float Q);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addJointTorqueMultiDof(IntPtr obj, int i, float[] Q);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addJointTorqueMultiDof2(IntPtr obj, int i, int dof, float Q);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addLinkConstraintForce(IntPtr obj, int i, [In] ref Vector3 f);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addLinkConstraintTorque(IntPtr obj, int i, [In] ref Vector3 t);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addLinkForce(IntPtr obj, int i, [In] ref Vector3 f);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_addLinkTorque(IntPtr obj, int i, [In] ref Vector3 t);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_applyDeltaVeeMultiDof(IntPtr obj, float[] delta_vee, float multiplier);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_applyDeltaVeeMultiDof2(IntPtr obj, float[] delta_vee, float multiplier);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_calcAccelerationDeltasMultiDof(IntPtr obj, float[] force, float[] output, IntPtr scratch_r, IntPtr scratch_v);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBody_calculateSerializeBufferSize(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_checkMotionAndSleepIfRequired(IntPtr obj, float timestep);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_clearConstraintForces(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_clearForcesAndTorques(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_clearVelocities(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_computeAccelerationsArticulatedBodyAlgorithmMultiDof(IntPtr obj, float dt, IntPtr scratch_r, IntPtr scratch_v, IntPtr scratch_m);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_computeAccelerationsArticulatedBodyAlgorithmMultiDof2(IntPtr obj, float dt, IntPtr scratch_r, IntPtr scratch_v, IntPtr scratch_m, bool isConstraintPass);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_fillConstraintJacobianMultiDof(IntPtr obj, int link, [In] ref Vector3 contact_point, [In] ref Vector3 normal_ang, [In] ref Vector3 normal_lin, float[] jac, IntPtr scratch_r, IntPtr scratch_v, IntPtr scratch_m);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_fillContactJacobianMultiDof(IntPtr obj, int link, [In] ref Vector3 contact_point, [In] ref Vector3 normal, float[] jac, IntPtr scratch_r, IntPtr scratch_v, IntPtr scratch_m);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_finalizeMultiDof(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_forwardKinematics(IntPtr obj, IntPtr scratch_q, IntPtr scratch_m);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getAngularDamping(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getAngularMomentum(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_getBaseCollider(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getBaseForce(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getBaseInertia(IntPtr obj, [Out] out Vector3 inertia);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getBaseMass(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_getBaseName(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getBaseOmega(IntPtr obj, [Out] out Vector3 omega);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getBasePos(IntPtr obj, [Out] out Vector3 pos);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getBaseTorque(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getBaseVel(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getBaseWorldTransform(IntPtr obj, [Out] out Matrix tr);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_getCanSleep(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBody_getCompanionId(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getJointPos(IntPtr obj, int i);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_getJointPosMultiDof(IntPtr obj, int i);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getJointTorque(IntPtr obj, int i);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_getJointTorqueMultiDof(IntPtr obj, int i);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getJointVel(IntPtr obj, int i);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_getJointVelMultiDof(IntPtr obj, int i);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getKineticEnergy(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getLinearDamping(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_getLink(IntPtr obj, int index);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getLinkForce(IntPtr obj, int i, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getLinkInertia(IntPtr obj, int i, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getLinkMass(IntPtr obj, int i);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getLinkTorque(IntPtr obj, int i, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getMaxAppliedImpulse(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBody_getMaxCoordinateVelocity(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBody_getNumDofs(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBody_getNumLinks(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBody_getNumPosVars(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBody_getParent(IntPtr obj, int link_num);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getParentToLocalRot(IntPtr obj, int i, [Out] out Quaternion value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getRVector(IntPtr obj, int i, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_getUseGyroTerm(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_getVelocityVector(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_getWorldToBaseRot(IntPtr obj, [Out] out Quaternion rot);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_goToSleep(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_hasFixedBase(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_hasSelfCollision(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_internalNeedsJointFeedback(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_isAwake(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_isPosUpdated(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_isUsingGlobalVelocities(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btMultiBody_isUsingRK4Integration(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_localDirToWorld(IntPtr obj, int i, [In] ref Vector3 vec, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_localPosToWorld(IntPtr obj, int i, [In] ref Vector3 vec, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_processDeltaVeeMultiDof2(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBody_serialize(IntPtr obj, IntPtr dataBuffer, IntPtr serializer);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setAngularDamping(IntPtr obj, float damp);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setBaseCollider(IntPtr obj, IntPtr collider);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setBaseInertia(IntPtr obj, [In] ref Vector3 inertia);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setBaseMass(IntPtr obj, float mass);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setBaseName(IntPtr obj, IntPtr name);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setBaseOmega(IntPtr obj, [In] ref Vector3 omega);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setBasePos(IntPtr obj, [In] ref Vector3 pos);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setBaseVel(IntPtr obj, [In] ref Vector3 vel);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setBaseWorldTransform(IntPtr obj, [In] ref Matrix tr);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setCanSleep(IntPtr obj, bool canSleep);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setCompanionId(IntPtr obj, int id);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setHasSelfCollision(IntPtr obj, bool hasSelfCollision);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setJointPos(IntPtr obj, int i, float q);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setJointPosMultiDof(IntPtr obj, int i, float[] q);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setJointVel(IntPtr obj, int i, float qdot);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setJointVelMultiDof(IntPtr obj, int i, float[] qdot);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setLinearDamping(IntPtr obj, float damp);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setMaxAppliedImpulse(IntPtr obj, float maxImp);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setMaxCoordinateVelocity(IntPtr obj, float maxVel);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setNumLinks(IntPtr obj, int numLinks);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setPosUpdated(IntPtr obj, bool updated);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setupFixed(IntPtr obj, int linkIndex, float mass, [In] ref Vector3 inertia, int parent, [In] ref Quaternion rotParentToThis, [In] ref Vector3 parentComToThisPivotOffset, [In] ref Vector3 thisPivotToThisComOffset);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setupPlanar(IntPtr obj, int i, float mass, [In] ref Vector3 inertia, int parent, [In] ref Quaternion rotParentToThis, [In] ref Vector3 rotationAxis, [In] ref Vector3 parentComToThisComOffset);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setupPlanar2(IntPtr obj, int i, float mass, [In] ref Vector3 inertia, int parent, [In] ref Quaternion rotParentToThis, [In] ref Vector3 rotationAxis, [In] ref Vector3 parentComToThisComOffset, bool disableParentCollision);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setupPrismatic(IntPtr obj, int i, float mass, [In] ref Vector3 inertia, int parent, [In] ref Quaternion rotParentToThis, [In] ref Vector3 jointAxis, [In] ref Vector3 parentComToThisPivotOffset, [In] ref Vector3 thisPivotToThisComOffset, bool disableParentCollision);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setupRevolute(IntPtr obj, int linkIndex, float mass, [In] ref Vector3 inertia, int parentIndex, [In] ref Quaternion rotParentToThis, [In] ref Vector3 jointAxis, [In] ref Vector3 parentComToThisPivotOffset, [In] ref Vector3 thisPivotToThisComOffset);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setupRevolute2(IntPtr obj, int linkIndex, float mass, [In] ref Vector3 inertia, int parentIndex, [In] ref Quaternion rotParentToThis, [In] ref Vector3 jointAxis, [In] ref Vector3 parentComToThisPivotOffset, [In] ref Vector3 thisPivotToThisComOffset, bool disableParentCollision);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setupSpherical(IntPtr obj, int linkIndex, float mass, [In] ref Vector3 inertia, int parent, [In] ref Quaternion rotParentToThis, [In] ref Vector3 parentComToThisPivotOffset, [In] ref Vector3 thisPivotToThisComOffset);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setupSpherical2(IntPtr obj, int linkIndex, float mass, [In] ref Vector3 inertia, int parent, [In] ref Quaternion rotParentToThis, [In] ref Vector3 parentComToThisPivotOffset, [In] ref Vector3 thisPivotToThisComOffset, bool disableParentCollision);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setUseGyroTerm(IntPtr obj, bool useGyro);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_setWorldToBaseRot(IntPtr obj, [In] ref Quaternion rot);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_stepPositionsMultiDof(IntPtr obj, float dt);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_stepPositionsMultiDof2(IntPtr obj, float dt, float[] pq);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_stepPositionsMultiDof3(IntPtr obj, float dt, float[] pq, float[] pqd);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_updateCollisionObjectWorldTransforms(IntPtr obj, IntPtr scratch_q, IntPtr scratch_m);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_useGlobalVelocities(IntPtr obj, bool use);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_useRK4Integration(IntPtr obj, bool use);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_wakeUp(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_worldDirToLocal(IntPtr obj, int i, [In] ref Vector3 vec, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_worldPosToLocal(IntPtr obj, int i, [In] ref Vector3 vec, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBody_delete(IntPtr obj);
}
}
| |
namespace SwtorCaster.Core.Services.Combat
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Caliburn.Micro;
using Domain;
using Domain.Log;
using Events;
using Factory;
using Logging;
using Parsing;
using Settings;
using static System.Environment;
public class RealTimeLogService : ICombatLogService
{
private Thread thread;
private FileInfo currentFile;
private DirectoryInfo logDirectory;
private readonly ILoggerService loggerService;
private readonly ISettingsService settingsService;
private readonly IEventAggregator eventAggregator;
private readonly IEventService eventService;
private readonly ICombatLogParser parser;
private readonly ICombatLogViewModelFactory logViewModelFactory;
private readonly Stopwatch clearStopwatch;
private readonly DispatcherTimer clearTimer;
public static string SwtorCombatLogPath => Path.Combine(GetFolderPath(SpecialFolder.MyDocuments), "Star Wars - The Old Republic", "CombatLogs");
public bool IsRunning { get; private set; }
private RealTimeLogService()
{
clearTimer = new DispatcherTimer(DispatcherPriority.Normal) { Interval = TimeSpan.FromSeconds(1), IsEnabled = true };
clearStopwatch = new Stopwatch();
clearTimer.Tick += ClearTimerOnTick;
}
public RealTimeLogService(
ILoggerService loggerService,
ISettingsService settingsService,
IEventAggregator eventAggregator,
IEventService eventService,
ICombatLogParser parser,
ICombatLogViewModelFactory logViewModelFactory) : this()
{
this.loggerService = loggerService;
this.settingsService = settingsService;
this.eventAggregator = eventAggregator;
this.eventService = eventService;
this.parser = parser;
this.logViewModelFactory = logViewModelFactory;
}
private DirectoryInfo GetLogDirectory()
{
var customDirectory = settingsService.Settings.CustomCombatLogDirectory;
if (!string.IsNullOrEmpty(customDirectory) && Directory.Exists(customDirectory)) return new DirectoryInfo(customDirectory);
return new DirectoryInfo(SwtorCombatLogPath);
}
public void Start()
{
if (IsRunning) return;
logDirectory = GetLogDirectory();
try
{
if (currentFile == null)
{
currentFile = GetLastFile();
}
StartWatcherNewCombatFile();
clearTimer.Start();
clearStopwatch.Start();
ReadCurrentFile();
loggerService.Log($"Parser service started.");
}
catch (Exception e)
{
loggerService.Log($"Error starting parser service: {e.Message}");
}
}
public void Stop()
{
IsRunning = false;
thread?.Abort();
clearStopwatch?.Stop();
clearTimer?.Stop();
thread = null;
loggerService.Log($"Parser service stopped");
}
private void StartWatcherNewCombatFile()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = SwtorCombatLogPath;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Filter = "combat_*.txt";
watcher.Created += new FileSystemEventHandler(NewCombatFile);
watcher.EnableRaisingEvents = true;
}
private void NewCombatFile(object source, FileSystemEventArgs e)
{
loggerService.Log($"Detected new file {e.Name}");
loggerService.Log($"Restarting parser service with new file");
currentFile = new FileInfo(e.FullPath);
Stop();
Start();
}
private FileInfo GetLastFile()
{
if (!Directory.Exists(logDirectory.FullName))
Directory.CreateDirectory(logDirectory.FullName);
var fileInfos = logDirectory.EnumerateFiles("combat_*.txt", SearchOption.TopDirectoryOnly);
FileInfo logInfo = fileInfos.OrderByDescending(x => x.LastWriteTime).FirstOrDefault();
return logInfo;
}
private void ClearTimerOnTick(object sender, EventArgs eventArgs)
{
if (!settingsService.Settings.EnableClearInactivity) return;
if (clearStopwatch.Elapsed.Seconds < settingsService.Settings.ClearAfterInactivity) return;
Application.Current.Dispatcher.Invoke(() =>
{
eventAggregator.PublishOnUIThread(new ParserMessage() { ClearLog = true });
});
}
private void ReadCurrentFile()
{
var file = currentFile;
if (file != null)
{
thread = new Thread(() => Read(file.FullName));
thread.Start();
IsRunning = true;
}
}
public void Read(string file)
{
using (var reader = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)))
{
reader.ReadToEnd();
while (thread != null)
{
if (!reader.EndOfStream)
{
try
{
var value = reader.ReadLine();
if (value != null)
{
Handle(value);
if (clearStopwatch.IsRunning)
{
clearStopwatch.Restart();
}
}
}
catch(Exception)
{
}
}
else
{
Thread.Sleep(500);
}
}
}
}
private void Handle(string value)
{
try
{
var logLine = parser.Parse(value);
eventService.Handle(logLine);
Application.Current.Dispatcher.Invoke(() => Render(logLine));
}
catch (Exception e)
{
loggerService.Log($"Error adding item: {e.Message}");
}
}
private void Render(CombatLogEvent logLine)
{
var viewModel = logViewModelFactory.Create(logLine);
eventAggregator.PublishOnUIThread(viewModel);
}
}
}
| |
// 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 Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ApiOperationPolicyOperations.
/// </summary>
public static partial class ApiOperationPolicyOperationsExtensions
{
/// <summary>
/// Get the policy configuration at the API Operation level.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current API
/// Management service instance.
/// </param>
public static PolicyContract Get(this IApiOperationPolicyOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId)
{
return operations.GetAsync(resourceGroupName, serviceName, apiId, operationId).GetAwaiter().GetResult();
}
/// <summary>
/// Get the policy configuration at the API Operation level.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PolicyContract> GetAsync(this IApiOperationPolicyOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, operationId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates policy configuration for the API Operation level.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='parameters'>
/// The policy contents to apply.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the Api Operation policy to update. A
/// value of "*" can be used for If-Match to unconditionally apply the
/// operation.
/// </param>
public static PolicyContract CreateOrUpdate(this IApiOperationPolicyOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, PolicyContract parameters, string ifMatch)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, apiId, operationId, parameters, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates policy configuration for the API Operation level.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='parameters'>
/// The policy contents to apply.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the Api Operation policy to update. A
/// value of "*" can be used for If-Match to unconditionally apply the
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PolicyContract> CreateOrUpdateAsync(this IApiOperationPolicyOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, PolicyContract parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, operationId, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the policy configuration at the Api Operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the Api Operation Policy to delete. A
/// value of "*" can be used for If-Match to unconditionally apply the
/// operation.
/// </param>
public static void Delete(this IApiOperationPolicyOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, string ifMatch)
{
operations.DeleteAsync(resourceGroupName, serviceName, apiId, operationId, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the policy configuration at the Api Operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='operationId'>
/// Operation identifier within an API. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the Api Operation Policy to delete. A
/// value of "*" can be used for If-Match to unconditionally apply the
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IApiOperationPolicyOperations operations, string resourceGroupName, string serviceName, string apiId, string operationId, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, operationId, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class ListRecordingsRequestDecoder
{
public const ushort BLOCK_LENGTH = 28;
public const ushort TEMPLATE_ID = 8;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private ListRecordingsRequestDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public ListRecordingsRequestDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public ListRecordingsRequestDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int FromRecordingIdId()
{
return 3;
}
public static int FromRecordingIdSinceVersion()
{
return 0;
}
public static int FromRecordingIdEncodingOffset()
{
return 16;
}
public static int FromRecordingIdEncodingLength()
{
return 8;
}
public static string FromRecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long FromRecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long FromRecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long FromRecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long FromRecordingId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int RecordCountId()
{
return 4;
}
public static int RecordCountSinceVersion()
{
return 0;
}
public static int RecordCountEncodingOffset()
{
return 24;
}
public static int RecordCountEncodingLength()
{
return 4;
}
public static string RecordCountMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int RecordCountNullValue()
{
return -2147483648;
}
public static int RecordCountMinValue()
{
return -2147483647;
}
public static int RecordCountMaxValue()
{
return 2147483647;
}
public int RecordCount()
{
return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[ListRecordingsRequest](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='fromRecordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("FromRecordingId=");
builder.Append(FromRecordingId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='recordCount', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("RecordCount=");
builder.Append(RecordCount());
Limit(originalLimit);
return builder;
}
}
}
| |
/*
* TestScanner.cs - Tests for the "JSScanner" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using CSUnit;
using System;
using Microsoft.JScript;
public class TestScanner : TestCase
{
// Constructor.
public TestScanner(String name)
: base(name)
{
// Nothing to do here.
}
// Set up for the tests.
protected override void Setup()
{
// Nothing to do here.
}
// Clean up after the tests.
protected override void Cleanup()
{
// Nothing to do here.
}
// Test scanner creation.
public void TestScannerCreate()
{
JSScanner scanner;
Context token;
scanner = JSScannerTest.TestCreateScanner("// comment\n");
scanner.GetNextToken();
token = JSScannerTest.TestGetTokenContext(scanner);
AssertEquals("Create (1)", JSToken.EndOfFile, token.GetToken());
}
// Test keyword recognition.
public void TestScannerKeywords()
{
JSScanner scanner;
Context token;
scanner = JSScannerTest.TestCreateScanner
("hello get switch assert \\assert switch0");
scanner.GetNextToken();
token = JSScannerTest.TestGetTokenContext(scanner);
AssertEquals("Keywords (1)", JSToken.Identifier,
token.GetToken());
AssertEquals("Keywords (2)", "hello",
JSScannerTest.TestGetIdentifierName(scanner));
scanner.GetNextToken();
AssertEquals("Keywords (3)", JSToken.Get,
token.GetToken());
AssertNull("Keywords (4)",
JSScannerTest.TestGetIdentifierName(scanner));
scanner.GetNextToken();
AssertEquals("Keywords (5)", JSToken.Switch,
token.GetToken());
AssertNull("Keywords (6)",
JSScannerTest.TestGetIdentifierName(scanner));
scanner.GetNextToken();
AssertEquals("Keywords (7)", JSToken.Assert,
token.GetToken());
AssertNull("Keywords (8)",
JSScannerTest.TestGetIdentifierName(scanner));
scanner.GetNextToken();
AssertEquals("Keywords (9)", JSToken.Identifier,
token.GetToken());
AssertEquals("Keywords (10)", "assert",
JSScannerTest.TestGetIdentifierName(scanner));
scanner.GetNextToken();
AssertEquals("Keywords (11)", JSToken.Identifier,
token.GetToken());
AssertEquals("Keywords (12)", "switch0",
JSScannerTest.TestGetIdentifierName(scanner));
scanner.GetNextToken();
AssertEquals("Keywords (13)",
JSToken.EndOfFile, token.GetToken());
}
// Test comment recognition.
public void TestScannerComments()
{
JSScanner scanner;
Context token;
scanner = JSScannerTest.TestCreateScanner
("#!/usr/local/bin/ilrun\n" +
"hello// single-line comment\r" +
"/* multi-line 1 */ switch /* multi-line\r\n" +
"2 */ assert /= / /*");
scanner.GetNextToken();
token = JSScannerTest.TestGetTokenContext(scanner);
AssertEquals("Comments (1)", JSToken.Identifier,
token.GetToken());
AssertEquals("Comments (2)", "hello",
JSScannerTest.TestGetIdentifierName(scanner));
AssertEquals("Comments (3)", 2, token.StartLine);
AssertEquals("Comments (4)", 2, token.EndLine);
AssertEquals("Comments (5)", 23, token.StartPosition);
AssertEquals("Comments (6)", 28, token.EndPosition);
AssertEquals("Comments (7)", 0, token.StartColumn);
AssertEquals("Comments (8)", 5, token.EndColumn);
scanner.GetNextToken();
AssertEquals("Comments (9)", JSToken.Switch,
token.GetToken());
AssertNull("Comments (10)",
JSScannerTest.TestGetIdentifierName(scanner));
scanner.GetNextToken();
AssertEquals("Comments (11)", JSToken.Assert,
token.GetToken());
AssertNull("Comments (12)",
JSScannerTest.TestGetIdentifierName(scanner));
AssertEquals("Comments (13)", 4, token.StartLine);
AssertEquals("Comments (14)", 4, token.EndLine);
scanner.GetNextToken();
AssertEquals("Comments (15)", JSToken.DivideAssign,
token.GetToken());
AssertNull("Comments (16)",
JSScannerTest.TestGetIdentifierName(scanner));
scanner.GetNextToken();
AssertEquals("Comments (17)", JSToken.Divide,
token.GetToken());
AssertNull("Comments (18)",
JSScannerTest.TestGetIdentifierName(scanner));
try
{
scanner.GetNextToken();
Fail("Comments (19)");
}
catch(Exception e)
{
AssertEquals("Comments (20)", JSError.NoCommentEnd,
JSScannerTest.TestExtractError(e));
AssertEquals("Comments (21)", JSToken.UnterminatedComment,
token.GetToken());
}
}
// Test a single operator.
private void TestOp(JSScanner scanner, String ops,
ref int posn, JSToken expected)
{
Context token = JSScannerTest.TestGetTokenContext(scanner);
scanner.GetNextToken();
int next = ops.IndexOf(' ', posn);
String thisop = ops.Substring(posn, next - posn);
AssertEquals("TestOp[" + thisop + "] (1)",
expected, token.GetToken());
AssertEquals("TestOp[" + thisop + "] (2)",
thisop, token.GetCode());
AssertEquals("TestOp[" + thisop + "] (3)",
posn, token.StartPosition);
AssertEquals("TestOp[" + thisop + "] (4)",
next, token.EndPosition);
posn = next + 1;
}
// Test operator recognition.
public void TestScannerOperators()
{
JSScanner scanner;
String ops = "{ } ( ) [ ] . ; , < > <= >= == != " +
"=== !== + - * / % ++ -- << >> >>> " +
"& | ^ ! ~ && || ? : = += -= *= /= " +
"%= <<= >>= >>>= &= |= ^= :: ";
int posn = 0;
scanner = JSScannerTest.TestCreateScanner(ops);
TestOp(scanner, ops, ref posn, JSToken.LeftCurly);
TestOp(scanner, ops, ref posn, JSToken.RightCurly);
TestOp(scanner, ops, ref posn, JSToken.LeftParen);
TestOp(scanner, ops, ref posn, JSToken.RightParen);
TestOp(scanner, ops, ref posn, JSToken.LeftBracket);
TestOp(scanner, ops, ref posn, JSToken.RightBracket);
TestOp(scanner, ops, ref posn, JSToken.AccessField);
TestOp(scanner, ops, ref posn, JSToken.Semicolon);
TestOp(scanner, ops, ref posn, JSToken.Comma);
TestOp(scanner, ops, ref posn, JSToken.LessThan);
TestOp(scanner, ops, ref posn, JSToken.GreaterThan);
TestOp(scanner, ops, ref posn, JSToken.LessThanEqual);
TestOp(scanner, ops, ref posn, JSToken.GreaterThanEqual);
TestOp(scanner, ops, ref posn, JSToken.Equal);
TestOp(scanner, ops, ref posn, JSToken.NotEqual);
TestOp(scanner, ops, ref posn, JSToken.StrictEqual);
TestOp(scanner, ops, ref posn, JSToken.StrictNotEqual);
TestOp(scanner, ops, ref posn, JSToken.Plus);
TestOp(scanner, ops, ref posn, JSToken.Minus);
TestOp(scanner, ops, ref posn, JSToken.Multiply);
TestOp(scanner, ops, ref posn, JSToken.Divide);
TestOp(scanner, ops, ref posn, JSToken.Modulo);
TestOp(scanner, ops, ref posn, JSToken.Increment);
TestOp(scanner, ops, ref posn, JSToken.Decrement);
TestOp(scanner, ops, ref posn, JSToken.LeftShift);
TestOp(scanner, ops, ref posn, JSToken.RightShift);
TestOp(scanner, ops, ref posn, JSToken.UnsignedRightShift);
TestOp(scanner, ops, ref posn, JSToken.BitwiseAnd);
TestOp(scanner, ops, ref posn, JSToken.BitwiseOr);
TestOp(scanner, ops, ref posn, JSToken.BitwiseXor);
TestOp(scanner, ops, ref posn, JSToken.LogicalNot);
TestOp(scanner, ops, ref posn, JSToken.BitwiseNot);
TestOp(scanner, ops, ref posn, JSToken.LogicalAnd);
TestOp(scanner, ops, ref posn, JSToken.LogicalOr);
TestOp(scanner, ops, ref posn, JSToken.ConditionalIf);
TestOp(scanner, ops, ref posn, JSToken.Colon);
TestOp(scanner, ops, ref posn, JSToken.Assign);
TestOp(scanner, ops, ref posn, JSToken.PlusAssign);
TestOp(scanner, ops, ref posn, JSToken.MinusAssign);
TestOp(scanner, ops, ref posn, JSToken.MultiplyAssign);
TestOp(scanner, ops, ref posn, JSToken.DivideAssign);
TestOp(scanner, ops, ref posn, JSToken.ModuloAssign);
TestOp(scanner, ops, ref posn, JSToken.LeftShiftAssign);
TestOp(scanner, ops, ref posn, JSToken.RightShiftAssign);
TestOp(scanner, ops, ref posn,
JSToken.UnsignedRightShiftAssign);
TestOp(scanner, ops, ref posn, JSToken.BitwiseAndAssign);
TestOp(scanner, ops, ref posn, JSToken.BitwiseOrAssign);
TestOp(scanner, ops, ref posn, JSToken.BitwiseXorAssign);
TestOp(scanner, ops, ref posn, JSToken.DoubleColon);
}
// Parse a number.
private void TestNum(String value, JSToken expected)
{
JSScanner scanner;
Context token;
scanner = JSScannerTest.TestCreateScanner(value);
token = JSScannerTest.TestGetTokenContext(scanner);
scanner.GetNextToken();
AssertEquals("TestNum[" + value + "] (1)",
value, token.GetCode());
AssertEquals("TestNum[" + value + "] (2)",
expected, token.GetToken());
}
// Parse an invalid number.
private void TestInvalidNum(String value, JSError expected)
{
JSScanner scanner;
Context token;
scanner = JSScannerTest.TestCreateScanner(value);
token = JSScannerTest.TestGetTokenContext(scanner);
try
{
scanner.GetNextToken();
Fail("TestInvalidNum[" + value + "] (1)");
}
catch(Exception e)
{
AssertEquals("TestNum[" + value + "] (2)", expected,
JSScannerTest.TestExtractError(e));
}
}
// Test number recognition.
public void TestScannerNumbers()
{
TestNum("0", JSToken.IntegerLiteral);
TestNum("0x17a", JSToken.IntegerLiteral);
TestNum("0X17A", JSToken.IntegerLiteral);
TestNum("123", JSToken.IntegerLiteral);
TestNum("123.0", JSToken.NumericLiteral);
TestNum(".123", JSToken.NumericLiteral);
TestNum("1e123", JSToken.NumericLiteral);
TestNum("1E-123", JSToken.NumericLiteral);
TestNum("1.5E-123", JSToken.NumericLiteral);
TestNum(".5E+123", JSToken.NumericLiteral);
TestInvalidNum("0x", JSError.BadHexDigit);
TestInvalidNum("0xG", JSError.BadHexDigit);
}
}; // class TestScanner
| |
using System;
using System.Net.NetworkInformation;
using Couchbase.Lite.Util;
using System.Threading;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Net.Http;
using System.Text;
#if __ANDROID__
using Android.App;
using Android.Net;
using Android.Content;
using Android.Webkit;
using Uri = System.Uri;
#endif
#if NET_3_5
using WebRequest = System.Net.Couchbase.WebRequest;
using HttpWebRequest = System.Net.Couchbase.HttpWebRequest;
using HttpWebResponse = System.Net.Couchbase.HttpWebResponse;
using WebException = System.Net.Couchbase.WebException;
#endif
namespace Couchbase.Lite
{
// NOTE: The Android specific #ifdefs are in here solely
// to work around Xamarin.Android bug
// https://bugzilla.xamarin.com/show_bug.cgi?id=1969
// NOTE: The issue above was fixed as of Xamarin.Android 4.18, but seems
// to have regressed in 4.20
/// <summary>
/// This uses the NetworkAvailability API to listen for network reachability
/// change events and fires off changes internally.
/// </summary>
internal sealed class NetworkReachabilityManager : INetworkReachabilityManager
{
private int _startCount = 0;
private const string TAG = "NetworkReachabilityManager";
public bool CanReach(string remoteUri)
{
HttpWebRequest request;
var uri = new Uri (remoteUri);
var credentials = uri.UserInfo;
if (credentials != null) {
remoteUri = string.Format ("{0}://{1}{2}", uri.Scheme, uri.Authority, uri.PathAndQuery);
request = WebRequest.CreateHttp (remoteUri);
request.Headers.Add ("Authorization", "Basic " + Convert.ToBase64String (Encoding.UTF8.GetBytes (credentials)));
request.PreAuthenticate = true;
}
else {
request = WebRequest.CreateHttp (remoteUri);
}
request.AllowWriteStreamBuffering = true;
request.Timeout = 10000;
request.Method = "GET";
try {
using(var response = (HttpWebResponse)request.GetResponse()) {
return true; //We only care that the server responded
}
} catch(Exception e) {
var we = e as WebException;
if(we != null && we.Status == WebExceptionStatus.ProtocolError) {
return true; //Getting an HTTP error technically means we can connect
}
Log.I(TAG, "Didn't get successful connection to {0}", remoteUri);
Log.D(TAG, " Cause: ", e);
return false;
}
}
#if __ANDROID__
private class AndroidNetworkChangeReceiver : BroadcastReceiver
{
const string Tag = "AndroidNetworkChangeReceiver";
readonly private Action<NetworkReachabilityStatus> _callback;
object lockObject;
private volatile Boolean _ignoreNotifications;
private NetworkReachabilityStatus _lastStatus;
public AndroidNetworkChangeReceiver(Action<NetworkReachabilityStatus> callback)
{
_callback = callback;
_ignoreNotifications = true;
lockObject = new object();
}
public override void OnReceive(Context context, Intent intent)
{
Log.D(Tag + ".OnReceive", "Received intent: {0}", intent.ToString());
if (_ignoreNotifications) {
Log.D(Tag + ".OnReceive", "Ignoring received intent: {0}", intent.ToString());
_ignoreNotifications = false;
return;
}
Log.D(Tag + ".OnReceive", "Received intent: {0}", intent.ToString());
var manager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
var networkInfo = manager.ActiveNetworkInfo;
var status = networkInfo == null || !networkInfo.IsConnected
? NetworkReachabilityStatus.Unreachable
: NetworkReachabilityStatus.Reachable;
if (!status.Equals(_lastStatus))
{
_callback(status);
}
lock(lockObject)
{
_lastStatus = status;
}
}
public void EnableListening()
{
_ignoreNotifications = false;
}
public void DisableListening()
{
_ignoreNotifications = true;
}
}
private AndroidNetworkChangeReceiver _receiver;
#endif
#region INetworkReachabilityManager implementation
public event EventHandler<NetworkReachabilityChangeEventArgs> StatusChanged
{
add { _statusChanged = (EventHandler<NetworkReachabilityChangeEventArgs>)Delegate.Combine(_statusChanged, value); }
remove { _statusChanged = (EventHandler<NetworkReachabilityChangeEventArgs>)Delegate.Remove(_statusChanged, value); }
}
private EventHandler<NetworkReachabilityChangeEventArgs> _statusChanged;
/// <summary>This method starts listening for network connectivity state changes.</summary>
/// <remarks>This method starts listening for network connectivity state changes.</remarks>
public void StartListening()
{
Interlocked.Increment(ref _startCount);
#if __ANDROID__
if (_receiver != null) {
return; // We only need one handler.
}
var intent = new IntentFilter(ConnectivityManager.ConnectivityAction);
_receiver = new AndroidNetworkChangeReceiver(InvokeNetworkChangeEvent);
Application.Context.RegisterReceiver(_receiver, intent);
#else
if (_isListening) {
return;
}
NetworkChange.NetworkAvailabilityChanged += OnNetworkChange;
_isListening = true;
#endif
}
/// <summary>This method stops this class from listening for network changes.</summary>
/// <remarks>This method stops this class from listening for network changes.</remarks>
public void StopListening()
{
var count = Interlocked.Decrement(ref _startCount);
if (count > 0) {
return;
}
if (count < 0) {
Log.W(TAG, "Too many calls to INetworkReachabilityManager.StopListening()");
Interlocked.Exchange(ref _startCount, 0);
return;
}
#if __ANDROID__
if (_receiver == null) {
return;
}
_receiver.DisableListening();
Application.Context.UnregisterReceiver(_receiver);
_receiver = null;
#else
if (!_isListening) {
return;
}
NetworkChange.NetworkAvailabilityChanged -= OnNetworkChange;
#endif
}
#endregion
#region Private Members
#if !__ANDROID__
private volatile Boolean _isListening;
#endif
#endregion
/// <summary>Notify listeners that the network is now reachable/unreachable.</summary>
internal void OnNetworkChange(Object sender, NetworkAvailabilityEventArgs args)
{
var status = args.IsAvailable
? NetworkReachabilityStatus.Reachable
: NetworkReachabilityStatus.Unreachable;
InvokeNetworkChangeEvent(status);
}
void InvokeNetworkChangeEvent(NetworkReachabilityStatus status)
{
var evt = _statusChanged;
if (evt == null)
{
return;
}
var eventArgs = new NetworkReachabilityChangeEventArgs(status);
evt(this, eventArgs);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
////////////////////////////////////////////////////////////////////////////
//
// Class: TextInfo
//
// Purpose: This Class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
// Date: [....] 31, 1999
//
////////////////////////////////////////////////////////////////////////////
using System.Security;
namespace System.Globalization {
using System;
using System.Text;
using System.Threading;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public partial class TextInfo : ICloneable, IDeserializationCallback
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
[OptionalField(VersionAdded = 2)]
private String m_listSeparator;
[OptionalField(VersionAdded = 2)]
private bool m_isReadOnly = false;
//
// In Whidbey we had several names:
// m_win32LangID is the name of the culture, but only used for (de)serialization.
// customCultureName is the name of the creating custom culture (if custom) In combination with m_win32LangID
// this is authoratative, ie when deserializing.
// m_cultureTableRecord was the data record of the creating culture. (could have different name if custom)
// m_textInfoID is the LCID of the textinfo itself (no longer used)
// m_name is the culture name (from cultureinfo.name)
//
// In Silverlight/Arrowhead this is slightly different:
// m_cultureName is the name of the creating culture. Note that we consider this authoratative,
// if the culture's textinfo changes when deserializing, then behavior may change.
// (ala Whidbey behavior). This is the only string Arrowhead needs to serialize.
// m_cultureData is the data that backs this class.
// m_textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
// m_textInfoName can be the same as m_cultureName on Silverlight since the OS knows
// how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't
// know how to resolve custom locle names to sort ids so we have to have alredy resolved this.
//
[OptionalField(VersionAdded = 3)]
private String m_cultureName; // Name of the culture that created this text info
[NonSerialized]private CultureData m_cultureData; // Data record for the culture that made us, not for this textinfo
[NonSerialized]private String m_textInfoName; // Name of the text info we're using (ie: m_cultureData.STEXTINFO)
#if !MONO
[NonSerialized]private IntPtr m_dataHandle; // Sort handle
[NonSerialized]private IntPtr m_handleOrigin;
#endif
[NonSerialized]private bool? m_IsAsciiCasingSameAsInvariant;
// Invariant text info
internal static TextInfo Invariant
{
get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
return s_Invariant;
}
}
internal volatile static TextInfo s_Invariant;
////////////////////////////////////////////////////////////////////////
//
// TextInfo Constructors
//
// Implements CultureInfo.TextInfo.
//
////////////////////////////////////////////////////////////////////////
internal TextInfo(CultureData cultureData)
{
// This is our primary data source, we don't need most of the rest of this
this.m_cultureData = cultureData;
this.m_cultureName = this.m_cultureData.CultureName;
this.m_textInfoName = this.m_cultureData.STEXTINFO;
#if !FEATURE_CORECLR && !MONO
IntPtr handleOrigin;
this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
this.m_handleOrigin = handleOrigin;
#endif
}
////////////////////////////////////////////////////////////////////////
//
// Serialization / Deserialization
//
// Note that we have to respect the Whidbey behavior for serialization compatibility
//
////////////////////////////////////////////////////////////////////////
#region Serialization
// the following fields are defined to keep the compatibility with Whidbey.
// don't change/remove the names/types of these fields.
[OptionalField(VersionAdded = 2)]
private string customCultureName;
#if !FEATURE_CORECLR
// the following fields are defined to keep compatibility with Everett.
// don't change/remove the names/types of these fields.
[OptionalField(VersionAdded = 1)]
internal int m_nDataItem;
[OptionalField(VersionAdded = 1)]
internal bool m_useUserOverride;
[OptionalField(VersionAdded = 1)]
internal int m_win32LangID;
#endif // !FEATURE_CORECLR
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
// Clear these so we can check if we've fixed them yet
this.m_cultureData = null;
this.m_cultureName = null;
}
private void OnDeserialized()
{
// this method will be called twice because of the support of IDeserializationCallback
if (this.m_cultureData == null)
{
if (this.m_cultureName == null)
{
// This is whidbey data, get it from customCultureName/win32langid
if (this.customCultureName != null)
{
// They gave a custom cultuer name, so use that
this.m_cultureName = this.customCultureName;
}
#if FEATURE_USE_LCID
else
{
if (m_win32LangID == 0)
{
// m_cultureName and m_win32LangID are nulls which means we got uninitialized textinfo serialization stream.
// To be compatible with v2/3/3.5 we need to return ar-SA TextInfo in this case.
m_cultureName = "ar-SA";
}
else
{
// No custom culture, use the name from the LCID
m_cultureName = CultureInfo.GetCultureInfo(m_win32LangID).m_cultureData.CultureName;
}
}
#endif
}
// Get the text info name belonging to that culture
this.m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData;
this.m_textInfoName = this.m_cultureData.STEXTINFO;
#if !FEATURE_CORECLR && !MONO
IntPtr handleOrigin;
this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
this.m_handleOrigin = handleOrigin;
#endif
}
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
#if !FEATURE_CORECLR
// Initialize the fields Whidbey expects:
// Whidbey expected this, so set it, but the value doesn't matter much
this.m_useUserOverride = false;
#endif // FEATURE_CORECLR
// Relabel our name since Whidbey expects it to be called customCultureName
this.customCultureName = this.m_cultureName;
#if FEATURE_USE_LCID
// Ignore the m_win32LangId because whidbey'll just get it by name if we make it the LOCALE_CUSTOM_UNSPECIFIED.
this.m_win32LangID = (CultureInfo.GetCultureInfo(m_cultureName)).LCID;
#endif
}
#endregion Serialization
//
// Internal ordinal comparison functions
//
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal static int GetHashCodeOrdinalIgnoreCase(String s)
{
return GetHashCodeOrdinalIgnoreCase(s, false, 0);
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal static int GetHashCodeOrdinalIgnoreCase(String s, bool forceRandomizedHashing, long additionalEntropy)
{
// This is the same as an case insensitive hash for Invariant
// (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules)
return (Invariant.GetCaseInsensitiveHashCode(s, forceRandomizedHashing, additionalEntropy));
}
#if !MONO
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal static unsafe bool TryFastFindStringOrdinalIgnoreCase(int searchFlags, String source, int startIndex, String value, int count, ref int foundIndex)
{
return InternalTryFindStringOrdinalIgnoreCase(searchFlags, source, count, startIndex, value, value.Length, ref foundIndex);
}
#endif
// This function doesn't check arguments. Please do check in the caller.
// The underlying unmanaged code will assert the sanity of arguments.
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal static unsafe int CompareOrdinalIgnoreCase(String str1, String str2)
{
#if __APPLE__
// ToUpper (invariant) here before going to the PAL since Mac OS 10.4 does this step
// wrong (CFCompareString uses the current OS locale and does not let you specify a specific locale)
return String.CompareOrdinal(str1.ToUpper(CultureInfo.InvariantCulture), str2.ToUpper(CultureInfo.InvariantCulture));
#else
// Compare the whole string and ignore case.
return InternalCompareStringOrdinalIgnoreCase(str1, 0, str2, 0, str1.Length, str2.Length);
#endif
}
// This function doesn't check arguments. Please do check in the caller.
// The underlying unmanaged code will assert the sanity of arguments.
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB )
{
Contract.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
Contract.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB");
#if __APPLE__
// ToUpper (invariant) here before going to the PAL since Mac OS 10.4 does this step
// wrong (CFCompareString uses the current OS locale and does not let you specify a specific locale)
return String.CompareOrdinal(strA.ToUpper(CultureInfo.InvariantCulture), indexA, strB.ToUpper(CultureInfo.InvariantCulture), indexB, Math.Max(lengthA, lengthB));
#else
return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB);
#endif
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
Contract.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
Contract.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
Contract.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");
// We return 0 if both inputs are empty strings
if (source.Length == 0 && value.Length == 0)
{
return 0;
}
#if __APPLE__
string sourceUpper = source.ToUpper(CultureInfo.InvariantCulture);
string valueUpper = value.ToUpper(CultureInfo.InvariantCulture);
#else
// fast path
#if !MONO
int ret = -1;
if (TryFastFindStringOrdinalIgnoreCase(Microsoft.Win32.Win32Native.FIND_FROMSTART, source, startIndex, value, count, ref ret))
return ret;
#endif
// the search space within [source] starts at offset [startIndex] inclusive and includes
// [count] characters (thus the last included character is at index [startIndex + count -1]
// [end] is the index of the next character after the search space
// (it points past the end of the search space)
int end = startIndex + count;
// maxStartIndex is the index beyond which we never *start* searching, inclusive; in other words;
// a search could include characters beyond maxStartIndex, but we'd never begin a search at an
// index strictly greater than maxStartIndex.
int maxStartIndex = end - value.Length;
for (; startIndex <= maxStartIndex; startIndex++)
{
#if __APPLE__
if (String.CompareOrdinal(sourceUpper, startIndex, valueUpper, 0, value.Length)==0)
#else
// We should always have the same or more characters left to search than our actual pattern
Contract.Assert(end - startIndex >= value.Length);
// since this is an ordinal comparison, we can assume that the lengths must match
if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
#endif
{
return startIndex;
}
}
// Not found
return -1;
}
#if FEATURE_CORECLR
private static bool LegacyMode
{
get
{
return CompatibilitySwitches.IsAppEarlierThanSilverlight4;
}
}
#endif // FEATURE_CORECLR
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
Contract.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
Contract.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
Contract.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
Contract.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");
// If value is Empty, the return value is startIndex
// <STRIP>we accidently shipped Silverlight 2 and 3 without this if-check</STRIP>
if (value.Length == 0
#if FEATURE_CORECLR
&& !LegacyMode
#endif // FEATURE_CORECLR
)
{
return startIndex;
}
#if __APPLE__
string sourceUpper = source.ToUpper(CultureInfo.InvariantCulture);
string valueUpper = value.ToUpper(CultureInfo.InvariantCulture);
#else
// fast path
#if !MONO
int ret = -1;
if (TryFastFindStringOrdinalIgnoreCase(Microsoft.Win32.Win32Native.FIND_FROMEND, source, startIndex, value, count, ref ret))
return ret;
#endif
// the search space within [source] ends at offset [startIndex] inclusive
// and includes [count] characters
// minIndex is the first included character and is at index [startIndex - count + 1]
int minIndex = startIndex - count + 1;
// First place we can find it is start index - (value.length -1)
if (value.Length > 0)
{
startIndex -= (value.Length - 1);
}
for (; startIndex >= minIndex; startIndex--)
{
#if __APPLE__
if (String.CompareOrdinal(sourceUpper, startIndex, valueUpper, 0, value.Length)==0)
#else
if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
#endif
{
return startIndex;
}
}
// Not found
return -1;
}
////////////////////////////////////////////////////////////////////////
//
// CodePage
//
// Returns the number of the code page used by this writing system.
// The type parameter can be any of the following values:
// ANSICodePage
// OEMCodePage
// MACCodePage
//
////////////////////////////////////////////////////////////////////////
#if !FEATURE_CORECLR
public virtual int ANSICodePage {
get {
return (this.m_cultureData.IDEFAULTANSICODEPAGE);
}
}
public virtual int OEMCodePage {
get {
return (this.m_cultureData.IDEFAULTOEMCODEPAGE);
}
}
public virtual int MacCodePage {
get {
return (this.m_cultureData.IDEFAULTMACCODEPAGE);
}
}
public virtual int EBCDICCodePage {
get {
return (this.m_cultureData.IDEFAULTEBCDICCODEPAGE);
}
}
#endif
////////////////////////////////////////////////////////////////////////
//
// LCID
//
// We need a way to get an LCID from outside of the BCL. This prop is the way.
// NOTE: neutral cultures will cause GPS incorrect LCIDS from this
//
////////////////////////////////////////////////////////////////////////
#if FEATURE_USE_LCID
[System.Runtime.InteropServices.ComVisible(false)]
public int LCID
{
get
{
// Just use the LCID from our text info name
return CultureInfo.GetCultureInfo(this.m_textInfoName).LCID;
}
}
#endif
////////////////////////////////////////////////////////////////////////
//
// CultureName
//
// The name of the culture associated with the current TextInfo.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public string CultureName
{
get
{
return(this.m_textInfoName);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get { return (m_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of IColnable.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public virtual Object Clone()
{
object o = MemberwiseClone();
((TextInfo) o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public static TextInfo ReadOnly(TextInfo textInfo)
{
if (textInfo == null) { throw new ArgumentNullException("textInfo"); }
Contract.EndContractBlock();
if (textInfo.IsReadOnly) { return (textInfo); }
TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
clonedTextInfo.SetReadOnlyState(true);
return (clonedTextInfo);
}
private void VerifyWritable()
{
if (m_isReadOnly)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
Contract.EndContractBlock();
}
internal void SetReadOnlyState(bool readOnly)
{
m_isReadOnly = readOnly;
}
////////////////////////////////////////////////////////////////////////
//
// ListSeparator
//
// Returns the string used to separate items in a list.
//
////////////////////////////////////////////////////////////////////////
public virtual String ListSeparator
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_listSeparator == null) {
m_listSeparator = this.m_cultureData.SLIST;
}
return (m_listSeparator);
}
[System.Runtime.InteropServices.ComVisible(false)]
set
{
if (value == null)
{
throw new ArgumentNullException("value", Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
m_listSeparator = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// ToLower
//
// Converts the character or string to lower case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
[System.Security.SecuritySafeCritical] // auto-generated
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public unsafe virtual char ToLower(char c)
{
if(IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToLowerAsciiInvariant(c);
}
#if MONO
return ToLowerInternal (c);
#else
return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, false));
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual String ToLower(String str)
{
if (str == null) { throw new ArgumentNullException("str"); }
Contract.EndContractBlock();
#if MONO
return ToLowerInternal (str);
#else
return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, false);
#endif
}
static private Char ToLowerAsciiInvariant(Char c)
{
if ('A' <= c && c <= 'Z')
{
c = (Char)(c | 0x20);
}
return c;
}
////////////////////////////////////////////////////////////////////////
//
// ToUpper
//
// Converts the character or string to upper case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
[System.Security.SecuritySafeCritical] // auto-generated
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public unsafe virtual char ToUpper(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToUpperAsciiInvariant(c);
}
#if MONO
return ToUpperInternal (c);
#else
return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, true));
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual String ToUpper(String str)
{
if (str == null) { throw new ArgumentNullException("str"); }
Contract.EndContractBlock();
#if MONO
return ToUpperInternal (str);
#else
return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, true);
#endif
}
static private Char ToUpperAsciiInvariant(Char c)
{
if ('a' <= c && c <= 'z')
{
c = (Char)(c & ~0x20);
}
return c;
}
static private bool IsAscii(Char c)
{
return c < 0x80;
}
private bool IsAsciiCasingSameAsInvariant
{
get
{
if (m_IsAsciiCasingSameAsInvariant == null)
{
#if MONO
m_IsAsciiCasingSameAsInvariant = !(m_cultureData.SISO639LANGNAME == "az" || m_cultureData.SISO639LANGNAME == "tr");
#else
m_IsAsciiCasingSameAsInvariant =
CultureInfo.GetCultureInfo(m_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CompareOptions.IgnoreCase) == 0;
#endif
}
return (bool)m_IsAsciiCasingSameAsInvariant;
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
if (that != null)
{
return this.CultureName.Equals(that.CultureName);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.CultureName.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// TextInfo.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("TextInfo - " + this.m_cultureData.CultureName);
}
//
// Titlecasing:
// -----------
// Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter
// and the rest of the letters are lowercase. The choice of which words to titlecase in headings
// and titles is dependent on language and local conventions. For example, "The Merry Wives of Windor"
// is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased.
// In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von"
// are not titlecased. In French even fewer words are titlecased: "Les joyeuses commeres de Windsor."
//
// Moreover, the determination of what actually constitutes a word is language dependent, and this can
// influence which letter or letters of a "word" are uppercased when titlecasing strings. For example
// "l'arbre" is considered two words in French, whereas "can't" is considered one word in English.
//
//
// Differences between UNICODE 5.0 and the .NET Framework (
#if !FEATURE_CORECLR
public unsafe String ToTitleCase(String str) {
if (str==null) {
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
if (str.Length == 0) {
return (str);
}
StringBuilder result = new StringBuilder();
String lowercaseData = null;
for (int i = 0; i < str.Length; i++) {
UnicodeCategory charType;
int charLen;
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (Char.CheckLetter(charType)) {
// Do the titlecasing for the first character of the word.
i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
//
// Convert the characters until the end of the this word
// to lowercase.
//
int lowercaseStart = i;
//
// Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc)
// This is in line with Word 2000 behavior of titlecasing.
//
bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter);
// Use a loop to find all of the other letters following this letter.
while (i < str.Length) {
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (IsLetterCategory(charType)) {
if (charType == UnicodeCategory.LowercaseLetter) {
hasLowerCase = true;
}
i += charLen;
} else if (str[i] == '\'') {
//
i++;
if (hasLowerCase) {
if (lowercaseData==null) {
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
} else {
result.Append(str, lowercaseStart, i - lowercaseStart);
}
lowercaseStart = i;
hasLowerCase = true;
} else if (!IsWordSeparator(charType)) {
// This category is considered to be part of the word.
// This is any category that is marked as false in wordSeprator array.
i+= charLen;
} else {
// A word separator. Break out of the loop.
break;
}
}
int count = i - lowercaseStart;
if (count>0) {
if (hasLowerCase) {
if (lowercaseData==null) {
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, count);
} else {
result.Append(str, lowercaseStart, count);
}
}
if (i < str.Length) {
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
else {
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
return (result.ToString());
}
private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) {
Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2) {
// Surrogate pair
result.Append(input[inputIndex++]);
result.Append(input[inputIndex]);
}
else {
result.Append(input[inputIndex]);
}
return inputIndex;
}
private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) {
Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2) {
// Surrogate pair
result.Append( this.ToUpper(input.Substring(inputIndex, charLen)) );
inputIndex++;
}
else {
switch (input[inputIndex]) {
//
// For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below.
//
case (char)0x01C4: // DZ with Caron -> Dz with Caron
case (char)0x01C5: // Dz with Caron -> Dz with Caron
case (char)0x01C6: // dz with Caron -> Dz with Caron
result.Append( (char)0x01C5 );
break;
case (char)0x01C7: // LJ -> Lj
case (char)0x01C8: // Lj -> Lj
case (char)0x01C9: // lj -> Lj
result.Append( (char)0x01C8 );
break;
case (char)0x01CA: // NJ -> Nj
case (char)0x01CB: // Nj -> Nj
case (char)0x01CC: // nj -> Nj
result.Append( (char)0x01CB );
break;
case (char)0x01F1: // DZ -> Dz
case (char)0x01F2: // Dz -> Dz
case (char)0x01F3: // dz -> Dz
result.Append( (char)0x01F2 );
break;
default:
result.Append( this.ToUpper(input[inputIndex]) );
break;
}
}
return inputIndex;
}
//
// Used in ToTitleCase():
// When we find a starting letter, the following array decides if a category should be
// considered as word seprator or not.
//
private const int wordSeparatorMask =
/* false */ (0 << 0) | // UppercaseLetter = 0,
/* false */ (0 << 1) | // LowercaseLetter = 1,
/* false */ (0 << 2) | // TitlecaseLetter = 2,
/* false */ (0 << 3) | // ModifierLetter = 3,
/* false */ (0 << 4) | // OtherLetter = 4,
/* false */ (0 << 5) | // NonSpacingMark = 5,
/* false */ (0 << 6) | // SpacingCombiningMark = 6,
/* false */ (0 << 7) | // EnclosingMark = 7,
/* false */ (0 << 8) | // DecimalDigitNumber = 8,
/* false */ (0 << 9) | // LetterNumber = 9,
/* false */ (0 << 10) | // OtherNumber = 10,
/* true */ (1 << 11) | // SpaceSeparator = 11,
/* true */ (1 << 12) | // LineSeparator = 12,
/* true */ (1 << 13) | // ParagraphSeparator = 13,
/* true */ (1 << 14) | // Control = 14,
/* true */ (1 << 15) | // Format = 15,
/* false */ (0 << 16) | // Surrogate = 16,
/* false */ (0 << 17) | // PrivateUse = 17,
/* true */ (1 << 18) | // ConnectorPunctuation = 18,
/* true */ (1 << 19) | // DashPunctuation = 19,
/* true */ (1 << 20) | // OpenPunctuation = 20,
/* true */ (1 << 21) | // ClosePunctuation = 21,
/* true */ (1 << 22) | // InitialQuotePunctuation = 22,
/* true */ (1 << 23) | // FinalQuotePunctuation = 23,
/* true */ (1 << 24) | // OtherPunctuation = 24,
/* true */ (1 << 25) | // MathSymbol = 25,
/* true */ (1 << 26) | // CurrencySymbol = 26,
/* true */ (1 << 27) | // ModifierSymbol = 27,
/* true */ (1 << 28) | // OtherSymbol = 28,
/* false */ (0 << 29); // OtherNotAssigned = 29;
private static bool IsWordSeparator(UnicodeCategory category) {
return (wordSeparatorMask & (1 << (int)category)) != 0;
}
private static bool IsLetterCategory(UnicodeCategory uc) {
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
|| uc == UnicodeCategory.TitlecaseLetter
|| uc == UnicodeCategory.ModifierLetter
|| uc == UnicodeCategory.OtherLetter);
}
#endif
#if !FEATURE_CORECLR
// IsRightToLeft
//
// Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
//
[System.Runtime.InteropServices.ComVisible(false)]
public bool IsRightToLeft
{
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
get
{
return this.m_cultureData.IsRightToLeft;
}
}
#endif
#if FEATURE_SERIALIZATION
/// <internalonly/>
void IDeserializationCallback.OnDeserialization(Object sender)
{
OnDeserialized();
}
#endif
//
// Get case-insensitive hash code for the specified string.
//
// NOTENOTE: this is an internal function. The caller should verify the string
// is not null before calling this. Currenlty, CaseInsensitiveHashCodeProvider
// does that.
//
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe int GetCaseInsensitiveHashCode(String str)
{
return GetCaseInsensitiveHashCode(str, false, 0);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe int GetCaseInsensitiveHashCode(String str, bool forceRandomizedHashing, long additionalEntropy)
{
// Validate inputs
if (str==null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
#if MONO
return this == s_Invariant ? GetInvariantCaseInsensitiveHashCode (str) : StringComparer.CurrentCultureIgnoreCase.GetHashCode (str);
#else
// Return our result
return (InternalGetCaseInsHash(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, forceRandomizedHashing, additionalEntropy));
#endif
}
#if MONO
unsafe int GetInvariantCaseInsensitiveHashCode (string str)
{
fixed (char * c = str) {
char * cc = c;
char * end = cc + str.Length - 1;
int h = 0;
for (;cc < end; cc += 2) {
h = (h << 5) - h + Char.ToUpperInvariant (*cc);
h = (h << 5) - h + Char.ToUpperInvariant (cc [1]);
}
++end;
if (cc < end)
h = (h << 5) - h + Char.ToUpperInvariant (*cc);
return h;
}
}
#else
// Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseChar
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern char InternalChangeCaseChar(IntPtr handle, IntPtr handleOrigin, String localeName, char ch, bool isToUpper);
// Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseString
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern String InternalChangeCaseString(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool isToUpper);
// Get case insensitive hash -- ComNlsInfo::InternalGetCaseInsHash
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern int InternalGetCaseInsHash(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool forceRandomizedHashing, long additionalEntropy);
// Call ::CompareStringOrdinal -- ComNlsInfo::InternalCompareStringOrdinalIgnoreCase
// Start at indexes and compare for length characters (or remainder of string if length == -1)
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern int InternalCompareStringOrdinalIgnoreCase(String string1, int index1, String string2, int index2, int length1, int length2);
// ComNlsInfo::InternalTryFindStringOrdinalIgnoreCase attempts a faster IndexOf/LastIndexOf OrdinalIgnoreCase using a kernel function.
// Returns true if FindStringOrdinal was handled, with foundIndex set to the target's index into the source
// Returns false when FindStringOrdinal wasn't handled
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static unsafe extern bool InternalTryFindStringOrdinalIgnoreCase(int searchFlags, String source, int sourceCount, int startIndex, String target, int targetCount, ref int foundIndex);
#endif
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Collections;
using Thrift.Processor;
using Thrift.Protocol;
using Thrift.Server;
using Thrift.Transport;
using Thrift.Transport.Server;
#pragma warning disable IDE0063 // using can be simplified, we don't
#pragma warning disable IDE0057 // substr can be simplified, we don't
namespace ThriftTest
{
internal enum ProtocolChoice
{
Binary,
Compact,
Json
}
internal enum TransportChoice
{
Socket,
TlsSocket,
NamedPipe
}
internal enum BufferChoice
{
None,
Buffered,
Framed
}
internal enum ServerChoice
{
Simple,
ThreadPool
}
internal class ServerParam
{
internal BufferChoice buffering = BufferChoice.None;
internal ProtocolChoice protocol = ProtocolChoice.Binary;
internal TransportChoice transport = TransportChoice.Socket;
internal ServerChoice server = ServerChoice.Simple;
internal int port = 9090;
internal string pipe = null;
internal void Parse(List<string> args)
{
for (var i = 0; i < args.Count; i++)
{
if (args[i].StartsWith("--pipe="))
{
pipe = args[i].Substring(args[i].IndexOf("=") + 1);
transport = TransportChoice.NamedPipe;
}
else if (args[i].StartsWith("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
if(transport != TransportChoice.TlsSocket)
transport = TransportChoice.Socket;
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
buffering = BufferChoice.Buffered;
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
buffering = BufferChoice.Framed;
}
else if (args[i] == "--binary" || args[i] == "--protocol=binary")
{
protocol = ProtocolChoice.Binary;
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
protocol = ProtocolChoice.Compact;
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
protocol = ProtocolChoice.Json;
}
else if (args[i] == "--server-type=simple")
{
server = ServerChoice.Simple;
}
else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
{
server = ServerChoice.ThreadPool;
}
else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
{
throw new NotImplementedException(args[i]);
}
else if (args[i] == "--ssl")
{
transport = TransportChoice.TlsSocket;
}
else if (args[i] == "--help")
{
PrintOptionsHelp();
return;
}
else
{
Console.WriteLine("Invalid argument: {0}", args[i]);
PrintOptionsHelp();
return;
}
}
}
internal static void PrintOptionsHelp()
{
Console.WriteLine("Server options:");
Console.WriteLine(" --pipe=<pipe name>");
Console.WriteLine(" --port=<port number>");
Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)");
Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)");
Console.WriteLine(" --server-type=<type> one of threaded,threadpool (defaults to simple)");
Console.WriteLine(" --processor=<prototype>");
Console.WriteLine(" --ssl");
Console.WriteLine();
}
}
public class TestServer
{
#pragma warning disable CA2211
public static int _clientID = -1; // use with Interlocked only!
#pragma warning restore CA2211
private static readonly TConfiguration Configuration = null; // or new TConfiguration() if needed
public delegate void TestLogDelegate(string msg, params object[] values);
public class MyServerEventHandler : TServerEventHandler
{
public int callCount = 0;
public Task PreServeAsync(CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
public Task<object> CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken)
{
callCount++;
return Task.FromResult<object>(null);
}
public Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
public Task ProcessContextAsync(object serverContext, TTransport transport, CancellationToken cancellationToken)
{
callCount++;
return Task.CompletedTask;
}
}
public class TestHandlerAsync : ThriftTest.IAsync
{
public TServer Server { get; set; }
private readonly int handlerID;
private readonly StringBuilder sb = new();
private readonly TestLogDelegate logger;
public TestHandlerAsync()
{
handlerID = Interlocked.Increment(ref _clientID);
logger += TestConsoleLogger;
logger.Invoke("New TestHandler instance created");
}
public void TestConsoleLogger(string msg, params object[] values)
{
sb.Clear();
sb.AppendFormat("handler{0:D3}:", handlerID);
sb.AppendFormat(msg, values);
sb.AppendLine();
Console.Write(sb.ToString());
}
public Task testVoid(CancellationToken cancellationToken)
{
logger.Invoke("testVoid()");
return Task.CompletedTask;
}
public Task<string> testString(string thing, CancellationToken cancellationToken)
{
logger.Invoke("testString({0})", thing);
return Task.FromResult(thing);
}
public Task<bool> testBool(bool thing, CancellationToken cancellationToken)
{
logger.Invoke("testBool({0})", thing);
return Task.FromResult(thing);
}
public Task<sbyte> testByte(sbyte thing, CancellationToken cancellationToken)
{
logger.Invoke("testByte({0})", thing);
return Task.FromResult(thing);
}
public Task<int> testI32(int thing, CancellationToken cancellationToken)
{
logger.Invoke("testI32({0})", thing);
return Task.FromResult(thing);
}
public Task<long> testI64(long thing, CancellationToken cancellationToken)
{
logger.Invoke("testI64({0})", thing);
return Task.FromResult(thing);
}
public Task<double> testDouble(double thing, CancellationToken cancellationToken)
{
logger.Invoke("testDouble({0})", thing);
return Task.FromResult(thing);
}
public Task<byte[]> testBinary(byte[] thing, CancellationToken cancellationToken)
{
logger.Invoke("testBinary({0} bytes)", thing.Length);
return Task.FromResult(thing);
}
public Task<Xtruct> testStruct(Xtruct thing, CancellationToken cancellationToken)
{
logger.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.String_thing, thing.Byte_thing, thing.I32_thing, thing.I64_thing);
return Task.FromResult(thing);
}
public Task<Xtruct2> testNest(Xtruct2 nest, CancellationToken cancellationToken)
{
var thing = nest.Struct_thing;
logger.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})",
nest.Byte_thing,
thing.String_thing,
thing.Byte_thing,
thing.I32_thing,
thing.I64_thing,
nest.I32_thing);
return Task.FromResult(nest);
}
public Task<Dictionary<int, int>> testMap(Dictionary<int, int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testMap({{");
var first = true;
foreach (var key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0} => {1}", key, thing[key]);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<Dictionary<string, string>> testStringMap(Dictionary<string, string> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testStringMap({{");
var first = true;
foreach (var key in thing.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0} => {1}", key, thing[key]);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<THashSet<int>> testSet(THashSet<int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testSet({{");
var first = true;
foreach (int elem in thing)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0}", elem);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<List<int>> testList(List<int> thing, CancellationToken cancellationToken)
{
sb.Clear();
sb.Append("testList({{");
var first = true;
foreach (var elem in thing)
{
if (first)
{
first = false;
}
else
{
sb.Append(", ");
}
sb.AppendFormat("{0}", elem);
}
sb.Append("}})");
logger.Invoke(sb.ToString());
return Task.FromResult(thing);
}
public Task<Numberz> testEnum(Numberz thing, CancellationToken cancellationToken)
{
logger.Invoke("testEnum({0})", thing);
return Task.FromResult(thing);
}
public Task<long> testTypedef(long thing, CancellationToken cancellationToken)
{
logger.Invoke("testTypedef({0})", thing);
return Task.FromResult(thing);
}
public Task<Dictionary<int, Dictionary<int, int>>> testMapMap(int hello, CancellationToken cancellationToken)
{
logger.Invoke("testMapMap({0})", hello);
var mapmap = new Dictionary<int, Dictionary<int, int>>();
var pos = new Dictionary<int, int>();
var neg = new Dictionary<int, int>();
for (var i = 1; i < 5; i++)
{
pos[i] = i;
neg[-i] = -i;
}
mapmap[4] = pos;
mapmap[-4] = neg;
return Task.FromResult(mapmap);
}
public Task<Dictionary<long, Dictionary<Numberz, Insanity>>> testInsanity(Insanity argument, CancellationToken cancellationToken)
{
logger.Invoke("testInsanity()");
/** from ThriftTest.thrift:
* So you think you've got this all worked, out eh?
*
* Creates a the returned map with these values and prints it out:
* { 1 => { 2 => argument,
* 3 => argument,
* },
* 2 => { 6 => <empty Insanity struct>, },
* }
* @return map<UserId, map<Numberz,Insanity>> - a map with the above values
*/
var first_map = new Dictionary<Numberz, Insanity>();
var second_map = new Dictionary<Numberz, Insanity>(); ;
first_map[Numberz.TWO] = argument;
first_map[Numberz.THREE] = argument;
second_map[Numberz.SIX] = new Insanity();
var insane = new Dictionary<long, Dictionary<Numberz, Insanity>>
{
[1] = first_map,
[2] = second_map
};
return Task.FromResult(insane);
}
public Task<Xtruct> testMulti(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5,
CancellationToken cancellationToken)
{
logger.Invoke("testMulti()");
var hello = new Xtruct(); ;
hello.String_thing = "Hello2";
hello.Byte_thing = arg0;
hello.I32_thing = arg1;
hello.I64_thing = arg2;
return Task.FromResult(hello);
}
public Task testException(string arg, CancellationToken cancellationToken)
{
logger.Invoke("testException({0})", arg);
if (arg == "Xception")
{
var x = new Xception
{
ErrorCode = 1001,
Message = arg
};
throw x;
}
if (arg == "TException")
{
throw new TException();
}
return Task.CompletedTask;
}
public Task<Xtruct> testMultiException(string arg0, string arg1, CancellationToken cancellationToken)
{
logger.Invoke("testMultiException({0}, {1})", arg0, arg1);
if (arg0 == "Xception")
{
var x = new Xception
{
ErrorCode = 1001,
Message = "This is an Xception"
};
throw x;
}
if (arg0 == "Xception2")
{
var x = new Xception2
{
ErrorCode = 2002,
Struct_thing = new Xtruct { String_thing = "This is an Xception2" }
};
throw x;
}
var result = new Xtruct { String_thing = arg1 };
return Task.FromResult(result);
}
public async Task testOneway(int secondsToSleep, CancellationToken cancellationToken)
{
logger.Invoke("testOneway({0}), sleeping...", secondsToSleep);
await Task.Delay(secondsToSleep * 1000, cancellationToken);
logger.Invoke("testOneway finished");
}
}
private static X509Certificate2 GetServerCert()
{
var serverCertName = "server.p12";
var possiblePaths = new List<string>
{
"../../../keys/",
"../../keys/",
"../keys/",
"keys/",
};
string existingPath = null;
foreach (var possiblePath in possiblePaths)
{
var path = Path.GetFullPath(possiblePath + serverCertName);
if (File.Exists(path))
{
existingPath = path;
break;
}
}
if (string.IsNullOrEmpty(existingPath))
{
throw new FileNotFoundException($"Cannot find file: {serverCertName}");
}
var cert = new X509Certificate2(existingPath, "thrift");
return cert;
}
public static async Task<int> Execute(List<string> args)
{
using (var loggerFactory = new LoggerFactory()) //.AddConsole().AddDebug();
{
var logger = loggerFactory.CreateLogger("Test");
try
{
var param = new ServerParam();
try
{
param.Parse(args);
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Error while parsing arguments");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
return 1;
}
// Endpoint transport (mandatory)
TServerTransport trans;
switch (param.transport)
{
case TransportChoice.NamedPipe:
Debug.Assert(param.pipe != null);
trans = new TNamedPipeServerTransport(param.pipe, Configuration, NamedPipeClientFlags.OnlyLocalClients);
break;
case TransportChoice.TlsSocket:
var cert = GetServerCert();
if (cert == null || !cert.HasPrivateKey)
{
cert?.Dispose();
throw new InvalidOperationException("Certificate doesn't contain private key");
}
trans = new TTlsServerSocketTransport(param.port, Configuration,
cert,
(sender, certificate, chain, errors) => true,
null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
break;
case TransportChoice.Socket:
default:
trans = new TServerSocketTransport(param.port, Configuration);
break;
}
// Layered transport (mandatory)
TTransportFactory transFactory = null;
switch (param.buffering)
{
case BufferChoice.Framed:
transFactory = new TFramedTransport.Factory();
break;
case BufferChoice.Buffered:
transFactory = new TBufferedTransport.Factory();
break;
default:
Debug.Assert(param.buffering == BufferChoice.None, "unhandled case");
transFactory = null; // no layered transprt
break;
}
TProtocolFactory proto = param.protocol switch
{
ProtocolChoice.Compact => new TCompactProtocol.Factory(),
ProtocolChoice.Json => new TJsonProtocol.Factory(),
ProtocolChoice.Binary => new TBinaryProtocol.Factory(),
_ => new TBinaryProtocol.Factory(),
};
// Processor
var testHandler = new TestHandlerAsync();
var testProcessor = new ThriftTest.AsyncProcessor(testHandler);
var processorFactory = new TSingletonProcessorFactory(testProcessor);
var poolconfig = new TThreadPoolAsyncServer.Configuration(); // use platform defaults
TServer serverEngine = param.server switch
{
ServerChoice.Simple => new TSimpleAsyncServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger),
ServerChoice.ThreadPool => new TThreadPoolAsyncServer(processorFactory, trans, transFactory, transFactory, proto, proto, poolconfig, logger),
_ => new TSimpleAsyncServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger)
};
//Server event handler
var serverEvents = new MyServerEventHandler();
serverEngine.SetEventHandler(serverEvents);
// Run it
var where = (!string.IsNullOrEmpty(param.pipe)) ? "pipe " + param.pipe : "port " + param.port;
Console.WriteLine("Running "+ serverEngine.GetType().Name +
" at "+ where +
" using "+ processorFactory.GetType().Name + " processor prototype factory " +
(param.buffering == BufferChoice.Buffered ? " with buffered transport" : "") +
(param.buffering == BufferChoice.Framed ? " with framed transport" : "") +
(param.transport == TransportChoice.TlsSocket ? " with encryption" : "") +
(param.protocol == ProtocolChoice.Compact ? " with compact protocol" : "") +
(param.protocol == ProtocolChoice.Json ? " with json protocol" : "") +
"...");
await serverEngine.ServeAsync(CancellationToken.None);
Console.ReadLine();
}
catch (Exception x)
{
Console.Error.Write(x);
return 1;
}
Console.WriteLine("done.");
return 0;
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using static Monacs.Core.Result;
namespace Monacs.Core
{
///<summary>
/// Contains the set of async extensions to work with the <see cref="Result{T}" /> type.
///</summary>
public static class AsyncResult
{
/* BindAsync */
/// <summary>
/// Transforms the <paramref name="result"/> into another <see cref="Result{T}"/> using the <paramref name="binder"/> function.
/// If the input result is Ok, returns the value of the binder call (which is <see cref="Result{T}"/> of <typeparamref name="TOut"/>).
/// Otherwise returns Error case of the Result of <typeparamref name="TOut"/>.
/// </summary>
/// <typeparam name="TIn">Type of the value in the input result.</typeparam>
/// <typeparam name="TOut">Type of the value in the returned result.</typeparam>
/// <param name="result">The result to bind with.</param>
/// <param name="binder">Function called with the input result value if it's Ok case.</param>
public static async Task<Result<TOut>> BindAsync<TIn, TOut>(this Result<TIn> result, Func<TIn, Task<Result<TOut>>> binder) =>
result.IsOk ? await binder(result.Value) : Error<TOut>(result.Error);
/// <summary>
/// Transforms the <paramref name="result"/> into another <see cref="Result{T}"/> using the <paramref name="binder"/> function.
/// If the input result is Ok, returns the value of the binder call (which is <see cref="Result{T}"/> of <typeparamref name="TOut"/>).
/// Otherwise returns Error case of the Result of <typeparamref name="TOut"/>.
/// </summary>
/// <typeparam name="TIn">Type of the value in the input result.</typeparam>
/// <typeparam name="TOut">Type of the value in the returned result.</typeparam>
/// <param name="result">The result to bind with.</param>
/// <param name="binder">Function called with the input result value if it's Ok case.</param>
public static async Task<Result<TOut>> BindAsync<TIn, TOut>(this Task<Result<TIn>> result, Func<TIn, Task<Result<TOut>>> binder) =>
await (await result).BindAsync(binder);
/// <summary>
/// Transforms the <paramref name="result"/> into another <see cref="Result{T}"/> using the <paramref name="binder"/> function.
/// If the input result is Ok, returns the value of the binder call (which is <see cref="Result{T}"/> of <typeparamref name="TOut"/>).
/// Otherwise returns Error case of the Result of <typeparamref name="TOut"/>.
/// </summary>
/// <typeparam name="TIn">Type of the value in the input result.</typeparam>
/// <typeparam name="TOut">Type of the value in the returned result.</typeparam>
/// <param name="result">The result to bind with.</param>
/// <param name="binder">Function called with the input result value if it's Ok case.</param>
public static async Task<Result<TOut>> BindAsync<TIn, TOut>(this Task<Result<TIn>> result, Func<TIn, Result<TOut>> binder) =>
(await result).Bind(binder);
/* MapAsync */
/// <summary>
/// Maps the value of the <paramref name="result"/> into another <see cref="Result{T}"/> using the <paramref name="mapper"/> function.
/// If the input result is Ok, returns the Ok case with the value of the mapper call (which is <typeparamref name="TOut"/>).
/// Otherwise returns Error case of the Result of <typeparamref name="TOut"/>.
/// </summary>
/// <typeparam name="TIn">Type of the value in the input result.</typeparam>
/// <typeparam name="TOut">Type of the value in the returned result.</typeparam>
/// <param name="result">The result to map on.</param>
/// <param name="mapper">Function called with the input result value if it's Ok case.</param>
public static async Task<Result<TOut>> MapAsync<TIn, TOut>(this Result<TIn> result, Func<TIn, Task<TOut>> mapper) =>
(result.IsOk ? Ok(await mapper(result.Value)) : Error<TOut>(result.Error));
/// <summary>
/// Maps the value of the <paramref name="result"/> into another <see cref="Result{T}"/> using the <paramref name="mapper"/> function.
/// If the input result is Ok, returns the Ok case with the value of the mapper call (which is <typeparamref name="TOut"/>).
/// Otherwise returns Error case of the Result of <typeparamref name="TOut"/>.
/// </summary>
/// <typeparam name="TIn">Type of the value in the input result.</typeparam>
/// <typeparam name="TOut">Type of the value in the returned result.</typeparam>
/// <param name="result">The result to map on.</param>
/// <param name="mapper">Function called with the input result value if it's Ok case.</param>
public static async Task<Result<TOut>> MapAsync<TIn, TOut>(this Task<Result<TIn>> result, Func<TIn, Task<TOut>> mapper) =>
await (await result).MapAsync(mapper);
/// <summary>
/// Maps the value of the <paramref name="result"/> into another <see cref="Result{T}"/> using the <paramref name="mapper"/> function.
/// If the input result is Ok, returns the Ok case with the value of the mapper call (which is <typeparamref name="TOut"/>).
/// Otherwise returns Error case of the Result of <typeparamref name="TOut"/>.
/// </summary>
/// <typeparam name="TIn">Type of the value in the input result.</typeparam>
/// <typeparam name="TOut">Type of the value in the returned result.</typeparam>
/// <param name="result">The result to map on.</param>
/// <param name="mapper">Function called with the input result value if it's Ok case.</param>
public static async Task<Result<TOut>> MapAsync<TIn, TOut>(this Task<Result<TIn>> result, Func<TIn, TOut> mapper) =>
(await result).Map(mapper);
/* MatchAsync */
/// <summary>
/// Does the pattern matching on the <see cref="Result{T}"/> type.
/// If the <paramref name="result"/> is Ok, calls <paramref name="ok"/> function
/// with the value from the result as a parameter and returns its result.
/// Otherwise calls <paramref name="error"/> function and returns its result.
/// </summary>
/// <typeparam name="TIn">Type of the value in the result.</typeparam>
/// <typeparam name="TOut">Type of the returned value.</typeparam>
/// <param name="result">The result to match on.</param>
/// <param name="ok">Function called for the Ok case.</param>
/// <param name="error">Function called for the Error case.</param>
public static async Task<TOut> MatchAsync<TIn, TOut>(this Result<TIn> result, Func<TIn, Task<TOut>> ok, Func<ErrorDetails, Task<TOut>> error) =>
result.IsOk ? await ok(result.Value) : await error(result.Error);
/// <summary>
/// Does the pattern matching on the <see cref="Result{T}"/> type.
/// If the <paramref name="result"/> is Ok, calls <paramref name="ok"/> function
/// with the value from the result as a parameter and returns its result.
/// Otherwise calls <paramref name="error"/> function and returns its result.
/// </summary>
/// <typeparam name="TIn">Type of the value in the result.</typeparam>
/// <typeparam name="TOut">Type of the returned value.</typeparam>
/// <param name="result">The result to match on.</param>
/// <param name="ok">Function called for the Ok case.</param>
/// <param name="error">Function called for the Error case.</param>
public static async Task<TOut> MatchAsync<TIn, TOut>(this Result<TIn> result, Func<TIn, Task<TOut>> ok, Func<ErrorDetails, TOut> error) =>
result.IsOk ? await ok(result.Value) : error(result.Error);
/// <summary>
/// Does the pattern matching on the <see cref="Result{T}"/> type.
/// If the <paramref name="result"/> is Ok, calls <paramref name="ok"/> function
/// with the value from the result as a parameter and returns its result.
/// Otherwise calls <paramref name="error"/> function and returns its result.
/// </summary>
/// <typeparam name="TIn">Type of the value in the result.</typeparam>
/// <typeparam name="TOut">Type of the returned value.</typeparam>
/// <param name="result">The result to match on.</param>
/// <param name="ok">Function called for the Ok case.</param>
/// <param name="error">Function called for the Error case.</param>
public static async Task<TOut> MatchAsync<TIn, TOut>(this Result<TIn> result, Func<TIn, TOut> ok, Func<ErrorDetails, Task<TOut>> error) =>
result.IsOk ? ok(result.Value) : await error(result.Error);
/// <summary>
/// Does the pattern matching on the <see cref="Result{T}"/> type.
/// If the <paramref name="result"/> is Ok, calls <paramref name="ok"/> function
/// with the value from the result as a parameter and returns its result.
/// Otherwise calls <paramref name="error"/> function and returns its result.
/// </summary>
/// <typeparam name="TIn">Type of the value in the result.</typeparam>
/// <typeparam name="TOut">Type of the returned value.</typeparam>
/// <param name="result">The result to match on.</param>
/// <param name="ok">Function called for the Ok case.</param>
/// <param name="error">Function called for the Error case.</param>
public static async Task<TOut> MatchAsync<TIn, TOut>(this Task<Result<TIn>> result, Func<TIn, TOut> ok, Func<ErrorDetails, TOut> error) =>
(await result).Match(ok, error);
/// <summary>
/// Does the pattern matching on the <see cref="Result{T}"/> type.
/// If the <paramref name="result"/> is Ok, calls <paramref name="ok"/> function
/// with the value from the result as a parameter and returns its result.
/// Otherwise calls <paramref name="error"/> function and returns its result.
/// </summary>
/// <typeparam name="TIn">Type of the value in the result.</typeparam>
/// <typeparam name="TOut">Type of the returned value.</typeparam>
/// <param name="result">The result to match on.</param>
/// <param name="ok">Function called for the Ok case.</param>
/// <param name="error">Function called for the Error case.</param>
public static async Task<TOut> MatchAsync<TIn, TOut>(this Task<Result<TIn>> result, Func<TIn, Task<TOut>> ok, Func<ErrorDetails, Task<TOut>> error) =>
await (await result).MatchAsync(ok, error);
/// <summary>
/// Does the pattern matching on the <see cref="Result{T}"/> type.
/// If the <paramref name="result"/> is Ok, calls <paramref name="ok"/> function
/// with the value from the result as a parameter and returns its result.
/// Otherwise calls <paramref name="error"/> function and returns its result.
/// </summary>
/// <typeparam name="TIn">Type of the value in the result.</typeparam>
/// <typeparam name="TOut">Type of the returned value.</typeparam>
/// <param name="result">The result to match on.</param>
/// <param name="ok">Function called for the Ok case.</param>
/// <param name="error">Function called for the Error case.</param>
public static async Task<TOut> MatchAsync<TIn, TOut>(this Task<Result<TIn>> result, Func<TIn, Task<TOut>> ok, Func<ErrorDetails, TOut> error) =>
await (await result).MatchAsync(ok, error);
/// <summary>
/// Does the pattern matching on the <see cref="Result{T}"/> type.
/// If the <paramref name="result"/> is Ok, calls <paramref name="ok"/> function
/// with the value from the result as a parameter and returns its result.
/// Otherwise calls <paramref name="error"/> function and returns its result.
/// </summary>
/// <typeparam name="TIn">Type of the value in the result.</typeparam>
/// <typeparam name="TOut">Type of the returned value.</typeparam>
/// <param name="result">The result to match on.</param>
/// <param name="ok">Function called for the Ok case.</param>
/// <param name="error">Function called for the Error case.</param>
public static async Task<TOut> MatchAsync<TIn, TOut>(this Task<Result<TIn>> result, Func<TIn, TOut> ok, Func<ErrorDetails, Task<TOut>> error) =>
await (await result).MatchAsync(ok, error);
/* IgnoreAsync */
///<summary>
/// Rejects the value of the <see cref="Result{T}" /> and returns <see cref="Result{Unit}" /> instead.
/// If the input <see cref="Result{T}" /> is Error then the error details are preserved.
///</summary>
/// <typeparam name="T">Type of the encapsulated value.</typeparam>
/// <param name="result">The result of which the value should be ignored.</param>
public static async Task<Result<Unit.Unit>> IgnoreAsync<T>(this Task<Result<T>> result) =>
(await result).Map(_ => Unit.Unit.Default);
/* Side Effects */
/// <summary>
/// Performs the <paramref name="action"/> with the value of the <paramref name="result"/> if it's Ok case.
/// If the result is Error case nothing happens.
/// In both cases unmodified result is returned.
/// </summary>
/// <typeparam name="T">Type of the value in the result.</typeparam>
/// <param name="result">The result to check for a value.</param>
/// <param name="action">Function executed if the result is Ok case.</param>
public static async Task<Result<T>> DoAsync<T>(this Task<Result<T>> result, Action<T> action) =>
(await result).Do(action);
/// <summary>
/// Performs the <paramref name="action"/> with the value of the <paramref name="result"/> if it's Ok case.
/// If the result is Error case nothing happens.
/// In both cases unmodified result is returned.
/// </summary>
/// <typeparam name="T">Type of the value in the result.</typeparam>
/// <param name="result">The result to check for a value.</param>
/// <param name="action">Function executed if the result is Ok case.</param>
public static async Task<Result<T>> DoAsync<T>(this Result<T> result, Func<T, Task> action)
{
if (result.IsOk)
await action(result.Value);
return result;
}
/// <summary>
/// Performs the <paramref name="action"/> with the value of the <paramref name="result"/> if it's Ok case.
/// If the result is Error case nothing happens.
/// In both cases unmodified result is returned.
/// </summary>
/// <typeparam name="T">Type of the value in the result.</typeparam>
/// <param name="result">The result to check for a value.</param>
/// <param name="action">Function executed if the result is Ok case.</param>
public static async Task<Result<T>> DoAsync<T>(this Task<Result<T>> result, Func<T, Task> action) =>
await (await result).DoAsync(action);
/// <summary>
/// Performs the <paramref name="action"/> if the <paramref name="result"/> is Error case.
/// If the result is Ok case nothing happens.
/// In both cases unmodified result is returned.
/// </summary>
/// <typeparam name="T">Type of the value in the result.</typeparam>
/// <param name="result">The result to check for a value.</param>
/// <param name="action">Function executed if the result is Error case.</param>
public static async Task<Result<T>> DoWhenErrorAsync<T>(this Task<Result<T>> result, Action<ErrorDetails> action) =>
(await result).DoWhenError(action);
/// <summary>
/// Performs the <paramref name="action"/> if the <paramref name="result"/> is Error case.
/// If the result is Ok case nothing happens.
/// In both cases unmodified result is returned.
/// </summary>
/// <typeparam name="T">Type of the value in the result.</typeparam>
/// <param name="result">The result to check for a value.</param>
/// <param name="action">Function executed if the result is Error case.</param>
public static async Task<Result<T>> DoWhenErrorAsync<T>(this Result<T> result, Func<ErrorDetails, Task> action)
{
if (result.IsError)
await action(result.Error);
return result;
}
/// <summary>
/// Performs the <paramref name="action"/> if the <paramref name="result"/> is Error case.
/// If the result is Ok case nothing happens.
/// In both cases unmodified result is returned.
/// </summary>
/// <typeparam name="T">Type of the value in the result.</typeparam>
/// <param name="result">The result to check for a value.</param>
/// <param name="action">Function executed if the result is Error case.</param>
public static async Task<Result<T>> DoWhenErrorAsync<T>(this Task<Result<T>> result, Func<ErrorDetails, Task> action) =>
await (await result).DoWhenErrorAsync(action);
/* Flip */
/// <summary>
/// Transforms <see cref="Result{T}"/> with async value inside to <see cref="Task{T}"/> of the result,
/// preserving original result's state and value.
/// </summary>
/// <typeparam name="T">Type of the value in the result.</typeparam>
/// <param name="result">Result to take the value from.</param>
public static async Task<Result<T>> FlipAsync<T>(this Result<Task<T>> result) =>
result.IsOk
? Ok(await result.Value)
: Error<T>(result.Error);
/* TryCatchAsync */
/// <summary>
/// Tries to execute <paramref name="func"/>.
/// If the execution completes without exception, returns Ok with the function result.
/// Otherwise returns Error with details generated by <paramref name="errorHandler"/> based on the thrown exception.
/// </summary>
/// <typeparam name="T">Type of the value in the result.</typeparam>
/// <param name="func">Function to execute.</param>
/// <param name="errorHandler">Function that generates error details in case of exception.</param>
public static async Task<Result<T>> TryCatchAsync<T>(Func<Task<T>> func, Func<Exception, ErrorDetails> errorHandler)
{
try
{
var result = await func();
return Ok(result);
}
catch (Exception ex)
{
return Error<T>(errorHandler(ex));
}
}
/// <summary>
/// Tries to execute <paramref name="func"/> with the value from the <paramref name="result"/> as an input.
/// If the execution completes without exception, returns Ok with the function result.
/// Otherwise returns Error with details generated by <paramref name="errorHandler"/> based on the thrown exception.
/// If the <paramref name="result"/> is Error function is not executed and the Error is returned.
/// </summary>
/// <typeparam name="TIn">Type of the value in the input result.</typeparam>
/// <typeparam name="TOut">Type of the value in the output result.</typeparam>
/// <param name="result">Result to take the value from.</param>
/// <param name="func">Function to execute.</param>
/// <param name="errorHandler">Function that generates error details in case of exception.</param>
public static async Task<Result<TOut>> TryCatchAsync<TIn, TOut>(this Result<TIn> result, Func<TIn, Task<TOut>> func, Func<TIn, Exception, ErrorDetails> errorHandler) =>
await result.BindAsync(value => TryCatchAsync(() => func(value), e => errorHandler(value, e)));
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using CommandLineParser.Compatibility;
using CommandLineParser.Exceptions;
namespace CommandLineParser.Arguments
{
/// <summary>
/// Use EnumeratedValueArgument for an argument whose values must be from certain finite set
/// (see <see cref="AllowedValues"/>)
/// </summary>
/// <typeparam name="TValue">Type of the value</typeparam>
/// <include file='..\Doc\CommandLineParser.xml' path='CommandLineParser/Arguments/EnumeratedValueArgument/*'/>
public class EnumeratedValueArgument<TValue> : CertifiedValueArgument<TValue>
{
private ICollection<TValue> _allowedValues;
private bool _ignoreCase;
/// <summary>
/// Set of values that are allowed for the argument.
/// </summary>
public ICollection<TValue> AllowedValues
{
get { return _allowedValues; }
set { _allowedValues = value; }
}
/// <summary>
/// Initilazes <see cref="AllowedValues"/> by a string of values separated by commas or semicolons.
/// </summary>
/// <param name="valuesString">Allowed values (separated by comas or semicolons)</param>
public void InitAllowedValues(string valuesString)
{
string[] splitted = valuesString.Split(';', ',');
TValue[] typedValues = new TValue[splitted.Length];
int i = 0;
foreach (string value in splitted)
{
typedValues[i] = Convert(value);
i++;
}
AllowedValues = typedValues;
}
/// <summary>
/// String arguments will be accepted even with differences in capitalisation (e.g. INFO will be accepted for info).
/// </summary>
public bool IgnoreCase
{
get { return _ignoreCase; }
set
{
if (!(typeof(TValue) == typeof(string)) && value)
{
throw new ArgumentException(string.Format("Ignore case can be used only for string arguments, type of TValue is {0}", typeof(TValue)));
}
_ignoreCase = value;
}
}
#region constructor
/// <summary>
/// Creates new command line argument with a <see cref="Argument.ShortName">short name</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
public EnumeratedValueArgument(char shortName)
: base(shortName)
{
_allowedValues = new TValue[0];
}
/// <summary>
/// Creates new command line argument with a <see cref="Argument.LongName">long name</see>.
/// </summary>
/// <param name="longName">Long name of the argument</param>
public EnumeratedValueArgument(string longName) : base(longName) { }
/// <summary>
/// Creates new command line argument with a <see cref="Argument.ShortName">short name</see>
/// and <see cref="Argument.LongName">long name</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
/// <param name="longName">Long name of the argument </param>
public EnumeratedValueArgument(char shortName, string longName)
: base(shortName, longName)
{
_allowedValues = new TValue[0];
}
/// <summary>
/// Creates new command line argument with a <see cref="Argument.ShortName">short name</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
/// <param name="allowedValues">Allowed values</param>
public EnumeratedValueArgument(char shortName, ICollection<TValue> allowedValues)
: base(shortName)
{
_allowedValues = allowedValues;
}
/// <summary>
/// Creates new command line argument with a <see cref="Argument.LongName">long name</see>.
/// </summary>
/// <param name="longName">Short name of the argument</param>
/// <param name="allowedValues">Allowed values</param>
public EnumeratedValueArgument(string longName, ICollection<TValue> allowedValues)
: base(longName)
{
_allowedValues = allowedValues;
}
/// <summary>
/// Creates new command line argument with a <see cref="Argument.ShortName">short name</see>
/// and <see cref="Argument.LongName">long name</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
/// <param name="longName">Long name of the argument </param>
/// <param name="allowedValues">Allowed values</param>
public EnumeratedValueArgument(char shortName, string longName, ICollection<TValue> allowedValues)
: base(shortName, longName)
{
_allowedValues = allowedValues;
}
/// <summary>
/// Creates new command line argument with a <see cref="Argument.ShortName">short name</see>,
/// <see cref="Argument.LongName">long name</see> and <see cref="Argument.Description">description</see>
/// </summary>
/// <param name="shortName">Short name of the argument</param>
/// <param name="longName">Long name of the argument </param>
/// <param name="description">Description of the argument</param>
/// <param name="allowedValues">Allowed values</param>
public EnumeratedValueArgument(char shortName, string longName, string description, ICollection<TValue> allowedValues)
: base(shortName, longName, description)
{
_allowedValues = allowedValues;
}
#endregion
/// <summary>
/// Checks whether the specified value belongs to
/// the set of <see cref="AllowedValues">allowed values</see>.
/// </summary>
/// <param name="value">value to certify</param>
/// <exception cref="CommandLineArgumentOutOfRangeException">thrown when <paramref name="value"/> does not belong to the set of allowed values.</exception>
protected override void Certify(TValue value)
{
bool ok;
if (IgnoreCase && typeof(TValue) == typeof(string) && value is string)
{
TValue found = _allowedValues.FirstOrDefault(av => StringComparer.CurrentCultureIgnoreCase.Compare(value.ToString(), av.ToString()) == 0);
ok = found != null;
if (ok)
{
base.Value = found;
}
}
else
{
ok = _allowedValues.Contains(value);
}
if (!ok)
throw new CommandLineArgumentOutOfRangeException(String.Format(
Messages.EXC_ARG_ENUM_OUT_OF_RANGE, Value,
Name), Name);
}
}
/// <summary>
/// <para>
/// Attribute for declaring a class' field a <see cref="EnumeratedValueArgument{TValue}"/> and
/// thus binding a field's value to a certain command line switch argument.
/// </para>
/// <para>
/// Instead of creating an argument explicitly, you can assign a class' field an argument
/// attribute and let the CommandLineParse take care of binding the attribute to the field.
/// </para>
/// </summary>
/// <remarks>Appliable to fields and properties (public).</remarks>
/// <remarks>Use <see cref="CommandLineParser.ExtractArgumentAttributes"/> for each object
/// you where you have delcared argument attributes.</remarks>
public sealed class EnumeratedValueArgumentAttribute : ArgumentAttribute
{
private readonly Type _argumentType;
/// <summary>
/// Creates proper generic <see cref="BoundedValueArgument{TValue}"/> type for <paramref name="type"/>.
/// </summary>
/// <param name="type">type of the argument value</param>
/// <returns>generic type</returns>
private static Type CreateProperValueArgumentType(Type type)
{
Type genericType = typeof(EnumeratedValueArgument<>);
Type constructedType = genericType.MakeGenericType(type);
return constructedType;
}
/// <summary>
/// Creates new instance of EnumeratedValueArgumentAttribute. EnumeratedValueArgument
/// uses underlying <see cref="EnumeratedValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="EnumeratedValueArgument{TValue}"/>.</param>
/// <param name="shortName"><see cref="Argument.ShortName">short name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public EnumeratedValueArgumentAttribute(Type type, char shortName)
: base(CreateProperValueArgumentType(type), shortName)
{
_argumentType = CreateProperValueArgumentType(type);
}
/// <summary>
/// Creates new instance of EnumeratedValueArgumentAttribute. EnumeratedValueArgument
/// uses underlying <see cref="EnumeratedValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="EnumeratedValueArgument{TValue}"/>.</param>
/// <param name="longName"><see cref="Argument.LongName">short name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public EnumeratedValueArgumentAttribute(Type type, string longName)
: base(CreateProperValueArgumentType(type), longName)
{
_argumentType = CreateProperValueArgumentType(type);
}
/// <summary>
/// Creates new instance of EnumeratedValueArgument. EnumeratedValueArgument
/// uses underlying <see cref="EnumeratedValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="EnumeratedValueArgument{TValue}"/>.</param>
/// <param name="shortName"><see cref="Argument.ShortName">short name</see> of the underlying argument</param>
/// <param name="longName"><see cref="Argument.LongName">long name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public EnumeratedValueArgumentAttribute(Type type, char shortName, string longName)
: base(CreateProperValueArgumentType(type), shortName, longName)
{
_argumentType = CreateProperValueArgumentType(type);
}
/// <summary>
/// Allowed values of the argument, separated by commas or semicolons.
/// </summary>
public string AllowedValues
{
get
{
return string.Empty;
}
set
{
_argumentType.InvokeMethod("InitAllowedValues", Argument, value);
}
}
/// <summary>
/// Default value
/// </summary>
public object DefaultValue
{
get
{
return _argumentType.GetPropertyValue<object>("DefaultValue", Argument);
}
set
{
_argumentType.SetPropertyValue("DefaultValue", Argument, value);
}
}
/// <summary>
/// When set to true, argument can appear on the command line with or without value, e.g. both is allowed:
/// <code>
/// myexe.exe -Arg Value
/// OR
/// myexe.exe -Arg
/// </code>
/// </summary>
public bool ValueOptional
{
get
{
return _argumentType.GetPropertyValue<bool>("ValueOptional", Argument);
}
set
{
_argumentType.SetPropertyValue("ValueOptional", Argument, value);
}
}
/// <summary>
/// String arguments will be accepted even with differences in capitalisation (e.g. INFO will be accepted for info).
/// </summary>
public bool IgnoreCase
{
get
{
return _argumentType.GetPropertyValue<bool>("IgnoreCase", Argument);
}
set
{
_argumentType.SetPropertyValue("IgnoreCase", Argument, value);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using VulkanCore.Khr;
using static VulkanCore.Ext.DeviceExtensions;
namespace VulkanCore.Ext
{
/// <summary>
/// Provides extension methods for the <see cref="Device"/> class.
/// </summary>
public static unsafe class DeviceExtensions
{
/// <summary>
/// Give a user-friendly name to an object.
/// <para>
/// Applications may change the name associated with an object simply by calling <see
/// cref="DebugMarkerSetObjectNameExt"/> again with a new string. To remove a previously set
/// name, name should be set to an empty string.
/// </para>
/// </summary>
/// <param name="device">The device that created the object.</param>
/// <param name="nameInfo">Specifies the parameters of the name to set on the object.</param>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static void DebugMarkerSetObjectNameExt(this Device device, DebugMarkerObjectNameInfoExt nameInfo)
{
int nameByteCount = Interop.String.GetMaxByteCount(nameInfo.ObjectName);
byte* nameBytes = stackalloc byte[nameByteCount];
Interop.String.ToPointer(nameInfo.ObjectName, nameBytes, nameByteCount);
nameInfo.ToNative(out DebugMarkerObjectNameInfoExt.Native nativeNameInfo, nameBytes);
Result result = vkDebugMarkerSetObjectNameEXT(device)(device, &nativeNameInfo);
VulkanException.ThrowForInvalidResult(result);
}
/// <summary>
/// Attach arbitrary data to an object.
/// <para>
/// In addition to setting a name for an object, debugging and validation layers may have
/// uses for additional binary data on a per-object basis that has no other place in the
/// Vulkan API. For example, a <see cref="ShaderModule"/> could have additional debugging
/// data attached to it to aid in offline shader tracing.
/// </para>
/// </summary>
/// <param name="device">The device that created the object.</param>
/// <param name="tagInfo">Specifies the parameters of the tag to attach to the object.</param>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static void DebugMarkerSetObjectTagExt(this Device device, DebugMarkerObjectTagInfoExt tagInfo)
{
fixed (byte* tagPtr = tagInfo.Tag)
{
tagInfo.ToNative(out DebugMarkerObjectTagInfoExt.Native nativeTagInfo, tagPtr);
vkDebugMarkerSetObjectTagEXT(device)(device, &nativeTagInfo);
}
}
internal static DebugReportObjectTypeExt GetTypeForObject<T>(T obj)
{
string name = typeof(T).Name;
bool success = Enum.TryParse<DebugReportObjectTypeExt>(name, out var type);
return success ? type : DebugReportObjectTypeExt.Unknown;
}
/// <summary>
/// Set the power state of a display.
/// </summary>
/// <param name="device">The display whose power state is modified.</param>
/// <param name="display">A logical device associated with <paramref name="display"/>.</param>
/// <param name="displayPowerInfo">Specifies the new power state of <paramref name="display"/>.</param>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static void DisplayPowerControlExt(this Device device, DisplayKhr display,
DisplayPowerInfoExt displayPowerInfo)
{
displayPowerInfo.Prepare();
Result result = vkDisplayPowerControlEXT(device)(device, display, &displayPowerInfo);
VulkanException.ThrowForInvalidResult(result);
}
/// <summary>
/// Signal a fence when a device event occurs.
/// </summary>
/// <param name="device">A logical device on which the event may occur.</param>
/// <param name="deviceEventInfo">A structure describing the event of interest to the application.</param>
/// <param name="allocator">Controls host memory allocation.</param>
/// <returns>The resulting fence object.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static Fence RegisterDeviceEventExt(this Device device, DeviceEventInfoExt deviceEventInfo,
AllocationCallbacks? allocator = null)
{
deviceEventInfo.Prepare();
AllocationCallbacks.Native* nativeAllocator = null;
if (allocator.HasValue)
{
nativeAllocator = (AllocationCallbacks.Native*)Interop.Alloc<AllocationCallbacks.Native>();
allocator.Value.ToNative(nativeAllocator);
}
long handle;
Result result = vkRegisterDeviceEventEXT(device)(device, &deviceEventInfo, nativeAllocator, &handle);
Interop.Free(nativeAllocator);
VulkanException.ThrowForInvalidResult(result);
return new Fence(device, ref allocator, handle);
}
/// <summary>
/// Signal a fence when a display event occurs.
/// </summary>
/// <param name="device">A logical device associated with <paramref name="display"/>.</param>
/// <param name="display">The display on which the event may occur.</param>
/// <param name="displayEventInfo">
/// The structure describing the event of interest to the application.
/// </param>
/// <param name="allocator">Controls host memory allocation.</param>
/// <returns>The resulting fence object.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static Fence RegisterDisplayEventExt(this Device device, DisplayKhr display, DisplayEventInfoExt displayEventInfo,
AllocationCallbacks? allocator = null)
{
displayEventInfo.Prepare();
AllocationCallbacks.Native* nativeAllocator = null;
if (allocator.HasValue)
{
nativeAllocator = (AllocationCallbacks.Native*)Interop.Alloc<AllocationCallbacks.Native>();
allocator.Value.ToNative(nativeAllocator);
}
long handle;
Result result = vkRegisterDisplayEventEXT(device)(device, display, &displayEventInfo, nativeAllocator, &handle);
Interop.Free(nativeAllocator);
VulkanException.ThrowForInvalidResult(result);
return new Fence(device, ref allocator, handle);
}
/// <summary>
/// Function to set HDR metadata.
/// </summary>
/// <param name="device">The logical device where the swapchain(s) were created.</param>
/// <param name="swapchains">The array of <see cref="SwapchainKhr"/> handles.</param>
/// <param name="metadata">The array of <see cref="HdrMetadataExt"/> structures.</param>
public static void SetHdrMetadataExt(this Device device, SwapchainKhr[] swapchains, HdrMetadataExt[] metadata)
{
int swapchainCount = swapchains?.Length ?? 0;
var swapchainPtrs = stackalloc long[swapchainCount];
for (int i = 0; i < swapchainCount; i++)
swapchainPtrs[i] = swapchains[i];
int metadataCount = metadata?.Length ?? 0;
for (int i = 0; i < metadataCount; i++)
metadata[i].Prepare();
fixed (HdrMetadataExt* metadataPtr = metadata)
vkSetHdrMetadataEXT(device)(device, swapchainCount, swapchainPtrs, metadataPtr);
}
/// <summary>
/// Creates a new validation cache.
/// </summary>
/// <param name="device">The logical device that creates the validation cache object.</param>
/// <param name="createInfo">The initial parameters for the validation cache object.</param>
/// <param name="allocator">Controls host memory allocation.</param>
/// <returns>Handle in which the resulting validation cache object is returned.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static ValidationCacheExt CreateValidationCacheExt(this Device device,
ValidationCacheCreateInfoExt createInfo, AllocationCallbacks? allocator)
{
return new ValidationCacheExt(device, &createInfo, ref allocator);
}
/// <summary>
/// Get properties of external memory host pointer.
/// </summary>
/// <param name="device">The logical device that will be importing <paramref name="hostPointer"/>.</param>
/// <param name="handleType">The type of the handle <paramref name="hostPointer"/>.</param>
/// <param name="hostPointer">The host pointer to import from.</param>
/// <returns>Properties of external memory host pointer.</returns>
/// <exception cref="VulkanException">Vulkan returns an error code.</exception>
public static MemoryHostPointerPropertiesExt GetMemoryHostPointerPropertiesExt(this Device device,
ExternalMemoryHandleTypesKhr handleType, IntPtr hostPointer)
{
MemoryHostPointerPropertiesExt properties;
Result result = vkGetMemoryHostPointerPropertiesEXT(device)(device, handleType, hostPointer, &properties);
VulkanException.ThrowForInvalidResult(result);
return properties;
}
private delegate Result vkDebugMarkerSetObjectNameEXTDelegate(IntPtr device, DebugMarkerObjectNameInfoExt.Native* nameInfo);
private static vkDebugMarkerSetObjectNameEXTDelegate vkDebugMarkerSetObjectNameEXT(Device device) => device.GetProc<vkDebugMarkerSetObjectNameEXTDelegate>(nameof(vkDebugMarkerSetObjectNameEXT));
private delegate Result vkDebugMarkerSetObjectTagEXTDelegate(IntPtr device, DebugMarkerObjectTagInfoExt.Native* tagInfo);
private static vkDebugMarkerSetObjectTagEXTDelegate vkDebugMarkerSetObjectTagEXT(Device device) => device.GetProc<vkDebugMarkerSetObjectTagEXTDelegate>(nameof(vkDebugMarkerSetObjectTagEXT));
private delegate Result vkDisplayPowerControlEXTDelegate(IntPtr device, long display, DisplayPowerInfoExt* displayPowerInfo);
private static vkDisplayPowerControlEXTDelegate vkDisplayPowerControlEXT(Device device) => device.GetProc<vkDisplayPowerControlEXTDelegate>(nameof(vkDisplayPowerControlEXT));
private delegate Result vkRegisterDisplayEventEXTDelegate(IntPtr device, long display, DisplayEventInfoExt* displayEventInfo, AllocationCallbacks.Native* allocator, long* fence);
private static vkRegisterDisplayEventEXTDelegate vkRegisterDisplayEventEXT(Device device) => device.GetProc<vkRegisterDisplayEventEXTDelegate>(nameof(vkRegisterDisplayEventEXT));
private delegate Result vkRegisterDeviceEventEXTDelegate(IntPtr device, DeviceEventInfoExt* deviceEventInfo, AllocationCallbacks.Native* allocator, long* fence);
private static vkRegisterDeviceEventEXTDelegate vkRegisterDeviceEventEXT(Device device) => device.GetProc<vkRegisterDeviceEventEXTDelegate>(nameof(vkRegisterDeviceEventEXT));
private delegate void vkSetHdrMetadataEXTDelegate(IntPtr device, int swapchainCount, long* swapchains, HdrMetadataExt* metadata);
private static vkSetHdrMetadataEXTDelegate vkSetHdrMetadataEXT(Device device) => device.GetProc<vkSetHdrMetadataEXTDelegate>(nameof(vkSetHdrMetadataEXT));
private delegate Result vkGetMemoryHostPointerPropertiesEXTDelegate(IntPtr device, ExternalMemoryHandleTypesKhr handleType, IntPtr hostPointer, MemoryHostPointerPropertiesExt* memoryHostPointerProperties);
private static vkGetMemoryHostPointerPropertiesEXTDelegate vkGetMemoryHostPointerPropertiesEXT(Device device) => device.GetProc<vkGetMemoryHostPointerPropertiesEXTDelegate>(nameof(vkGetMemoryHostPointerPropertiesEXT));
}
/// <summary>
/// Specify parameters of a name to give to an object.
/// </summary>
public unsafe struct DebugMarkerObjectNameInfoExt
{
/// <summary>
/// Specifies specifying the type of the object to be named.
/// </summary>
public DebugReportObjectTypeExt ObjectType;
/// <summary>
/// The object to be named.
/// </summary>
public long Object;
/// <summary>
/// A unicode string specifying the name to apply to object.
/// </summary>
public string ObjectName;
/// <summary>
/// Initializes a new instance of the <see cref="DebugMarkerObjectNameInfoExt"/> structure.
/// </summary>
/// <param name="obj">Vulkan object to be name.</param>
/// <param name="name">Name to set.</param>
public DebugMarkerObjectNameInfoExt(VulkanHandle<IntPtr> obj, string name)
{
ObjectType = GetTypeForObject(obj);
Object = obj.Handle.ToInt64();
ObjectName = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="DebugMarkerObjectNameInfoExt"/> structure.
/// </summary>
/// <param name="obj">Vulkan object to name.</param>
/// <param name="name">Name to set.</param>
public DebugMarkerObjectNameInfoExt(VulkanHandle<long> obj, string name)
{
ObjectType = GetTypeForObject(obj);
Object = obj.Handle;
ObjectName = name;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public DebugReportObjectTypeExt ObjectType;
public long Object;
public byte* ObjectName;
}
internal void ToNative(out Native native, byte* objectName)
{
native.Type = StructureType.DebugMarkerObjectNameInfoExt;
native.Next = IntPtr.Zero;
native.ObjectType = ObjectType;
native.Object = Object;
native.ObjectName = objectName;
}
}
/// <summary>
/// Specify parameters of a tag to attach to an object.
/// </summary>
public unsafe struct DebugMarkerObjectTagInfoExt
{
/// <summary>
/// Specifies the type of the object to be named.
/// </summary>
public DebugReportObjectTypeExt ObjectType;
/// <summary>
/// The object to be tagged.
/// </summary>
public long Object;
/// <summary>
/// A numerical identifier of the tag.
/// </summary>
public long TagName;
/// <summary>
/// Bytes containing the data to be associated with the object.
/// </summary>
public byte[] Tag;
/// <summary>
/// Initializes a new instance of the <see cref="DebugMarkerObjectTagInfoExt"/> structure.
/// </summary>
/// <param name="obj">Vulkan object to be tagged.</param>
/// <param name="tagName">A numerical identifier of the tag.</param>
/// <param name="tag">Bytes containing the data to be associated with the object.</param>
public DebugMarkerObjectTagInfoExt(VulkanHandle<IntPtr> obj, long tagName, byte[] tag)
{
ObjectType = GetTypeForObject(obj);
Object = obj.Handle.ToInt64();
TagName = tagName;
Tag = tag;
}
/// <summary>
/// Initializes a new instance of the <see cref="DebugMarkerObjectTagInfoExt"/> structure.
/// </summary>
/// <param name="obj">Vulkan object to be tagged.</param>
/// <param name="tagName">A numerical identifier of the tag.</param>
/// <param name="tag">Bytes containing the data to be associated with the object.</param>
public DebugMarkerObjectTagInfoExt(VulkanHandle<long> obj, long tagName, byte[] tag)
{
ObjectType = GetTypeForObject(obj);
Object = obj.Handle;
TagName = tagName;
Tag = tag;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public StructureType Type;
public IntPtr Next;
public DebugReportObjectTypeExt ObjectType;
public long Object;
public long TagName;
public Size TagSize;
public byte* Tag;
}
internal void ToNative(out Native native, byte* tag)
{
native.Type = StructureType.DebugMarkerObjectTagInfoExt;
native.Next = IntPtr.Zero;
native.ObjectType = ObjectType;
native.Object = Object;
native.TagName = TagName;
native.TagSize = Tag?.Length ?? 0;
native.Tag = tag;
}
}
/// <summary>
/// Describe the power state of a display.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DisplayPowerInfoExt
{
internal StructureType Type;
internal IntPtr Next;
/// <summary>
/// The new power state of the display.
/// </summary>
public DisplayPowerStateExt PowerState;
/// <summary>
/// Initializes a new instance of the <see cref="DisplayPowerInfoExt"/> structure.
/// </summary>
/// <param name="powerState">The new power state of the display.</param>
public DisplayPowerInfoExt(DisplayPowerStateExt powerState)
{
Type = StructureType.DisplayPowerInfoExt;
Next = IntPtr.Zero;
PowerState = powerState;
}
internal void Prepare()
{
Type = StructureType.DisplayPowerInfoExt;
}
}
/// <summary>
/// Possible power states for a display.
/// </summary>
public enum DisplayPowerStateExt
{
/// <summary>
/// Specifies that the display is powered down.
/// </summary>
Off = 0,
/// <summary>
/// Specifies that the display is in a low power mode, but may be able to transition back to
/// <see cref="On"/> more quickly than if it were in <see cref="Off"/>.
/// <para>This state may be the same as <see cref="Off"/>.</para>
/// </summary>
Suspend = 1,
/// <summary>
/// Specifies that the display is powered on.
/// </summary>
On = 2
}
/// <summary>
/// Describe a device event to create.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DeviceEventInfoExt
{
internal StructureType Type;
internal IntPtr Next;
/// <summary>
/// Specifies when the fence will be signaled.
/// </summary>
public DeviceEventTypeExt DeviceEvent;
/// <summary>
/// Initializes a new instance of the <see cref="DeviceEventInfoExt"/> structure.
/// </summary>
/// <param name="deviceEvent">Specifies when the fence will be signaled.</param>
public DeviceEventInfoExt(DeviceEventTypeExt deviceEvent)
{
Type = StructureType.DeviceEventInfoExt;
Next = IntPtr.Zero;
DeviceEvent = deviceEvent;
}
internal void Prepare()
{
Type = StructureType.DeviceEventInfoExt;
}
}
/// <summary>
/// Describe a display event to create.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DisplayEventInfoExt
{
internal StructureType Type;
internal IntPtr Next;
/// <summary>
/// Specifies when the fence will be signaled.
/// </summary>
public DisplayEventTypeExt DisplayEvent;
/// <summary>
/// Initializes a new instance of the <see cref="DisplayEventInfoExt"/> structure.
/// </summary>
/// <param name="displayEvent">Specifies when the fence will be signaled.</param>
public DisplayEventInfoExt(DisplayEventTypeExt displayEvent)
{
Type = StructureType.DisplayEventInfoExt;
Next = IntPtr.Zero;
DisplayEvent = displayEvent;
}
internal void Prepare()
{
Type = StructureType.DisplayEventInfoExt;
}
}
/// <summary>
/// Events that can occur on a device object.
/// </summary>
public enum DeviceEventTypeExt
{
/// <summary>
/// Specifies that the fence is signaled when a display is plugged into or unplugged from the
/// specified device.
/// <para>
/// Applications can use this notification to determine when they need to re-enumerate the
/// available displays on a device.
/// </para>
/// </summary>
DisplayHotplug = 0
}
/// <summary>
/// Events that can occur on a display object.
/// </summary>
public enum DisplayEventTypeExt
{
/// <summary>
/// Specifies that the fence is signaled when the first pixel of the next display refresh
/// cycle leaves the display engine for the display.
/// </summary>
FirstPixelOut = 0
}
/// <summary>
/// Structure to specify HDR metadata.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct HdrMetadataExt
{
internal StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The mastering display's red primary in chromaticity coordinates.
/// </summary>
public XYColorExt DisplayPrimaryRed;
/// <summary>
/// The mastering display's green primary in chromaticity coordinates.
/// </summary>
public XYColorExt DisplayPrimaryGreen;
/// <summary>
/// The mastering display's blue primary in chromaticity coordinates.
/// </summary>
public XYColorExt DisplayPrimaryBlue;
/// <summary>
/// The mastering display's white-point in chromaticity coordinates.
/// </summary>
public XYColorExt WhitePoint;
/// <summary>
/// The maximum luminance of the mastering display in nits.
/// </summary>
public float MaxLuminance;
/// <summary>
/// The minimum luminance of the mastering display in nits.
/// </summary>
public float MinLuminance;
/// <summary>
/// Content's maximum luminance in nits.
/// </summary>
public float MaxContentLightLevel;
/// <summary>
/// The maximum frame average light level in nits.
/// </summary>
public float MaxFrameAverageLightLevel;
internal void Prepare()
{
Type = StructureType.HdrMetadataExt;
}
}
/// <summary>
/// Structure to specify X,Y chromaticity coordinates.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct XYColorExt
{
/// <summary>
/// The X coordinate of chromaticity limited to between 0 and 1.
/// </summary>
public float X;
/// <summary>
/// The Y coordinate of chromaticity limited to between 0 and 1.
/// </summary>
public float Y;
}
/// <summary>
/// Specify a system wide priority.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DeviceQueueGlobalPriorityCreateInfoExt
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The system-wide priority associated to this queue as specified by <see
/// cref="QueueGlobalPriorityExt"/>.
/// </summary>
public QueueGlobalPriorityExt GlobalPriority;
}
/// <summary>
/// Values specifying a system-wide queue priority.
/// </summary>
public enum QueueGlobalPriorityExt
{
/// <summary>
/// Below the system default. Useful for non-interactive tasks.
/// </summary>
Low = 128,
/// <summary>
/// The system default priority.
/// </summary>
Medium = 256,
/// <summary>
/// Above the system default.
/// </summary>
High = 512,
/// <summary>
/// The highest priority. Useful for critical tasks.
/// </summary>
Realtime = 1024
}
/// <summary>
/// Import memory from a host pointer.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ImportMemoryHostPointerInfoExt
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// Specifies the handle type.
/// </summary>
public ExternalMemoryHandleTypesKhr HandleType;
/// <summary>
/// The host pointer to import from.
/// </summary>
public IntPtr HostPointer;
}
/// <summary>
/// Roperties of external memory host pointer.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MemoryHostPointerPropertiesExt
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// A bitmask containing one bit set for every memory type which the specified host pointer
/// can be imported as.
/// </summary>
public int MemoryTypeBits;
}
/// <summary>
/// Structure describing external memory host pointer limits that can be supported by an implementation.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct PhysicalDeviceExternalMemoryHostPropertiesExt
{
public StructureType Type;
public IntPtr Next;
public long MinImportedHostPointerAlignment;
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using QuantConnect.Configuration;
using QuantConnect.Logging;
namespace QuantConnect.Brokerages.InteractiveBrokers
{
/// <summary>
/// Handles launching and killing the IB Controller script
/// </summary>
/// <remarks>
/// Requires TWS or IB Gateway and IBController installed to run
/// </remarks>
public static class InteractiveBrokersGatewayRunner
{
// process that's running the IB Controller script
private static int _scriptProcessId;
// parameters needed for restart
private static string _ibControllerDirectory;
private static string _twsDirectory;
private static string _userId;
private static string _password;
private static string _tradingMode;
private static bool _useTws;
/// <summary>
/// Starts the interactive brokers gateway using values from configuration
/// </summary>
public static void StartFromConfiguration()
{
Start(Config.Get("ib-controller-dir"),
Config.Get("ib-tws-dir"),
Config.Get("ib-user-name"),
Config.Get("ib-password"),
Config.Get("ib-trading-mode"),
Config.GetBool("ib-use-tws")
);
}
/// <summary>
/// Starts the IB Gateway
/// </summary>
/// <param name="ibControllerDirectory">Directory to the IB controller installation</param>
/// <param name="twsDirectory"></param>
/// <param name="userId">The log in user id</param>
/// <param name="password">The log in password</param>
/// <param name="tradingMode">Live or Paper trading modes</param>
/// <param name="useTws">True to use Trader Work Station, false to just launch the API gateway</param>
public static void Start(string ibControllerDirectory, string twsDirectory, string userId, string password, string tradingMode, bool useTws = false)
{
_ibControllerDirectory = ibControllerDirectory;
_twsDirectory = twsDirectory;
_userId = userId;
_password = password;
_tradingMode = tradingMode;
_useTws = useTws;
var useTwsSwitch = useTws ? "TWS" : "GATEWAY";
var batchFilename = Path.Combine("InteractiveBrokers", "run-ib-controller.bat");
var bashFilename = Path.Combine("InteractiveBrokers", "run-ib-controller.sh");
try
{
var file = OS.IsWindows ? batchFilename : bashFilename;
var arguments = string.Format("{0} {1} {2} {3} {4} {5} {6}", file, ibControllerDirectory, twsDirectory, userId, password, useTwsSwitch, tradingMode);
Log.Trace($"InteractiveBrokersGatewayRunner.Start(): Launching IBController: {file} {ibControllerDirectory} {twsDirectory} {userId} XXX {useTwsSwitch} {tradingMode}");
var processStartInfo = OS.IsWindows ? new ProcessStartInfo("cmd.exe", "/C " + arguments) : new ProcessStartInfo("bash", arguments);
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardOutput = false;
var process = Process.Start(processStartInfo);
_scriptProcessId = process != null ? process.Id : 0;
// wait a few seconds for IB to start up
Thread.Sleep(TimeSpan.FromSeconds(30));
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Stops the IB Gateway
/// </summary>
public static void Stop()
{
if (_scriptProcessId == 0)
{
return;
}
try
{
Log.Trace("InteractiveBrokersGatewayRunner.Stop(): Stopping IBController...");
if (OS.IsWindows)
{
if (_useTws)
{
foreach (var process in Process.GetProcessesByName("java"))
{
if (process.MainWindowTitle.Contains("Interactive Brokers"))
{
process.Kill();
Thread.Sleep(2500);
}
}
foreach (var process in Process.GetProcessesByName("cmd"))
{
if (process.MainWindowTitle.ToLower().Contains("ibcontroller"))
{
process.Kill();
Thread.Sleep(2500);
}
}
}
else
{
foreach (var process in Process.GetProcesses())
{
try
{
if (process.MainWindowTitle.ToLower().Contains("ibcontroller") ||
process.MainWindowTitle.ToLower().Contains("ib gateway"))
{
process.Kill();
Thread.Sleep(2500);
}
}
catch (Exception)
{
// ignored
}
}
}
}
else
{
try
{
Process.Start("pkill", "xvfb-run");
Process.Start("pkill", "java");
Process.Start("pkill", "Xvfb");
Thread.Sleep(2500);
}
catch (Exception)
{
// ignored
}
}
_scriptProcessId = 0;
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Returns true if IB Gateway is running
/// </summary>
/// <returns></returns>
public static bool IsRunning()
{
if (_scriptProcessId == 0)
{
return false;
}
// do not restart if using TWS instead of Gateway
if (_useTws)
{
return true;
}
try
{
return IsIbControllerRunning();
}
catch (Exception err)
{
Log.Error(err);
}
return false;
}
/// <summary>
/// Restarts the IB Gateway, needed if shut down unexpectedly
/// </summary>
public static void Restart()
{
Start(_ibControllerDirectory, _twsDirectory, _userId, _password, _tradingMode, _useTws);
}
/// <summary>
/// Detects if the IB Controller is running
/// </summary>
private static bool IsIbControllerRunning()
{
if (OS.IsWindows)
{
foreach (var process in Process.GetProcesses())
{
try
{
if (process.MainWindowTitle.ToLower().Contains("ibcontroller"))
{
return true;
}
}
catch (Exception)
{
// ignored
}
}
}
else
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "bash",
Arguments = "-c 'ps aux | grep -v bash | grep java | grep ibgateway'",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
process.Start();
var output = process.StandardOutput.ReadToEnd();
var processFound = output.Contains("java") && output.Contains("ibgateway");
process.WaitForExit();
return processFound;
}
return false;
}
private static IEnumerable<Process> GetSpawnedProcesses(int id)
{
// loop over all the processes and return those that were spawned by the specified processed ID
return Process.GetProcesses().Where(x =>
{
try
{
var parent = ProcessExtensions.Parent(x);
if (parent != null)
{
return parent.Id == id;
}
}
catch
{
return false;
}
return false;
});
}
//http://stackoverflow.com/questions/394816/how-to-get-parent-process-in-net-in-managed-way
private static class ProcessExtensions
{
private static string FindIndexedProcessName(int pid)
{
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;
for (var index = 0; index < processesByName.Length; index++)
{
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int)processId.NextValue() == pid)
{
return processIndexdName;
}
}
return processIndexdName;
}
private static Process FindPidFromIndexedProcessName(string indexedProcessName)
{
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int)parentId.NextValue());
}
public static Process Parent(Process process)
{
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Securities;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Represents a grouping of data emitted at a certain time.
/// </summary>
public class TimeSlice
{
/// <summary>
/// Gets the count of data points in this <see cref="TimeSlice"/>
/// </summary>
public int DataPointCount { get; private set; }
/// <summary>
/// Gets the time this data was emitted
/// </summary>
public DateTime Time { get; private set; }
/// <summary>
/// Gets the data in the time slice
/// </summary>
public List<KeyValuePair<Security, List<BaseData>>> Data { get; private set; }
/// <summary>
/// Gets the <see cref="Slice"/> that will be used as input for the algorithm
/// </summary>
public Slice Slice { get; private set; }
/// <summary>
/// Gets the data used to update the cash book
/// </summary>
public List<KeyValuePair<Cash, BaseData>> CashBookUpdateData { get; private set; }
/// <summary>
/// Gets the data used to update securities
/// </summary>
public List<KeyValuePair<Security, BaseData>> SecuritiesUpdateData { get; private set; }
/// <summary>
/// Gets the data used to update the consolidators
/// </summary>
public List<KeyValuePair<SubscriptionDataConfig, List<BaseData>>> ConsolidatorUpdateData { get; private set; }
/// <summary>
/// Gets all the custom data in this <see cref="TimeSlice"/>
/// </summary>
public List<KeyValuePair<Security, List<BaseData>>> CustomData { get; private set; }
/// <summary>
/// Gets the changes to the data subscriptions as a result of universe selection
/// </summary>
public SecurityChanges SecurityChanges { get; set; }
/// <summary>
/// Initializes a new <see cref="TimeSlice"/> containing the specified data
/// </summary>
public TimeSlice(DateTime time, int dataPointCount, Slice slice, List<KeyValuePair<Security, List<BaseData>>> data, List<KeyValuePair<Cash, BaseData>> cashBookUpdateData, List<KeyValuePair<Security, BaseData>> securitiesUpdateData, List<KeyValuePair<SubscriptionDataConfig, List<BaseData>>> consolidatorUpdateData, List<KeyValuePair<Security, List<BaseData>>> customData, SecurityChanges securityChanges)
{
Time = time;
Data = data;
Slice = slice;
CustomData = customData;
DataPointCount = dataPointCount;
CashBookUpdateData = cashBookUpdateData;
SecuritiesUpdateData = securitiesUpdateData;
ConsolidatorUpdateData = consolidatorUpdateData;
SecurityChanges = securityChanges;
}
/// <summary>
/// Creates a new <see cref="TimeSlice"/> for the specified time using the specified data
/// </summary>
/// <param name="utcDateTime">The UTC frontier date time</param>
/// <param name="algorithmTimeZone">The algorithm's time zone, required for computing algorithm and slice time</param>
/// <param name="cashBook">The algorithm's cash book, required for generating cash update pairs</param>
/// <param name="data">The data in this <see cref="TimeSlice"/></param>
/// <param name="changes">The new changes that are seen in this time slice as a result of universe selection</param>
/// <returns>A new <see cref="TimeSlice"/> containing the specified data</returns>
public static TimeSlice Create(DateTime utcDateTime, DateTimeZone algorithmTimeZone, CashBook cashBook, List<KeyValuePair<Security, List<BaseData>>> data, SecurityChanges changes)
{
int count = 0;
var security = new List<KeyValuePair<Security, BaseData>>();
var custom = new List<KeyValuePair<Security, List<BaseData>>>();
var consolidator = new List<KeyValuePair<SubscriptionDataConfig, List<BaseData>>>();
var allDataForAlgorithm = new List<BaseData>(data.Count);
var cash = new List<KeyValuePair<Cash, BaseData>>(cashBook.Count);
var cashSecurities = new HashSet<Symbol>();
foreach (var cashItem in cashBook.Values)
{
cashSecurities.Add(cashItem.SecuritySymbol);
}
Split split;
Dividend dividend;
Delisting delisting;
SymbolChangedEvent symbolChange;
var algorithmTime = utcDateTime.ConvertFromUtc(algorithmTimeZone);
var tradeBars = new TradeBars(algorithmTime);
var ticks = new Ticks(algorithmTime);
var splits = new Splits(algorithmTime);
var dividends = new Dividends(algorithmTime);
var delistings = new Delistings(algorithmTime);
var symbolChanges = new SymbolChangedEvents(algorithmTime);
foreach (var kvp in data)
{
var list = kvp.Value;
var symbol = kvp.Key.Symbol;
// keep count of all data points
count += list.Count;
BaseData update = null;
var consolidatorUpdate = new List<BaseData>(list.Count);
for (int i = 0; i < list.Count; i++)
{
var baseData = list[i];
if (!kvp.Key.SubscriptionDataConfig.IsInternalFeed)
{
// this is all the data that goes into the algorithm
allDataForAlgorithm.Add(baseData);
}
if (kvp.Key.SubscriptionDataConfig.IsCustomData)
{
// this is all the custom data
custom.Add(kvp);
}
// don't add internal feed data to ticks/bars objects
if (baseData.DataType != MarketDataType.Auxiliary)
{
if (!kvp.Key.SubscriptionDataConfig.IsInternalFeed)
{
// populate ticks and tradebars dictionaries with no aux data
if (baseData.DataType == MarketDataType.Tick)
{
List<Tick> ticksList;
if (!ticks.TryGetValue(symbol, out ticksList))
{
ticksList = new List<Tick> {(Tick) baseData};
ticks[symbol] = ticksList;
}
ticksList.Add((Tick) baseData);
}
else if (baseData.DataType == MarketDataType.TradeBar)
{
tradeBars[symbol] = (TradeBar) baseData;
}
// this is data used to update consolidators
consolidatorUpdate.Add(baseData);
}
// this is the data used set market prices
update = baseData;
}
// include checks for various aux types so we don't have to construct the dictionaries in Slice
else if ((delisting = baseData as Delisting) != null)
{
delistings[symbol] = delisting;
}
else if ((dividend = baseData as Dividend) != null)
{
dividends[symbol] = dividend;
}
else if ((split = baseData as Split) != null)
{
splits[symbol] = split;
}
else if ((symbolChange = baseData as SymbolChangedEvent) != null)
{
// symbol changes is keyed by the requested symbol
symbolChanges[kvp.Key.SubscriptionDataConfig.Symbol] = symbolChange;
}
}
// check for 'cash securities' if we found valid update data for this symbol
// and we need this data to update cash conversion rates, long term we should
// have Cash hold onto it's security, then he can update himself, or rather, just
// patch through calls to conversion rate to compue it on the fly using Security.Price
if (update != null && cashSecurities.Contains(kvp.Key.Symbol))
{
foreach (var cashKvp in cashBook)
{
if (cashKvp.Value.SecuritySymbol == kvp.Key.Symbol)
{
cash.Add(new KeyValuePair<Cash, BaseData>(cashKvp.Value, update));
}
}
}
security.Add(new KeyValuePair<Security, BaseData>(kvp.Key, update));
consolidator.Add(new KeyValuePair<SubscriptionDataConfig, List<BaseData>>(kvp.Key.SubscriptionDataConfig, consolidatorUpdate));
}
var slice = new Slice(utcDateTime.ConvertFromUtc(algorithmTimeZone), allDataForAlgorithm, tradeBars, ticks, splits, dividends, delistings, symbolChanges);
return new TimeSlice(utcDateTime, count, slice, data, cash, security, consolidator, custom, changes);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableQueueTest : SimpleElementImmutablesTestBase
{
private void EnqueueDequeueTestHelper<T>(params T[] items)
{
Assert.NotNull(items);
var queue = ImmutableQueue<T>.Empty;
int i = 0;
foreach (T item in items)
{
var nextQueue = queue.Enqueue(item);
Assert.NotSame(queue, nextQueue); //, "Enqueue returned this instead of a new instance.");
Assert.Equal(i, queue.Count()); //, "Enqueue mutated the queue.");
Assert.Equal(++i, nextQueue.Count());
queue = nextQueue;
}
i = 0;
foreach (T element in queue)
{
AssertAreSame(items[i++], element);
}
i = 0;
foreach (T element in (System.Collections.IEnumerable)queue)
{
AssertAreSame(items[i++], element);
}
i = items.Length;
foreach (T expectedItem in items)
{
T actualItem = queue.Peek();
AssertAreSame(expectedItem, actualItem);
var nextQueue = queue.Dequeue();
Assert.NotSame(queue, nextQueue); //, "Dequeue returned this instead of a new instance.");
Assert.Equal(i, queue.Count());
Assert.Equal(--i, nextQueue.Count());
queue = nextQueue;
}
}
[Fact]
public void EnumerationOrder()
{
var queue = ImmutableQueue<int>.Empty;
// Push elements onto the backwards stack.
queue = queue.Enqueue(1).Enqueue(2).Enqueue(3);
Assert.Equal(1, queue.Peek());
// Force the backwards stack to be reversed and put into forwards.
queue = queue.Dequeue();
// Push elements onto the backwards stack again.
queue = queue.Enqueue(4).Enqueue(5);
// Now that we have some elements on the forwards and backwards stack,
// 1. enumerate all elements to verify order.
Assert.Equal<int>(new[] { 2, 3, 4, 5 }, queue.ToArray());
// 2. dequeue all elements to verify order
var actual = new int[queue.Count()];
for (int i = 0; i < actual.Length; i++)
{
actual[i] = queue.Peek();
queue = queue.Dequeue();
}
}
[Fact]
public void GetEnumeratorText()
{
var queue = ImmutableQueue.Create(5);
var enumeratorStruct = queue.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
Assert.True(enumeratorStruct.MoveNext());
Assert.Equal(5, enumeratorStruct.Current);
Assert.False(enumeratorStruct.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
var enumerator = ((IEnumerable<int>)queue).GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var queue = ImmutableQueue.Create(5);
var enumerator = ((IEnumerable<int>)queue).GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
// As pure structs with no disposable reference types inside it,
// we have nothing to track across struct copies, and this just works.
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
////Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = ((IEnumerable<int>)queue).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(queue.Peek(), enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void EnqueueDequeueTest()
{
this.EnqueueDequeueTestHelper(new GenericParameterHelper(1), new GenericParameterHelper(2), new GenericParameterHelper(3));
this.EnqueueDequeueTestHelper<GenericParameterHelper>();
// interface test
IImmutableQueue<GenericParameterHelper> queueInterface = ImmutableQueue.Create<GenericParameterHelper>();
IImmutableQueue<GenericParameterHelper> populatedQueueInterface = queueInterface.Enqueue(new GenericParameterHelper(5));
Assert.Equal(new GenericParameterHelper(5), populatedQueueInterface.Peek());
}
[Fact]
public void DequeueOutValue()
{
var queue = ImmutableQueue<int>.Empty.Enqueue(5).Enqueue(6);
int head;
queue = queue.Dequeue(out head);
Assert.Equal(5, head);
var emptyQueue = queue.Dequeue(out head);
Assert.Equal(6, head);
Assert.True(emptyQueue.IsEmpty);
// Also check that the interface extension method works.
IImmutableQueue<int> interfaceQueue = queue;
Assert.Same(emptyQueue, interfaceQueue.Dequeue(out head));
Assert.Equal(6, head);
}
[Fact]
public void ClearTest()
{
var emptyQueue = ImmutableQueue.Create<GenericParameterHelper>();
AssertAreSame(emptyQueue, emptyQueue.Clear());
var nonEmptyQueue = emptyQueue.Enqueue(new GenericParameterHelper(3));
AssertAreSame(emptyQueue, nonEmptyQueue.Clear());
// Interface test
IImmutableQueue<GenericParameterHelper> queueInterface = nonEmptyQueue;
AssertAreSame(emptyQueue, queueInterface.Clear());
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableQueue<int>.Empty.Equals(null));
Assert.False(ImmutableQueue<int>.Empty.Equals("hi"));
Assert.True(ImmutableQueue<int>.Empty.Equals(ImmutableQueue<int>.Empty));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5).Equals(ImmutableQueue<int>.Empty.Enqueue(3)));
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Equals(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(5)));
// Also be sure to compare equality of partially dequeued queues since that moves data to different fields.
Assert.False(ImmutableQueue<int>.Empty.Enqueue(3).Enqueue(1).Enqueue(2).Dequeue().Equals(ImmutableQueue<int>.Empty.Enqueue(1).Enqueue(2)));
}
[Fact]
public void PeekEmptyThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Peek());
}
[Fact]
public void DequeueEmptyThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableQueue<GenericParameterHelper>.Empty.Dequeue());
}
[Fact]
public void Create()
{
ImmutableQueue<int> queue = ImmutableQueue.Create<int>();
Assert.True(queue.IsEmpty);
queue = ImmutableQueue.Create(1);
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1 }, queue);
queue = ImmutableQueue.Create(1, 2);
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
queue = ImmutableQueue.CreateRange((IEnumerable<int>)new[] { 1, 2 });
Assert.False(queue.IsEmpty);
Assert.Equal(new[] { 1, 2 }, queue);
Assert.Throws<ArgumentNullException>("items", () => ImmutableQueue.CreateRange((IEnumerable<int>)null));
Assert.Throws<ArgumentNullException>("items", () => ImmutableQueue.Create((int[])null));
}
[Fact]
public void Empty()
{
// We already test Create(), so just prove that Empty has the same effect.
Assert.Same(ImmutableQueue.Create<int>(), ImmutableQueue<int>.Empty);
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableQueue.Create<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableQueue.Create<string>());
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var queue = ImmutableQueue<T>.Empty;
foreach (var item in contents)
{
queue = queue.Enqueue(item);
}
return queue;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.Security;
using System.ServiceModel;
namespace System.Runtime
{
internal class ExceptionTrace
{
private const ushort FailFastEventLogCategory = 6;
private string _eventSourceName;
private readonly EtwDiagnosticTrace _diagnosticTrace;
public ExceptionTrace(string eventSourceName, EtwDiagnosticTrace diagnosticTrace)
{
Fx.Assert(diagnosticTrace != null, "'diagnosticTrace' MUST NOT be NULL.");
_eventSourceName = eventSourceName;
_diagnosticTrace = diagnosticTrace;
}
public void AsInformation(Exception exception)
{
//Traces an informational trace message
}
public void AsWarning(Exception exception)
{
//Traces a warning trace message
}
public Exception AsError(Exception exception)
{
// AggregateExceptions are automatically unwrapped.
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return AsError<Exception>(aggregateException);
}
// TargetInvocationExceptions are automatically unwrapped.
TargetInvocationException targetInvocationException = exception as TargetInvocationException;
if (targetInvocationException != null && targetInvocationException.InnerException != null)
{
return AsError(targetInvocationException.InnerException);
}
return TraceException<Exception>(exception);
}
public Exception AsError(Exception exception, string eventSource)
{
// AggregateExceptions are automatically unwrapped.
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return AsError<Exception>(aggregateException, eventSource);
}
// TargetInvocationExceptions are automatically unwrapped.
TargetInvocationException targetInvocationException = exception as TargetInvocationException;
if (targetInvocationException != null && targetInvocationException.InnerException != null)
{
return AsError(targetInvocationException.InnerException, eventSource);
}
return TraceException<Exception>(exception, eventSource);
}
public Exception AsError(TargetInvocationException targetInvocationException, string eventSource)
{
Fx.Assert(targetInvocationException != null, "targetInvocationException cannot be null.");
// If targetInvocationException contains any fatal exceptions, return it directly
// without tracing it or any inner exceptions.
if (Fx.IsFatal(targetInvocationException))
{
return targetInvocationException;
}
// A non-null inner exception could require further unwrapping in AsError.
Exception innerException = targetInvocationException.InnerException;
if (innerException != null)
{
return AsError(innerException, eventSource);
}
// A null inner exception is unlikely but possible.
// In this case, trace and return the targetInvocationException itself.
return TraceException<Exception>(targetInvocationException, eventSource);
}
public Exception AsError<TPreferredException>(AggregateException aggregateException)
{
return AsError<TPreferredException>(aggregateException, _eventSourceName);
}
/// <summary>
/// Extracts the first inner exception of type <typeparamref name="TPreferredException"/>
/// from the <see cref="AggregateException"/> if one is present.
/// </summary>
/// <remarks>
/// If no <typeparamref name="TPreferredException"/> inner exception is present, this
/// method returns the first inner exception. All inner exceptions will be traced,
/// including the one returned. The containing <paramref name="aggregateException"/>
/// will not be traced unless there are no inner exceptions.
/// </remarks>
/// <typeparam name="TPreferredException">The preferred type of inner exception to extract.
/// Use <c>typeof(Exception)</c> to extract the first exception regardless of type.</typeparam>
/// <param name="aggregateException">The <see cref="AggregateException"/> to examine.</param>
/// <param name="eventSource">The event source to trace.</param>
/// <returns>The extracted exception. It will not be <c>null</c>
/// but it may not be of type <typeparamref name="TPreferredException"/>.</returns>
public Exception AsError<TPreferredException>(AggregateException aggregateException, string eventSource)
{
Fx.Assert(aggregateException != null, "aggregateException cannot be null.");
// If aggregateException contains any fatal exceptions, return it directly
// without tracing it or any inner exceptions.
if (Fx.IsFatal(aggregateException))
{
return aggregateException;
}
// Collapse possibly nested graph into a flat list.
// Empty inner exception list is unlikely but possible via public api.
ReadOnlyCollection<Exception> innerExceptions = aggregateException.Flatten().InnerExceptions;
if (innerExceptions.Count == 0)
{
return TraceException(aggregateException, eventSource);
}
// Find the first inner exception, giving precedence to TPreferredException
Exception favoredException = null;
foreach (Exception nextInnerException in innerExceptions)
{
// AggregateException may wrap TargetInvocationException, so unwrap those as well
TargetInvocationException targetInvocationException = nextInnerException as TargetInvocationException;
Exception innerException = (targetInvocationException != null && targetInvocationException.InnerException != null)
? targetInvocationException.InnerException
: nextInnerException;
if (innerException is TPreferredException && favoredException == null)
{
favoredException = innerException;
}
// All inner exceptions are traced
TraceException<Exception>(innerException, eventSource);
}
if (favoredException == null)
{
Fx.Assert(innerExceptions.Count > 0, "InnerException.Count is known to be > 0 here.");
favoredException = innerExceptions[0];
}
return favoredException;
}
public ArgumentException Argument(string paramName, string message)
{
return TraceException<ArgumentException>(new ArgumentException(message, paramName));
}
public ArgumentNullException ArgumentNull(string paramName)
{
return TraceException<ArgumentNullException>(new ArgumentNullException(paramName));
}
public ArgumentNullException ArgumentNull(string paramName, string message)
{
return TraceException<ArgumentNullException>(new ArgumentNullException(paramName, message));
}
public ArgumentException ArgumentNullOrEmpty(string paramName)
{
return this.Argument(paramName, InternalSR.ArgumentNullOrEmpty(paramName));
}
public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message)
{
return TraceException<ArgumentOutOfRangeException>(new ArgumentOutOfRangeException(paramName, actualValue, message));
}
// 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));
}
public void TraceUnhandledException(Exception exception)
{
TraceCore.UnhandledException(_diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
}
public void TraceEtwException(Exception exception, EventLevel eventLevel)
{
}
private TException TraceException<TException>(TException exception)
where TException : Exception
{
return TraceException<TException>(exception, _eventSourceName);
}
[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")]
[SecuritySafeCritical]
private TException TraceException<TException>(TException exception, string eventSource)
where TException : Exception
{
if (TraceCore.ThrowingExceptionIsEnabled(_diagnosticTrace))
{
TraceCore.ThrowingException(_diagnosticTrace, eventSource, exception != null ? exception.ToString() : string.Empty, exception);
}
BreakOnException(exception);
return exception;
}
[Fx.Tag.SecurityNote(Critical = "Calls into critical method UnsafeNativeMethods.IsDebuggerPresent and UnsafeNativeMethods.DebugBreak",
Safe = "Safe because it's a no-op in retail builds.")]
[SecuritySafeCritical]
private void BreakOnException(Exception exception)
{
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void TraceFailFast(string message)
{
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using System.Linq;
/// <summary>
/// Specifies details of the jobs to be created on a schedule.
/// </summary>
public partial class JobSpecification
{
/// <summary>
/// Initializes a new instance of the JobSpecification class.
/// </summary>
public JobSpecification() { }
/// <summary>
/// Initializes a new instance of the JobSpecification class.
/// </summary>
/// <param name="poolInfo">The pool on which the Batch service runs the
/// tasks of jobs created under this schedule.</param>
/// <param name="priority">The priority of jobs created under this
/// schedule.</param>
/// <param name="displayName">The display name for jobs created under
/// this schedule.</param>
/// <param name="usesTaskDependencies">The flag that determines if this
/// job will use tasks with dependencies.</param>
/// <param name="onAllTasksComplete">The action the Batch service
/// should take when all tasks in a job created under this schedule are
/// in the completed state.</param>
/// <param name="onTaskFailure">The action the Batch service should
/// take when any task fails in a job created under this schedule. A
/// task is considered to have failed if it completes with a non-zero
/// exit code and has exhausted its retry count, or if it had a
/// scheduling error.</param>
/// <param name="constraints">The execution constraints for jobs
/// created under this schedule.</param>
/// <param name="jobManagerTask">The details of a Job Manager task to
/// be launched when a job is started under this schedule.</param>
/// <param name="jobPreparationTask">The Job Preparation task for jobs
/// created under this schedule.</param>
/// <param name="jobReleaseTask">The Job Release task for jobs created
/// under this schedule.</param>
/// <param name="commonEnvironmentSettings">A list of common
/// environment variable settings. These environment variables are set
/// for all tasks in jobs created under this schedule (including the
/// Job Manager, Job Preparation and Job Release tasks).</param>
/// <param name="metadata">A list of name-value pairs associated with
/// each job created under this schedule as metadata.</param>
public JobSpecification(PoolInformation poolInfo, int? priority = default(int?), string displayName = default(string), bool? usesTaskDependencies = default(bool?), OnAllTasksComplete? onAllTasksComplete = default(OnAllTasksComplete?), OnTaskFailure? onTaskFailure = default(OnTaskFailure?), JobConstraints constraints = default(JobConstraints), JobManagerTask jobManagerTask = default(JobManagerTask), JobPreparationTask jobPreparationTask = default(JobPreparationTask), JobReleaseTask jobReleaseTask = default(JobReleaseTask), System.Collections.Generic.IList<EnvironmentSetting> commonEnvironmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), System.Collections.Generic.IList<MetadataItem> metadata = default(System.Collections.Generic.IList<MetadataItem>))
{
Priority = priority;
DisplayName = displayName;
UsesTaskDependencies = usesTaskDependencies;
OnAllTasksComplete = onAllTasksComplete;
OnTaskFailure = onTaskFailure;
Constraints = constraints;
JobManagerTask = jobManagerTask;
JobPreparationTask = jobPreparationTask;
JobReleaseTask = jobReleaseTask;
CommonEnvironmentSettings = commonEnvironmentSettings;
PoolInfo = poolInfo;
Metadata = metadata;
}
/// <summary>
/// Gets or sets the priority of jobs created under this schedule.
/// </summary>
/// <remarks>
/// Priority values can range from -1000 to 1000, with -1000 being the
/// lowest priority and 1000 being the highest priority. The default
/// value is 0. This priority is used as the default for all jobs under
/// the job schedule. You can update a job's priority after it has been
/// created using by using the update job API.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets or sets the display name for jobs created under this schedule.
/// </summary>
/// <remarks>
/// The name need not be unique and can contain any Unicode characters
/// up to a maximum length of 1024.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the flag that determines if this job will use tasks
/// with dependencies.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "usesTaskDependencies")]
public bool? UsesTaskDependencies { get; set; }
/// <summary>
/// Gets or sets the action the Batch service should take when all
/// tasks in a job created under this schedule are in the completed
/// state.
/// </summary>
/// <remarks>
/// Note that if a job contains no tasks, then all tasks are considered
/// complete. This option is therefore most commonly used with a Job
/// Manager task; if you want to use automatic job termination without
/// a Job Manager, you should initially set onAllTasksComplete to
/// noAction and update the job properties to set onAllTasksComplete to
/// terminateJob once you have finished adding tasks. The default is
/// noAction. Possible values include: 'noAction', 'terminateJob'
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "onAllTasksComplete")]
public OnAllTasksComplete? OnAllTasksComplete { get; set; }
/// <summary>
/// Gets or sets the action the Batch service should take when any task
/// fails in a job created under this schedule. A task is considered to
/// have failed if it completes with a non-zero exit code and has
/// exhausted its retry count, or if it had a scheduling error.
/// </summary>
/// <remarks>
/// The default is noAction. Possible values include: 'noAction',
/// 'performExitOptionsJobAction'
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "onTaskFailure")]
public OnTaskFailure? OnTaskFailure { get; set; }
/// <summary>
/// Gets or sets the execution constraints for jobs created under this
/// schedule.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "constraints")]
public JobConstraints Constraints { get; set; }
/// <summary>
/// Gets or sets the details of a Job Manager task to be launched when
/// a job is started under this schedule.
/// </summary>
/// <remarks>
/// If the job does not specify a Job Manager task, the user must
/// explicitly add tasks to the job using the Task API. If the job does
/// specify a Job Manager task, the Batch service creates the Job
/// Manager task when the job is created, and will try to schedule the
/// Job Manager task before scheduling other tasks in the job.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobManagerTask")]
public JobManagerTask JobManagerTask { get; set; }
/// <summary>
/// Gets or sets the Job Preparation task for jobs created under this
/// schedule.
/// </summary>
/// <remarks>
/// If a job has a Job Preparation task, the Batch service will run the
/// Job Preparation task on a compute node before starting any tasks of
/// that job on that compute node.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobPreparationTask")]
public JobPreparationTask JobPreparationTask { get; set; }
/// <summary>
/// Gets or sets the Job Release task for jobs created under this
/// schedule.
/// </summary>
/// <remarks>
/// The primary purpose of the Job Release task is to undo changes to
/// compute nodes made by the Job Preparation task. Example activities
/// include deleting local files, or shutting down services that were
/// started as part of job preparation. A Job Release task cannot be
/// specified without also specifying a Job Preparation task for the
/// job. The Batch service runs the Job Release task on the compute
/// nodes that have run the Job Preparation task.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "jobReleaseTask")]
public JobReleaseTask JobReleaseTask { get; set; }
/// <summary>
/// Gets or sets a list of common environment variable settings. These
/// environment variables are set for all tasks in jobs created under
/// this schedule (including the Job Manager, Job Preparation and Job
/// Release tasks).
/// </summary>
/// <remarks>
/// Individual tasks can override an environment setting specified here
/// by specifying the same setting name with a different value.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "commonEnvironmentSettings")]
public System.Collections.Generic.IList<EnvironmentSetting> CommonEnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets the pool on which the Batch service runs the tasks of
/// jobs created under this schedule.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "poolInfo")]
public PoolInformation PoolInfo { get; set; }
/// <summary>
/// Gets or sets a list of name-value pairs associated with each job
/// created under this schedule as metadata.
/// </summary>
/// <remarks>
/// The Batch service does not assign any meaning to metadata; it is
/// solely for the use of user code.
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "metadata")]
public System.Collections.Generic.IList<MetadataItem> Metadata { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (PoolInfo == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "PoolInfo");
}
if (this.JobManagerTask != null)
{
this.JobManagerTask.Validate();
}
if (this.JobPreparationTask != null)
{
this.JobPreparationTask.Validate();
}
if (this.JobReleaseTask != null)
{
this.JobReleaseTask.Validate();
}
if (this.CommonEnvironmentSettings != null)
{
foreach (var element in this.CommonEnvironmentSettings)
{
if (element != null)
{
element.Validate();
}
}
}
if (this.PoolInfo != null)
{
this.PoolInfo.Validate();
}
if (this.Metadata != null)
{
foreach (var element1 in this.Metadata)
{
if (element1 != null)
{
element1.Validate();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.ClusterState2
{
public partial class ClusterState2YamlTests
{
public class ClusterState220FilteringYamlBase : YamlTestsBase
{
public ClusterState220FilteringYamlBase() : base()
{
//do index
_body = new {
text= "The quick brown fox is brown."
};
this.Do(()=> _client.Index("testidx", "testtype", "testing_document", _body));
//do indices.refresh
this.Do(()=> _client.IndicesRefreshForAll());
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class FilteringTheClusterStateByBlocksShouldReturnTheBlocksFieldEvenIfTheResponseIsEmpty2Tests : ClusterState220FilteringYamlBase
{
[Test]
public void FilteringTheClusterStateByBlocksShouldReturnTheBlocksFieldEvenIfTheResponseIsEmpty2Test()
{
//do cluster.state
this.Do(()=> _client.ClusterState("blocks"));
//is_true _response.blocks;
this.IsTrue(_response.blocks);
//is_false _response.nodes;
this.IsFalse(_response.nodes);
//is_false _response.metadata;
this.IsFalse(_response.metadata);
//is_false _response.routing_table;
this.IsFalse(_response.routing_table);
//is_false _response.routing_nodes;
this.IsFalse(_response.routing_nodes);
//is_false _response.allocations;
this.IsFalse(_response.allocations);
//length _response.blocks: 0;
this.IsLength(_response.blocks, 0);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class FilteringTheClusterStateByBlocksShouldReturnTheBlocks3Tests : ClusterState220FilteringYamlBase
{
[Test]
public void FilteringTheClusterStateByBlocksShouldReturnTheBlocks3Test()
{
//do indices.put_settings
_body = new Dictionary<string, object> {
{ @"index.blocks.read_only", @"true" }
};
this.Do(()=> _client.IndicesPutSettings("testidx", _body));
//do cluster.state
this.Do(()=> _client.ClusterState("blocks"));
//is_true _response.blocks;
this.IsTrue(_response.blocks);
//is_false _response.nodes;
this.IsFalse(_response.nodes);
//is_false _response.metadata;
this.IsFalse(_response.metadata);
//is_false _response.routing_table;
this.IsFalse(_response.routing_table);
//is_false _response.routing_nodes;
this.IsFalse(_response.routing_nodes);
//is_false _response.allocations;
this.IsFalse(_response.allocations);
//length _response.blocks: 1;
this.IsLength(_response.blocks, 1);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class FilteringTheClusterStateByNodesOnlyShouldWork4Tests : ClusterState220FilteringYamlBase
{
[Test]
public void FilteringTheClusterStateByNodesOnlyShouldWork4Test()
{
//do cluster.state
this.Do(()=> _client.ClusterState("nodes"));
//is_false _response.blocks;
this.IsFalse(_response.blocks);
//is_true _response.nodes;
this.IsTrue(_response.nodes);
//is_false _response.metadata;
this.IsFalse(_response.metadata);
//is_false _response.routing_table;
this.IsFalse(_response.routing_table);
//is_false _response.routing_nodes;
this.IsFalse(_response.routing_nodes);
//is_false _response.allocations;
this.IsFalse(_response.allocations);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class FilteringTheClusterStateByMetadataOnlyShouldWork5Tests : ClusterState220FilteringYamlBase
{
[Test]
public void FilteringTheClusterStateByMetadataOnlyShouldWork5Test()
{
//do cluster.state
this.Do(()=> _client.ClusterState("metadata"));
//is_false _response.blocks;
this.IsFalse(_response.blocks);
//is_false _response.nodes;
this.IsFalse(_response.nodes);
//is_true _response.metadata;
this.IsTrue(_response.metadata);
//is_false _response.routing_table;
this.IsFalse(_response.routing_table);
//is_false _response.routing_nodes;
this.IsFalse(_response.routing_nodes);
//is_false _response.allocations;
this.IsFalse(_response.allocations);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class FilteringTheClusterStateByRoutingTableOnlyShouldWork6Tests : ClusterState220FilteringYamlBase
{
[Test]
public void FilteringTheClusterStateByRoutingTableOnlyShouldWork6Test()
{
//do cluster.state
this.Do(()=> _client.ClusterState("routing_table"));
//is_false _response.blocks;
this.IsFalse(_response.blocks);
//is_false _response.nodes;
this.IsFalse(_response.nodes);
//is_false _response.metadata;
this.IsFalse(_response.metadata);
//is_true _response.routing_table;
this.IsTrue(_response.routing_table);
//is_true _response.routing_nodes;
this.IsTrue(_response.routing_nodes);
//is_true _response.allocations;
this.IsTrue(_response.allocations);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class FilteringTheClusterStateByIndicesShouldWorkInRoutingTableAndMetadata7Tests : ClusterState220FilteringYamlBase
{
[Test]
public void FilteringTheClusterStateByIndicesShouldWorkInRoutingTableAndMetadata7Test()
{
//do index
_body = new {
text= "The quick brown fox is brown."
};
this.Do(()=> _client.Index("another", "type", "testing_document", _body));
//do indices.refresh
this.Do(()=> _client.IndicesRefreshForAll());
//do cluster.state
this.Do(()=> _client.ClusterState("routing_table,metadata", "testidx"));
//is_false _response.metadata.indices.another;
this.IsFalse(_response.metadata.indices.another);
//is_false _response.routing_table.indices.another;
this.IsFalse(_response.routing_table.indices.another);
//is_true _response.metadata.indices.testidx;
this.IsTrue(_response.metadata.indices.testidx);
//is_true _response.routing_table.indices.testidx;
this.IsTrue(_response.routing_table.indices.testidx);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class FilteringTheClusterStateUsingAllForIndicesAndMetricsShouldWork8Tests : ClusterState220FilteringYamlBase
{
[Test]
public void FilteringTheClusterStateUsingAllForIndicesAndMetricsShouldWork8Test()
{
//do cluster.state
this.Do(()=> _client.ClusterState("_all", "_all"));
//is_true _response.blocks;
this.IsTrue(_response.blocks);
//is_true _response.nodes;
this.IsTrue(_response.nodes);
//is_true _response.metadata;
this.IsTrue(_response.metadata);
//is_true _response.routing_table;
this.IsTrue(_response.routing_table);
//is_true _response.routing_nodes;
this.IsTrue(_response.routing_nodes);
//is_true _response.allocations;
this.IsTrue(_response.allocations);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using AutoRest.Core.ClientModel;
using AutoRest.Core.Logging;
using AutoRest.Core.Properties;
using AutoRest.Core.Utilities;
namespace AutoRest.Core
{
public abstract class CodeNamer
{
private static readonly IDictionary<char, string> basicLaticCharacters;
protected CodeNamer()
{
ReservedWords = new HashSet<string>();
}
/// <summary>
/// Gets collection of reserved words.
/// </summary>
public HashSet<string> ReservedWords { get; private set; }
/// <summary>
/// Formats segments of a string split by underscores or hyphens into "Camel" case strings.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public static string CamelCase(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
if (name[0] == '_')
// Preserve leading underscores.
return '_' + CamelCase(name.Substring(1));
return
name.Split('_', '-', ' ')
.Where(s => !string.IsNullOrEmpty(s))
.Select((s, i) => FormatCase(s, i == 0)) // Pass true/toLower for just the first element.
.DefaultIfEmpty("")
.Aggregate(string.Concat);
}
/// <summary>
/// Formats segments of a string split by underscores or hyphens into "Pascal" case.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public static string PascalCase(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
if (name[0] == '_')
// Preserve leading underscores and treat them like
// uppercase characters by calling 'CamelCase()' on the rest.
return '_' + CamelCase(name.Substring(1));
return
name.Split('_', '-', ' ')
.Where(s => !string.IsNullOrEmpty(s))
.Select(s => FormatCase(s, false))
.DefaultIfEmpty("")
.Aggregate(string.Concat);
}
/// <summary>
/// Wraps value in quotes and escapes quotes inside.
/// </summary>
/// <param name="value">String to quote</param>
/// <param name="quoteChar">Quote character</param>
/// <param name="escapeChar">Escape character</param>
/// <exception cref="System.ArgumentNullException">Throw when either quoteChar or escapeChar are null.</exception>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public static string QuoteValue(string value, string quoteChar = "\"", string escapeChar = "\\")
{
if (quoteChar == null)
{
throw new ArgumentNullException("quoteChar");
}
if (escapeChar == null)
{
throw new ArgumentNullException("escapeChar");
}
if (value == null)
{
value = string.Empty;
}
return quoteChar + value.Replace(quoteChar, escapeChar + quoteChar) + quoteChar;
}
/// <summary>
/// Recursively normalizes names in the client model
/// </summary>
/// <param name="client"></param>
public virtual void NormalizeClientModel(ServiceClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
client.Name = GetClientName(client.Name);
client.Namespace = GetNamespaceName(client.Namespace);
NormalizeClientProperties(client);
var normalizedModels = new List<CompositeType>();
foreach (var modelType in client.ModelTypes)
{
normalizedModels.Add(NormalizeTypeDeclaration(modelType) as CompositeType);
modelType.Properties.ForEach(p => QuoteParameter(p));
}
client.ModelTypes.Clear();
normalizedModels.ForEach((item) => client.ModelTypes.Add(item));
var normalizedErrors = new List<CompositeType>();
foreach (var modelType in client.ErrorTypes)
{
normalizedErrors.Add(NormalizeTypeDeclaration(modelType) as CompositeType);
}
client.ErrorTypes.Clear();
normalizedErrors.ForEach((item) => client.ErrorTypes.Add(item));
var normalizedHeaders = new List<CompositeType>();
foreach (var modelType in client.HeaderTypes)
{
normalizedHeaders.Add(NormalizeTypeDeclaration(modelType) as CompositeType);
}
client.HeaderTypes.Clear();
normalizedHeaders.ForEach((item) => client.HeaderTypes.Add(item));
var normalizedEnums = new List<EnumType>();
foreach (var enumType in client.EnumTypes)
{
var normalizedType = NormalizeTypeDeclaration(enumType) as EnumType;
if (normalizedType != null)
{
normalizedEnums.Add(NormalizeTypeDeclaration(enumType) as EnumType);
}
}
client.EnumTypes.Clear();
normalizedEnums.ForEach((item) => client.EnumTypes.Add(item));
foreach (var method in client.Methods)
{
NormalizeMethod(method);
}
}
/// <summary>
/// Normalizes the client properties names of a client model
/// </summary>
/// <param name="client">A client model</param>
protected virtual void NormalizeClientProperties(ServiceClient client)
{
if (client != null)
{
foreach (var property in client.Properties)
{
property.Name = GetPropertyName(property.Name);
property.Type = NormalizeTypeReference(property.Type);
QuoteParameter(property);
}
}
}
/// <summary>
/// Normalizes names in the method
/// </summary>
/// <param name="method"></param>
public virtual void NormalizeMethod(Method method)
{
if (method == null)
{
throw new ArgumentNullException("method");
}
method.Name = GetMethodName(method.Name);
method.Group = GetMethodGroupName(method.Group);
method.ReturnType = NormalizeTypeReference(method.ReturnType);
method.DefaultResponse = NormalizeTypeReference(method.DefaultResponse);
var normalizedResponses = new Dictionary<HttpStatusCode, Response>();
foreach (var statusCode in method.Responses.Keys)
{
normalizedResponses[statusCode] = NormalizeTypeReference(method.Responses[statusCode]);
}
method.Responses.Clear();
foreach (var statusCode in normalizedResponses.Keys)
{
method.Responses[statusCode] = normalizedResponses[statusCode];
}
NormalizeParameters(method);
}
/// <summary>
/// Normalizes the parameter names of a method
/// </summary>
/// <param name="method">A method model</param>
protected virtual void NormalizeParameters(Method method)
{
if (method != null)
{
foreach (var parameter in method.Parameters)
{
parameter.Name = method.Scope.GetUniqueName(GetParameterName(parameter.Name));
parameter.Type = NormalizeTypeReference(parameter.Type);
QuoteParameter(parameter);
}
foreach (var parameterTransformation in method.InputParameterTransformation)
{
parameterTransformation.OutputParameter.Name = method.Scope.GetUniqueName(GetParameterName(parameterTransformation.OutputParameter.Name));
parameterTransformation.OutputParameter.Type = NormalizeTypeReference(parameterTransformation.OutputParameter.Type);
QuoteParameter(parameterTransformation.OutputParameter);
foreach (var parameterMapping in parameterTransformation.ParameterMappings)
{
if (parameterMapping.InputParameterProperty != null)
{
parameterMapping.InputParameterProperty = GetPropertyName(parameterMapping.InputParameterProperty);
}
if (parameterMapping.OutputParameterProperty != null)
{
parameterMapping.OutputParameterProperty = GetPropertyName(parameterMapping.OutputParameterProperty);
}
}
}
}
}
/// <summary>
/// Quotes default value of the parameter.
/// </summary>
/// <param name="parameter"></param>
protected void QuoteParameter(IParameter parameter)
{
if (parameter != null)
{
parameter.DefaultValue = EscapeDefaultValue(parameter.DefaultValue, parameter.Type);
}
}
/// <summary>
/// Returns a quoted string for the given language if applicable.
/// </summary>
/// <param name="defaultValue">Value to quote.</param>
/// <param name="type">Data type.</param>
public abstract string EscapeDefaultValue(string defaultValue, IType type);
/// <summary>
/// Formats a string for naming members of an enum using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetEnumMemberName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(name));
}
/// <summary>
/// Formats a string for naming fields using a prefix '_' and VariableName Camel case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetFieldName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return '_' + GetVariableName(name);
}
/// <summary>
/// Formats a string for naming interfaces using a prefix 'I' and Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetInterfaceName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return "I" + PascalCase(RemoveInvalidCharacters(name));
}
/// <summary>
/// Formats a string for naming a method using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetMethodName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Operation")));
}
/// <summary>
/// Formats a string for identifying a namespace using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetNamespaceName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharactersNamespace(name));
}
/// <summary>
/// Formats a string for naming method parameters using GetVariableName Camel case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetParameterName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return GetVariableName(GetEscapedReservedName(name, "Parameter"));
}
/// <summary>
/// Formats a string for naming properties using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetPropertyName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Property")));
}
/// <summary>
/// Formats a string for naming a Type or Object using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetTypeName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
}
/// <summary>
/// Formats a string for naming a Method Group using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetMethodGroupName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
}
public virtual string GetClientName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
}
/// <summary>
/// Formats a string for naming a local variable using Camel case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetVariableName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return CamelCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Variable")));
}
/// <summary>
/// Returns language specific type reference name.
/// </summary>
/// <param name="typePair"></param>
/// <returns></returns>
public virtual Response NormalizeTypeReference(Response typePair)
{
return new Response(NormalizeTypeReference(typePair.Body),
NormalizeTypeReference(typePair.Headers));
}
/// <summary>
/// Returns language specific type reference name.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public abstract IType NormalizeTypeReference(IType type);
/// <summary>
/// Returns language specific type declaration name.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public abstract IType NormalizeTypeDeclaration(IType type);
/// <summary>
/// Formats a string as upper or lower case. Two-letter inputs that are all upper case are both lowered.
/// Example: ID = > id, Ex => ex
/// </summary>
/// <param name="name"></param>
/// <param name="toLower"></param>
/// <returns>The formatted string.</returns>
private static string FormatCase(string name, bool toLower)
{
if (!string.IsNullOrEmpty(name))
{
if (name.Length < 2 || (name.Length == 2 && char.IsUpper(name[0]) && char.IsUpper(name[1])))
{
name = toLower ? name.ToLowerInvariant() : name.ToUpperInvariant();
}
else
{
name =
(toLower
? char.ToLowerInvariant(name[0])
: char.ToUpperInvariant(name[0])) + name.Substring(1, name.Length - 1);
}
}
return name;
}
/// <summary>
/// Removes invalid characters from the name. Everything but alpha-numeral, underscore,
/// and dash.
/// </summary>
/// <param name="name">String to parse.</param>
/// <returns>Name with invalid characters removed.</returns>
public static string RemoveInvalidCharacters(string name)
{
return GetValidName(name, '_', '-');
}
/// <summary>
/// Removes invalid characters from the namespace. Everything but alpha-numeral, underscore,
/// period, and dash.
/// </summary>
/// <param name="name">String to parse.</param>
/// <returns>Namespace with invalid characters removed.</returns>
protected virtual string RemoveInvalidCharactersNamespace(string name)
{
return GetValidName(name, '_', '-', '.');
}
/// <summary>
/// Gets valid name for the identifier.
/// </summary>
/// <param name="name">String to parse.</param>
/// <param name="allowedCharacters">Allowed characters.</param>
/// <returns>Name with invalid characters removed.</returns>
protected static string GetValidName(string name, params char[] allowedCharacters)
{
var correctName = RemoveInvalidCharacters(name, allowedCharacters);
// here we have only letters and digits or an empty string
if (string.IsNullOrEmpty(correctName) ||
basicLaticCharacters.ContainsKey(correctName[0]))
{
var sb = new StringBuilder();
foreach (char symbol in name)
{
if (basicLaticCharacters.ContainsKey(symbol))
{
sb.Append(basicLaticCharacters[symbol]);
}
else
{
sb.Append(symbol);
}
}
correctName = RemoveInvalidCharacters(sb.ToString(), allowedCharacters);
}
// if it is still empty string, throw
if (correctName.IsNullOrEmpty())
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName, name));
}
return correctName;
}
/// <summary>
/// Removes invalid characters from the name.
/// </summary>
/// <param name="name">String to parse.</param>
/// <param name="allowerCharacters">Allowed characters.</param>
/// <returns>Name with invalid characters removed.</returns>
private static string RemoveInvalidCharacters(string name, params char[] allowerCharacters)
{
return new string(name.Replace("[]", "Sequence")
.Where(c => char.IsLetterOrDigit(c) || allowerCharacters.Contains(c))
.ToArray());
}
/// <summary>
/// If the provided name is a reserved word in a programming language then the method converts the
/// name by appending the provided appendValue
/// </summary>
/// <param name="name">Name.</param>
/// <param name="appendValue">String to append.</param>
/// <returns>The transformed reserved name</returns>
protected virtual string GetEscapedReservedName(string name, string appendValue)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (appendValue == null)
{
throw new ArgumentNullException("appendValue");
}
if (ReservedWords.Contains(name, StringComparer.OrdinalIgnoreCase))
{
name += appendValue;
}
return name;
}
/// <summary>
/// Resolves name collisions in the client model by iterating over namespaces (if provided,
/// model names, client name, and client method groups.
/// </summary>
/// <param name="serviceClient">Service client to process.</param>
/// <param name="clientNamespace">Client namespace or null.</param>
/// <param name="modelNamespace">Client model namespace or null.</param>
public virtual void ResolveNameCollisions(ServiceClient serviceClient, string clientNamespace,
string modelNamespace)
{
if (serviceClient == null)
{
throw new ArgumentNullException("serviceClient");
}
// take all namespaces of Models
var exclusionListQuery = SplitNamespaceAndIgnoreLast(modelNamespace)
.Union(SplitNamespaceAndIgnoreLast(clientNamespace));
var exclusionDictionary = new Dictionary<string, string>(exclusionListQuery
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToDictionary(s => s, v => "namespace"), StringComparer.OrdinalIgnoreCase);
var models = new List<CompositeType>(serviceClient.ModelTypes);
serviceClient.ModelTypes.Clear();
foreach (var model in models)
{
model.Name = ResolveNameConflict(
exclusionDictionary,
model.Name,
"Schema definition",
"Model");
serviceClient.ModelTypes.Add(model);
}
models = new List<CompositeType>(serviceClient.HeaderTypes);
serviceClient.HeaderTypes.Clear();
foreach (var model in models)
{
model.Name = ResolveNameConflict(
exclusionDictionary,
model.Name,
"Schema definition",
"Model");
serviceClient.HeaderTypes.Add(model);
}
foreach (var model in serviceClient.ModelTypes
.Concat(serviceClient.HeaderTypes)
.Concat(serviceClient.ErrorTypes))
{
foreach (var property in model.Properties)
{
if (property.Name.Equals(model.Name, StringComparison.OrdinalIgnoreCase))
{
property.Name += "Property";
}
}
}
var enumTypes = new List<EnumType>(serviceClient.EnumTypes);
serviceClient.EnumTypes.Clear();
foreach (var enumType in enumTypes)
{
enumType.Name = ResolveNameConflict(
exclusionDictionary,
enumType.Name,
"Enum name",
"Enum");
serviceClient.EnumTypes.Add(enumType);
}
serviceClient.Name = ResolveNameConflict(
exclusionDictionary,
serviceClient.Name,
"Client",
"Client");
ResolveMethodGroupNameCollision(serviceClient, exclusionDictionary);
}
/// <summary>
/// Resolves name collisions in the client model for method groups (operations).
/// </summary>
/// <param name="serviceClient"></param>
/// <param name="exclusionDictionary"></param>
protected virtual void ResolveMethodGroupNameCollision(ServiceClient serviceClient,
Dictionary<string, string> exclusionDictionary)
{
if (serviceClient == null)
{
throw new ArgumentNullException("serviceClient");
}
if (exclusionDictionary == null)
{
throw new ArgumentNullException("exclusionDictionary");
}
var methodGroups = serviceClient.MethodGroups.ToList();
foreach (var methodGroup in methodGroups)
{
var resolvedName = ResolveNameConflict(
exclusionDictionary,
methodGroup,
"Client operation",
"Operations");
foreach (var method in serviceClient.Methods)
{
if (method.Group == methodGroup)
{
method.Group = resolvedName;
}
}
}
}
protected static string ResolveNameConflict(
Dictionary<string, string> exclusionDictionary,
string typeName,
string type,
string suffix)
{
string resolvedName = typeName;
var sb = new StringBuilder();
sb.AppendLine();
while (exclusionDictionary.ContainsKey(resolvedName))
{
sb.AppendLine(string.Format(CultureInfo.InvariantCulture,
Resources.NamespaceConflictReasonMessage,
resolvedName,
exclusionDictionary[resolvedName]));
resolvedName += suffix;
}
if (!string.Equals(resolvedName, typeName, StringComparison.OrdinalIgnoreCase))
{
sb.AppendLine(Resources.NamingConflictsSuggestion);
Logger.LogWarning(
string.Format(
CultureInfo.InvariantCulture,
Resources.EntityConflictTitleMessage,
type,
typeName,
resolvedName,
sb));
}
exclusionDictionary.Add(resolvedName, type);
return resolvedName;
}
private static IEnumerable<string> SplitNamespaceAndIgnoreLast(string nameSpace)
{
if (string.IsNullOrEmpty(nameSpace))
{
return Enumerable.Empty<string>();
}
var namespaceWords = nameSpace.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries);
if (namespaceWords.Length < 1)
{
return Enumerable.Empty<string>();
}
// else we do not need the last part of the namespace
return namespaceWords.Take(namespaceWords.Length - 1);
}
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static CodeNamer()
{
basicLaticCharacters = new Dictionary<char, string>();
basicLaticCharacters[(char)32] = "Space";
basicLaticCharacters[(char)33] = "ExclamationMark";
basicLaticCharacters[(char)34] = "QuotationMark";
basicLaticCharacters[(char)35] = "NumberSign";
basicLaticCharacters[(char)36] = "DollarSign";
basicLaticCharacters[(char)37] = "PercentSign";
basicLaticCharacters[(char)38] = "Ampersand";
basicLaticCharacters[(char)39] = "Apostrophe";
basicLaticCharacters[(char)40] = "LeftParenthesis";
basicLaticCharacters[(char)41] = "RightParenthesis";
basicLaticCharacters[(char)42] = "Asterisk";
basicLaticCharacters[(char)43] = "PlusSign";
basicLaticCharacters[(char)44] = "Comma";
basicLaticCharacters[(char)45] = "HyphenMinus";
basicLaticCharacters[(char)46] = "FullStop";
basicLaticCharacters[(char)47] = "Slash";
basicLaticCharacters[(char)48] = "Zero";
basicLaticCharacters[(char)49] = "One";
basicLaticCharacters[(char)50] = "Two";
basicLaticCharacters[(char)51] = "Three";
basicLaticCharacters[(char)52] = "Four";
basicLaticCharacters[(char)53] = "Five";
basicLaticCharacters[(char)54] = "Six";
basicLaticCharacters[(char)55] = "Seven";
basicLaticCharacters[(char)56] = "Eight";
basicLaticCharacters[(char)57] = "Nine";
basicLaticCharacters[(char)58] = "Colon";
basicLaticCharacters[(char)59] = "Semicolon";
basicLaticCharacters[(char)60] = "LessThanSign";
basicLaticCharacters[(char)61] = "EqualSign";
basicLaticCharacters[(char)62] = "GreaterThanSign";
basicLaticCharacters[(char)63] = "QuestionMark";
basicLaticCharacters[(char)64] = "AtSign";
basicLaticCharacters[(char)91] = "LeftSquareBracket";
basicLaticCharacters[(char)92] = "Backslash";
basicLaticCharacters[(char)93] = "RightSquareBracket";
basicLaticCharacters[(char)94] = "CircumflexAccent";
basicLaticCharacters[(char)96] = "GraveAccent";
basicLaticCharacters[(char)123] = "LeftCurlyBracket";
basicLaticCharacters[(char)124] = "VerticalBar";
basicLaticCharacters[(char)125] = "RightCurlyBracket";
basicLaticCharacters[(char)126] = "Tilde";
}
}
}
| |
using System;
using System.IO;
namespace CatLib._3rd.ICSharpCode.SharpZipLib.Core
{
/// <summary>
/// Provides simple <see cref="Stream"/>" utilities.
/// </summary>
public sealed class StreamUtils
{
/// <summary>
/// Read from a <see cref="Stream"/> ensuring all the required data is read.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <param name="buffer">The buffer to fill.</param>
/// <seealso cref="ReadFully(Stream,byte[],int,int)"/>
static public void ReadFully(Stream stream, byte[] buffer)
{
ReadFully(stream, buffer, 0, buffer.Length);
}
/// <summary>
/// Read from a <see cref="Stream"/>" ensuring all the required data is read.
/// </summary>
/// <param name="stream">The stream to read data from.</param>
/// <param name="buffer">The buffer to store data in.</param>
/// <param name="offset">The offset at which to begin storing data.</param>
/// <param name="count">The number of bytes of data to store.</param>
/// <exception cref="ArgumentNullException">Required parameter is null</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> and or <paramref name="count"/> are invalid.</exception>
/// <exception cref="EndOfStreamException">End of stream is encountered before all the data has been read.</exception>
static public void ReadFully(Stream stream, byte[] buffer, int offset, int count)
{
if (stream == null) {
throw new ArgumentNullException("stream");
}
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
// Offset can equal length when buffer and count are 0.
if ((offset < 0) || (offset > buffer.Length)) {
throw new ArgumentOutOfRangeException("offset");
}
if ((count < 0) || (offset + count > buffer.Length)) {
throw new ArgumentOutOfRangeException("count");
}
while (count > 0) {
int readCount = stream.Read(buffer, offset, count);
if (readCount <= 0) {
throw new EndOfStreamException();
}
offset += readCount;
count -= readCount;
}
}
/// <summary>
/// Copy the contents of one <see cref="Stream"/> to another.
/// </summary>
/// <param name="source">The stream to source data from.</param>
/// <param name="destination">The stream to write data to.</param>
/// <param name="buffer">The buffer to use during copying.</param>
static public void Copy(Stream source, Stream destination, byte[] buffer)
{
if (source == null) {
throw new ArgumentNullException("source");
}
if (destination == null) {
throw new ArgumentNullException("destination");
}
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
// Ensure a reasonable size of buffer is used without being prohibitive.
if (buffer.Length < 128) {
throw new ArgumentException("Buffer is too small", "buffer");
}
bool copying = true;
while (copying) {
int bytesRead = source.Read(buffer, 0, buffer.Length);
if (bytesRead > 0) {
destination.Write(buffer, 0, bytesRead);
} else {
destination.Flush();
copying = false;
}
}
}
/// <summary>
/// Copy the contents of one <see cref="Stream"/> to another.
/// </summary>
/// <param name="source">The stream to source data from.</param>
/// <param name="destination">The stream to write data to.</param>
/// <param name="buffer">The buffer to use during copying.</param>
/// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param>
/// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
/// <param name="sender">The source for this event.</param>
/// <param name="name">The name to use with the event.</param>
/// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
static public void Copy(Stream source, Stream destination,
byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name)
{
Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1);
}
/// <summary>
/// Copy the contents of one <see cref="Stream"/> to another.
/// </summary>
/// <param name="source">The stream to source data from.</param>
/// <param name="destination">The stream to write data to.</param>
/// <param name="buffer">The buffer to use during copying.</param>
/// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param>
/// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
/// <param name="sender">The source for this event.</param>
/// <param name="name">The name to use with the event.</param>
/// <param name="fixedTarget">A predetermined fixed target value to use with progress updates.
/// If the value is negative the target is calculated by looking at the stream.</param>
/// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
static public void Copy(Stream source, Stream destination,
byte[] buffer,
ProgressHandler progressHandler, TimeSpan updateInterval,
object sender, string name, long fixedTarget)
{
if (source == null) {
throw new ArgumentNullException("source");
}
if (destination == null) {
throw new ArgumentNullException("destination");
}
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
// Ensure a reasonable size of buffer is used without being prohibitive.
if (buffer.Length < 128) {
throw new ArgumentException("Buffer is too small", "buffer");
}
if (progressHandler == null) {
throw new ArgumentNullException("progressHandler");
}
bool copying = true;
DateTime marker = DateTime.Now;
long processed = 0;
long target = 0;
if (fixedTarget >= 0) {
target = fixedTarget;
} else if (source.CanSeek) {
target = source.Length - source.Position;
}
// Always fire 0% progress..
var args = new ProgressEventArgs(name, processed, target);
progressHandler(sender, args);
bool progressFired = true;
while (copying) {
int bytesRead = source.Read(buffer, 0, buffer.Length);
if (bytesRead > 0) {
processed += bytesRead;
progressFired = false;
destination.Write(buffer, 0, bytesRead);
} else {
destination.Flush();
copying = false;
}
if (DateTime.Now - marker > updateInterval) {
progressFired = true;
marker = DateTime.Now;
args = new ProgressEventArgs(name, processed, target);
progressHandler(sender, args);
copying = args.ContinueRunning;
}
}
if (!progressFired) {
args = new ProgressEventArgs(name, processed, target);
progressHandler(sender, args);
}
}
/// <summary>
/// Initialise an instance of <see cref="StreamUtils"></see>
/// </summary>
private StreamUtils()
{
// Do nothing.
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace LibGit2Sharp.Core
{
internal class HistoryRewriter
{
private readonly IRepository repo;
private readonly HashSet<Commit> targetedCommits;
private readonly Dictionary<GitObject, GitObject> objectMap = new Dictionary<GitObject, GitObject>();
private readonly Dictionary<Reference, Reference> refMap = new Dictionary<Reference, Reference>();
private readonly Queue<Action> rollbackActions = new Queue<Action>();
private readonly string backupRefsNamespace;
private readonly RewriteHistoryOptions options;
public HistoryRewriter(
IRepository repo,
IEnumerable<Commit> commitsToRewrite,
RewriteHistoryOptions options)
{
this.repo = repo;
this.options = options;
targetedCommits = new HashSet<Commit>(commitsToRewrite);
backupRefsNamespace = this.options.BackupRefsNamespace;
if (!backupRefsNamespace.EndsWith("/", StringComparison.Ordinal))
{
backupRefsNamespace += "/";
}
}
public void Execute()
{
var success = false;
try
{
// Find out which refs lead to at least one the commits
var refsToRewrite = repo.Refs.ReachableFrom(targetedCommits).ToList();
var filter = new CommitFilter
{
Since = refsToRewrite,
SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Topological
};
var commits = repo.Commits.QueryBy(filter);
foreach (var commit in commits)
{
RewriteCommit(commit);
}
// Ordering matters. In the case of `A -> B -> commit`, we need to make sure B is rewritten
// before A.
foreach (var reference in refsToRewrite.OrderBy(ReferenceDepth))
{
// TODO: Rewrite refs/notes/* properly
if (reference.CanonicalName.StartsWith("refs/notes/"))
{
continue;
}
RewriteReference(reference);
}
success = true;
if (options.OnSucceeding != null)
{
options.OnSucceeding();
}
}
catch (Exception ex)
{
try
{
if (!success && options.OnError != null)
{
options.OnError(ex);
}
}
finally
{
foreach (var action in rollbackActions)
{
action();
}
}
throw;
}
finally
{
rollbackActions.Clear();
}
}
private Reference RewriteReference(Reference reference)
{
// Has this target already been rewritten?
if (refMap.ContainsKey(reference))
{
return refMap[reference];
}
var sref = reference as SymbolicReference;
if (sref != null)
{
return RewriteReference(
sref, old => old.Target, RewriteReference,
(refs, old, target, logMessage) => refs.UpdateTarget(old, target, logMessage));
}
var dref = reference as DirectReference;
if (dref != null)
{
return RewriteReference(
dref, old => old.Target, RewriteTarget,
(refs, old, target, logMessage) => refs.UpdateTarget(old, target.Id, logMessage));
}
return reference;
}
private delegate Reference ReferenceUpdater<in TRef, in TTarget>(
ReferenceCollection refs, TRef origRef, TTarget origTarget, string logMessage)
where TRef : Reference
where TTarget : class;
private Reference RewriteReference<TRef, TTarget>(
TRef oldRef, Func<TRef, TTarget> selectTarget,
Func<TTarget, TTarget> rewriteTarget,
ReferenceUpdater<TRef, TTarget> updateTarget)
where TRef : Reference
where TTarget : class
{
var oldRefTarget = selectTarget(oldRef);
string newRefName = oldRef.CanonicalName;
if (oldRef.IsTag() && options.TagNameRewriter != null)
{
newRefName = Reference.TagPrefix +
options.TagNameRewriter(oldRef.CanonicalName.Substring(Reference.TagPrefix.Length),
false, oldRef.TargetIdentifier);
}
var newTarget = rewriteTarget(oldRefTarget);
if (oldRefTarget.Equals(newTarget) && oldRef.CanonicalName == newRefName)
{
// The reference isn't rewritten
return oldRef;
}
string backupName = backupRefsNamespace + oldRef.CanonicalName.Substring("refs/".Length);
if (repo.Refs.Resolve<Reference>(backupName) != null)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.InvariantCulture, "Can't back up reference '{0}' - '{1}' already exists",
oldRef.CanonicalName, backupName));
}
repo.Refs.Add(backupName, oldRef.TargetIdentifier, "filter-branch: backup");
rollbackActions.Enqueue(() => repo.Refs.Remove(backupName));
if (newTarget == null)
{
repo.Refs.Remove(oldRef);
rollbackActions.Enqueue(() => repo.Refs.Add(oldRef.CanonicalName, oldRef, "filter-branch: abort", true));
return refMap[oldRef] = null;
}
Reference newRef = updateTarget(repo.Refs, oldRef, newTarget, "filter-branch: rewrite");
rollbackActions.Enqueue(() => updateTarget(repo.Refs, oldRef, oldRefTarget, "filter-branch: abort"));
if (newRef.CanonicalName == newRefName)
{
return refMap[oldRef] = newRef;
}
var movedRef = repo.Refs.Rename(newRef, newRefName, false);
rollbackActions.Enqueue(() => repo.Refs.Rename(newRef, oldRef.CanonicalName, false));
return refMap[oldRef] = movedRef;
}
private void RewriteCommit(Commit commit)
{
var newHeader = CommitRewriteInfo.From(commit);
var newTree = commit.Tree;
// Find the new parents
var newParents = commit.Parents;
if (targetedCommits.Contains(commit))
{
// Get the new commit header
if (options.CommitHeaderRewriter != null)
{
newHeader = options.CommitHeaderRewriter(commit) ?? newHeader;
}
if (options.CommitTreeRewriter != null)
{
// Get the new commit tree
var newTreeDefinition = options.CommitTreeRewriter(commit);
newTree = repo.ObjectDatabase.CreateTree(newTreeDefinition);
}
// Retrieve new parents
if (options.CommitParentsRewriter != null)
{
newParents = options.CommitParentsRewriter(commit);
}
}
// Create the new commit
var mappedNewParents = newParents
.Select(oldParent =>
objectMap.ContainsKey(oldParent)
? objectMap[oldParent] as Commit
: oldParent)
.Where(newParent => newParent != null)
.ToList();
if (options.PruneEmptyCommits &&
TryPruneEmptyCommit(commit, mappedNewParents, newTree))
{
return;
}
var newCommit = repo.ObjectDatabase.CreateCommit(newHeader.Author,
newHeader.Committer,
newHeader.Message,
newTree,
mappedNewParents,
true);
// Record the rewrite
objectMap[commit] = newCommit;
}
private bool TryPruneEmptyCommit(Commit commit, IList<Commit> mappedNewParents, Tree newTree)
{
var parent = mappedNewParents.Count > 0 ? mappedNewParents[0] : null;
if (parent == null)
{
if (newTree.Count == 0)
{
objectMap[commit] = null;
return true;
}
}
else if (parent.Tree == newTree)
{
objectMap[commit] = parent;
return true;
}
return false;
}
private GitObject RewriteTarget(GitObject oldTarget)
{
// Has this target already been rewritten?
if (objectMap.ContainsKey(oldTarget))
{
return objectMap[oldTarget];
}
Debug.Assert((oldTarget as Commit) == null);
var annotation = oldTarget as TagAnnotation;
if (annotation == null)
{
//TODO: Probably a Tree or a Blob. This is not covered by any test
return oldTarget;
}
// Recursively rewrite annotations if necessary
var newTarget = RewriteTarget(annotation.Target);
string newName = annotation.Name;
if (options.TagNameRewriter != null)
{
newName = options.TagNameRewriter(annotation.Name, true, annotation.Target.Sha);
}
var newAnnotation = repo.ObjectDatabase.CreateTagAnnotation(newName, newTarget, annotation.Tagger,
annotation.Message);
objectMap[annotation] = newAnnotation;
return newAnnotation;
}
private int ReferenceDepth(Reference reference)
{
var dref = reference as DirectReference;
return dref == null
? 1 + ReferenceDepth(((SymbolicReference)reference).Target)
: 1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Razor.Language;
using Newtonsoft.Json;
namespace Microsoft.CodeAnalysis.Razor.Serialization
{
internal class TagHelperDescriptorJsonConverter : JsonConverter
{
public static readonly TagHelperDescriptorJsonConverter Instance = new TagHelperDescriptorJsonConverter();
public override bool CanConvert(Type objectType)
{
return typeof(TagHelperDescriptor).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.StartObject)
{
return null;
}
// Required tokens (order matters)
var descriptorKind = reader.ReadNextStringProperty(nameof(TagHelperDescriptor.Kind));
var typeName = reader.ReadNextStringProperty(nameof(TagHelperDescriptor.Name));
var assemblyName = reader.ReadNextStringProperty(nameof(TagHelperDescriptor.AssemblyName));
var builder = TagHelperDescriptorBuilder.Create(descriptorKind, typeName, assemblyName);
reader.ReadProperties(propertyName =>
{
switch (propertyName)
{
case nameof(TagHelperDescriptor.Documentation):
if (reader.Read())
{
var documentation = (string)reader.Value;
builder.Documentation = documentation;
}
break;
case nameof(TagHelperDescriptor.TagOutputHint):
if (reader.Read())
{
var tagOutputHint = (string)reader.Value;
builder.TagOutputHint = tagOutputHint;
}
break;
case nameof(TagHelperDescriptor.CaseSensitive):
if (reader.Read())
{
var caseSensitive = (bool)reader.Value;
builder.CaseSensitive = caseSensitive;
}
break;
case nameof(TagHelperDescriptor.TagMatchingRules):
ReadTagMatchingRules(reader, builder);
break;
case nameof(TagHelperDescriptor.BoundAttributes):
ReadBoundAttributes(reader, builder);
break;
case nameof(TagHelperDescriptor.AllowedChildTags):
ReadAllowedChildTags(reader, builder);
break;
case nameof(TagHelperDescriptor.Diagnostics):
ReadDiagnostics(reader, builder.Diagnostics);
break;
case nameof(TagHelperDescriptor.Metadata):
ReadMetadata(reader, builder.Metadata);
break;
}
});
return builder.Build();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var tagHelper = (TagHelperDescriptor)value;
writer.WriteStartObject();
writer.WritePropertyName(nameof(TagHelperDescriptor.Kind));
writer.WriteValue(tagHelper.Kind);
writer.WritePropertyName(nameof(TagHelperDescriptor.Name));
writer.WriteValue(tagHelper.Name);
writer.WritePropertyName(nameof(TagHelperDescriptor.AssemblyName));
writer.WriteValue(tagHelper.AssemblyName);
if (tagHelper.Documentation != null)
{
writer.WritePropertyName(nameof(TagHelperDescriptor.Documentation));
writer.WriteValue(tagHelper.Documentation);
}
if (tagHelper.TagOutputHint != null)
{
writer.WritePropertyName(nameof(TagHelperDescriptor.TagOutputHint));
writer.WriteValue(tagHelper.TagOutputHint);
}
writer.WritePropertyName(nameof(TagHelperDescriptor.CaseSensitive));
writer.WriteValue(tagHelper.CaseSensitive);
writer.WritePropertyName(nameof(TagHelperDescriptor.TagMatchingRules));
writer.WriteStartArray();
foreach (var ruleDescriptor in tagHelper.TagMatchingRules)
{
WriteTagMatchingRule(writer, ruleDescriptor, serializer);
}
writer.WriteEndArray();
if (tagHelper.BoundAttributes != null && tagHelper.BoundAttributes.Count > 0)
{
writer.WritePropertyName(nameof(TagHelperDescriptor.BoundAttributes));
writer.WriteStartArray();
foreach (var boundAttribute in tagHelper.BoundAttributes)
{
WriteBoundAttribute(writer, boundAttribute, serializer);
}
writer.WriteEndArray();
}
if (tagHelper.AllowedChildTags != null && tagHelper.AllowedChildTags.Count > 0)
{
writer.WritePropertyName(nameof(TagHelperDescriptor.AllowedChildTags));
writer.WriteStartArray();
foreach (var allowedChildTag in tagHelper.AllowedChildTags)
{
WriteAllowedChildTags(writer, allowedChildTag, serializer);
}
writer.WriteEndArray();
}
if (tagHelper.Diagnostics != null && tagHelper.Diagnostics.Count > 0)
{
writer.WritePropertyName(nameof(TagHelperDescriptor.Diagnostics));
serializer.Serialize(writer, tagHelper.Diagnostics);
}
writer.WritePropertyName(nameof(TagHelperDescriptor.Metadata));
WriteMetadata(writer, tagHelper.Metadata);
writer.WriteEndObject();
}
private static void WriteAllowedChildTags(JsonWriter writer, AllowedChildTagDescriptor allowedChildTag, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(AllowedChildTagDescriptor.Name));
writer.WriteValue(allowedChildTag.Name);
writer.WritePropertyName(nameof(AllowedChildTagDescriptor.DisplayName));
writer.WriteValue(allowedChildTag.DisplayName);
writer.WritePropertyName(nameof(AllowedChildTagDescriptor.Diagnostics));
serializer.Serialize(writer, allowedChildTag.Diagnostics);
writer.WriteEndObject();
}
private static void WriteBoundAttribute(JsonWriter writer, BoundAttributeDescriptor boundAttribute, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(BoundAttributeDescriptor.Kind));
writer.WriteValue(boundAttribute.Kind);
writer.WritePropertyName(nameof(BoundAttributeDescriptor.Name));
writer.WriteValue(boundAttribute.Name);
writer.WritePropertyName(nameof(BoundAttributeDescriptor.TypeName));
writer.WriteValue(boundAttribute.TypeName);
if (boundAttribute.IsEnum)
{
writer.WritePropertyName(nameof(BoundAttributeDescriptor.IsEnum));
writer.WriteValue(boundAttribute.IsEnum);
}
if (boundAttribute.IndexerNamePrefix != null)
{
writer.WritePropertyName(nameof(BoundAttributeDescriptor.IndexerNamePrefix));
writer.WriteValue(boundAttribute.IndexerNamePrefix);
}
if (boundAttribute.IsEditorRequired)
{
writer.WritePropertyName(nameof(BoundAttributeDescriptor.IsEditorRequired));
writer.WriteValue(boundAttribute.IsEditorRequired);
}
if (boundAttribute.IndexerTypeName != null)
{
writer.WritePropertyName(nameof(BoundAttributeDescriptor.IndexerTypeName));
writer.WriteValue(boundAttribute.IndexerTypeName);
}
if (boundAttribute.Documentation != null)
{
writer.WritePropertyName(nameof(BoundAttributeDescriptor.Documentation));
writer.WriteValue(boundAttribute.Documentation);
}
if (boundAttribute.Diagnostics != null && boundAttribute.Diagnostics.Count > 0)
{
writer.WritePropertyName(nameof(BoundAttributeDescriptor.Diagnostics));
serializer.Serialize(writer, boundAttribute.Diagnostics);
}
writer.WritePropertyName(nameof(BoundAttributeDescriptor.Metadata));
WriteMetadata(writer, boundAttribute.Metadata);
if (boundAttribute.BoundAttributeParameters != null && boundAttribute.BoundAttributeParameters.Count > 0)
{
writer.WritePropertyName(nameof(BoundAttributeDescriptor.BoundAttributeParameters));
writer.WriteStartArray();
foreach (var boundAttributeParameter in boundAttribute.BoundAttributeParameters)
{
WriteBoundAttributeParameter(writer, boundAttributeParameter, serializer);
}
writer.WriteEndArray();
}
writer.WriteEndObject();
}
private static void WriteBoundAttributeParameter(JsonWriter writer, BoundAttributeParameterDescriptor boundAttributeParameter, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(BoundAttributeParameterDescriptor.Name));
writer.WriteValue(boundAttributeParameter.Name);
writer.WritePropertyName(nameof(BoundAttributeParameterDescriptor.TypeName));
writer.WriteValue(boundAttributeParameter.TypeName);
if (boundAttributeParameter.IsEnum != default)
{
writer.WritePropertyName(nameof(BoundAttributeParameterDescriptor.IsEnum));
writer.WriteValue(boundAttributeParameter.IsEnum);
}
if (boundAttributeParameter.Documentation != null)
{
writer.WritePropertyName(nameof(BoundAttributeParameterDescriptor.Documentation));
writer.WriteValue(boundAttributeParameter.Documentation);
}
if (boundAttributeParameter.Diagnostics != null && boundAttributeParameter.Diagnostics.Count > 0)
{
writer.WritePropertyName(nameof(BoundAttributeParameterDescriptor.Diagnostics));
serializer.Serialize(writer, boundAttributeParameter.Diagnostics);
}
writer.WritePropertyName(nameof(BoundAttributeParameterDescriptor.Metadata));
WriteMetadata(writer, boundAttributeParameter.Metadata);
writer.WriteEndObject();
}
private static void WriteMetadata(JsonWriter writer, IReadOnlyDictionary<string, string> metadata)
{
writer.WriteStartObject();
foreach (var kvp in metadata)
{
writer.WritePropertyName(kvp.Key);
writer.WriteValue(kvp.Value);
}
writer.WriteEndObject();
}
private static void WriteTagMatchingRule(JsonWriter writer, TagMatchingRuleDescriptor ruleDescriptor, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(TagMatchingRuleDescriptor.TagName));
writer.WriteValue(ruleDescriptor.TagName);
if (ruleDescriptor.ParentTag != null)
{
writer.WritePropertyName(nameof(TagMatchingRuleDescriptor.ParentTag));
writer.WriteValue(ruleDescriptor.ParentTag);
}
if (ruleDescriptor.TagStructure != default)
{
writer.WritePropertyName(nameof(TagMatchingRuleDescriptor.TagStructure));
writer.WriteValue(ruleDescriptor.TagStructure);
}
if (ruleDescriptor.Attributes != null && ruleDescriptor.Attributes.Count > 0)
{
writer.WritePropertyName(nameof(TagMatchingRuleDescriptor.Attributes));
writer.WriteStartArray();
foreach (var requiredAttribute in ruleDescriptor.Attributes)
{
WriteRequiredAttribute(writer, requiredAttribute, serializer);
}
writer.WriteEndArray();
}
if (ruleDescriptor.Diagnostics != null && ruleDescriptor.Diagnostics.Count > 0)
{
writer.WritePropertyName(nameof(TagMatchingRuleDescriptor.Diagnostics));
serializer.Serialize(writer, ruleDescriptor.Diagnostics);
}
writer.WriteEndObject();
}
private static void WriteRequiredAttribute(JsonWriter writer, RequiredAttributeDescriptor requiredAttribute, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(RequiredAttributeDescriptor.Name));
writer.WriteValue(requiredAttribute.Name);
if (requiredAttribute.NameComparison != default)
{
writer.WritePropertyName(nameof(RequiredAttributeDescriptor.NameComparison));
writer.WriteValue(requiredAttribute.NameComparison);
}
if (requiredAttribute.Value != null)
{
writer.WritePropertyName(nameof(RequiredAttributeDescriptor.Value));
writer.WriteValue(requiredAttribute.Value);
}
if (requiredAttribute.ValueComparison != default)
{
writer.WritePropertyName(nameof(RequiredAttributeDescriptor.ValueComparison));
writer.WriteValue(requiredAttribute.ValueComparison);
}
if (requiredAttribute.Diagnostics != null && requiredAttribute.Diagnostics.Count > 0)
{
writer.WritePropertyName(nameof(RequiredAttributeDescriptor.Diagnostics));
serializer.Serialize(writer, requiredAttribute.Diagnostics);
}
if (requiredAttribute.Metadata != null && requiredAttribute.Metadata.Count > 0)
{
writer.WritePropertyName(nameof(RequiredAttributeDescriptor.Metadata));
WriteMetadata(writer, requiredAttribute.Metadata);
}
writer.WriteEndObject();
}
private static void ReadBoundAttributes(JsonReader reader, TagHelperDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartArray)
{
return;
}
do
{
ReadBoundAttribute(reader, builder);
} while (reader.TokenType != JsonToken.EndArray);
}
private static void ReadBoundAttribute(JsonReader reader, TagHelperDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartObject)
{
return;
}
builder.BindAttribute(attribute =>
{
reader.ReadProperties(propertyName =>
{
switch (propertyName)
{
case nameof(BoundAttributeDescriptor.Name):
if (reader.Read())
{
var name = (string)reader.Value;
attribute.Name = name;
}
break;
case nameof(BoundAttributeDescriptor.TypeName):
if (reader.Read())
{
var typeName = (string)reader.Value;
attribute.TypeName = typeName;
}
break;
case nameof(BoundAttributeDescriptor.Documentation):
if (reader.Read())
{
var documentation = (string)reader.Value;
attribute.Documentation = documentation;
}
break;
case nameof(BoundAttributeDescriptor.IndexerNamePrefix):
if (reader.Read())
{
var indexerNamePrefix = (string)reader.Value;
if (indexerNamePrefix != null)
{
attribute.IsDictionary = true;
attribute.IndexerAttributeNamePrefix = indexerNamePrefix;
}
}
break;
case nameof(BoundAttributeDescriptor.IndexerTypeName):
if (reader.Read())
{
var indexerTypeName = (string)reader.Value;
if (indexerTypeName != null)
{
attribute.IsDictionary = true;
attribute.IndexerValueTypeName = indexerTypeName;
}
}
break;
case nameof(BoundAttributeDescriptor.IsEnum):
if (reader.Read())
{
var isEnum = (bool)reader.Value;
attribute.IsEnum = isEnum;
}
break;
case nameof(BoundAttributeDescriptor.IsEditorRequired):
if (reader.Read())
{
var value = (bool)reader.Value;
attribute.IsEditorRequired = value;
}
break;
case nameof(BoundAttributeDescriptor.BoundAttributeParameters):
ReadBoundAttributeParameters(reader, attribute);
break;
case nameof(BoundAttributeDescriptor.Diagnostics):
ReadDiagnostics(reader, attribute.Diagnostics);
break;
case nameof(BoundAttributeDescriptor.Metadata):
ReadMetadata(reader, attribute.Metadata);
break;
}
});
});
}
private static void ReadBoundAttributeParameters(JsonReader reader, BoundAttributeDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartArray)
{
return;
}
do
{
ReadBoundAttributeParameter(reader, builder);
} while (reader.TokenType != JsonToken.EndArray);
}
private static void ReadBoundAttributeParameter(JsonReader reader, BoundAttributeDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartObject)
{
return;
}
builder.BindAttributeParameter(parameter =>
{
reader.ReadProperties(propertyName =>
{
switch (propertyName)
{
case nameof(BoundAttributeParameterDescriptor.Name):
if (reader.Read())
{
var name = (string)reader.Value;
parameter.Name = name;
}
break;
case nameof(BoundAttributeParameterDescriptor.TypeName):
if (reader.Read())
{
var typeName = (string)reader.Value;
parameter.TypeName = typeName;
}
break;
case nameof(BoundAttributeParameterDescriptor.IsEnum):
if (reader.Read())
{
var isEnum = (bool)reader.Value;
parameter.IsEnum = isEnum;
}
break;
case nameof(BoundAttributeParameterDescriptor.Documentation):
if (reader.Read())
{
var documentation = (string)reader.Value;
parameter.Documentation = documentation;
}
break;
case nameof(BoundAttributeParameterDescriptor.Metadata):
ReadMetadata(reader, parameter.Metadata);
break;
case nameof(BoundAttributeParameterDescriptor.Diagnostics):
ReadDiagnostics(reader, parameter.Diagnostics);
break;
}
});
});
}
private static void ReadTagMatchingRules(JsonReader reader, TagHelperDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartArray)
{
return;
}
do
{
ReadTagMatchingRule(reader, builder);
} while (reader.TokenType != JsonToken.EndArray);
}
private static void ReadTagMatchingRule(JsonReader reader, TagHelperDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartObject)
{
return;
}
builder.TagMatchingRule(rule =>
{
reader.ReadProperties(propertyName =>
{
switch (propertyName)
{
case nameof(TagMatchingRuleDescriptor.TagName):
if (reader.Read())
{
var tagName = (string)reader.Value;
rule.TagName = tagName;
}
break;
case nameof(TagMatchingRuleDescriptor.ParentTag):
if (reader.Read())
{
var parentTag = (string)reader.Value;
rule.ParentTag = parentTag;
}
break;
case nameof(TagMatchingRuleDescriptor.TagStructure):
rule.TagStructure = (TagStructure)reader.ReadAsInt32();
break;
case nameof(TagMatchingRuleDescriptor.Attributes):
ReadRequiredAttributeValues(reader, rule);
break;
case nameof(TagMatchingRuleDescriptor.Diagnostics):
ReadDiagnostics(reader, rule.Diagnostics);
break;
}
});
});
}
private static void ReadRequiredAttributeValues(JsonReader reader, TagMatchingRuleDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartArray)
{
return;
}
do
{
ReadRequiredAttribute(reader, builder);
} while (reader.TokenType != JsonToken.EndArray);
}
private static void ReadRequiredAttribute(JsonReader reader, TagMatchingRuleDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartObject)
{
return;
}
builder.Attribute(attribute =>
{
reader.ReadProperties(propertyName =>
{
switch (propertyName)
{
case nameof(RequiredAttributeDescriptor.Name):
if (reader.Read())
{
var name = (string)reader.Value;
attribute.Name = name;
}
break;
case nameof(RequiredAttributeDescriptor.NameComparison):
var nameComparison = (RequiredAttributeDescriptor.NameComparisonMode)reader.ReadAsInt32();
attribute.NameComparisonMode = nameComparison;
break;
case nameof(RequiredAttributeDescriptor.Value):
if (reader.Read())
{
var value = (string)reader.Value;
attribute.Value = value;
}
break;
case nameof(RequiredAttributeDescriptor.ValueComparison):
var valueComparison = (RequiredAttributeDescriptor.ValueComparisonMode)reader.ReadAsInt32();
attribute.ValueComparisonMode = valueComparison;
break;
case nameof(RequiredAttributeDescriptor.Diagnostics):
ReadDiagnostics(reader, attribute.Diagnostics);
break;
case nameof(RequiredAttributeDescriptor.Metadata):
ReadMetadata(reader, attribute.Metadata);
break;
}
});
});
}
private static void ReadAllowedChildTags(JsonReader reader, TagHelperDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartArray)
{
return;
}
do
{
ReadAllowedChildTag(reader, builder);
} while (reader.TokenType != JsonToken.EndArray);
}
private static void ReadAllowedChildTag(JsonReader reader, TagHelperDescriptorBuilder builder)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartObject)
{
return;
}
builder.AllowChildTag(childTag =>
{
reader.ReadProperties(propertyName =>
{
switch (propertyName)
{
case nameof(AllowedChildTagDescriptor.Name):
if (reader.Read())
{
var name = (string)reader.Value;
childTag.Name = name;
}
break;
case nameof(AllowedChildTagDescriptor.DisplayName):
if (reader.Read())
{
var displayName = (string)reader.Value;
childTag.DisplayName = displayName;
}
break;
case nameof(AllowedChildTagDescriptor.Diagnostics):
ReadDiagnostics(reader, childTag.Diagnostics);
break;
}
});
});
}
private static void ReadMetadata(JsonReader reader, IDictionary<string, string> metadata)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartObject)
{
return;
}
reader.ReadProperties(propertyName =>
{
if (reader.Read())
{
var value = (string)reader.Value;
metadata[propertyName] = value;
}
});
}
private static void ReadDiagnostics(JsonReader reader, RazorDiagnosticCollection diagnostics)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartArray)
{
return;
}
do
{
ReadDiagnostic(reader, diagnostics);
} while (reader.TokenType != JsonToken.EndArray);
}
private static void ReadDiagnostic(JsonReader reader, RazorDiagnosticCollection diagnostics)
{
if (!reader.Read())
{
return;
}
if (reader.TokenType != JsonToken.StartObject)
{
return;
}
string id = default;
int severity = default;
string message = default;
SourceSpan sourceSpan = default;
reader.ReadProperties(propertyName =>
{
switch (propertyName)
{
case nameof(RazorDiagnostic.Id):
if (reader.Read())
{
id = (string)reader.Value;
}
break;
case nameof(RazorDiagnostic.Severity):
severity = reader.ReadAsInt32().Value;
break;
case "Message":
if (reader.Read())
{
message = (string)reader.Value;
}
break;
case nameof(RazorDiagnostic.Span):
sourceSpan = ReadSourceSpan(reader);
break;
}
});
var descriptor = new RazorDiagnosticDescriptor(id, () => message, (RazorDiagnosticSeverity)severity);
var diagnostic = RazorDiagnostic.Create(descriptor, sourceSpan);
diagnostics.Add(diagnostic);
}
private static SourceSpan ReadSourceSpan(JsonReader reader)
{
if (!reader.Read())
{
return SourceSpan.Undefined;
}
if (reader.TokenType != JsonToken.StartObject)
{
return SourceSpan.Undefined;
}
string filePath = default;
int absoluteIndex = default;
int lineIndex = default;
int characterIndex = default;
int length = default;
reader.ReadProperties(propertyName =>
{
switch (propertyName)
{
case nameof(SourceSpan.FilePath):
if (reader.Read())
{
filePath = (string)reader.Value;
}
break;
case nameof(SourceSpan.AbsoluteIndex):
absoluteIndex = reader.ReadAsInt32().Value;
break;
case nameof(SourceSpan.LineIndex):
lineIndex = reader.ReadAsInt32().Value;
break;
case nameof(SourceSpan.CharacterIndex):
characterIndex = reader.ReadAsInt32().Value;
break;
case nameof(SourceSpan.Length):
length = reader.ReadAsInt32().Value;
break;
}
});
var sourceSpan = new SourceSpan(filePath, absoluteIndex, lineIndex, characterIndex, length);
return sourceSpan;
}
}
}
| |
// WARNING
//
// This file has been generated automatically by Visual Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace vitaadmin
{
[Register ("VC_Calendar")]
partial class VC_Calendar
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIActivityIndicatorView AI_Busy { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIButton B_Back { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIButton B_ExcNewShift { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIButton B_ExcSave { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIButton B_NewException { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_Advanced { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_Basic { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_CalendarEntryFor { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_Close { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_DeleteShift { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_ExcSite { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_Open { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_ShiftDetails { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_Shifts { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_SiteIsOpen { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel L_UsersOnShift { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UISwitch SW_ExcIsOpen { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField TB_DateForCalendarEntry { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField TB_ExcAdvShift { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField TB_ExcBasicShift { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField TB_ExcCloseShift { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField TB_ExcDate { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField TB_ExcOpenShift { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITableView TV_Exceptions { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITableView TV_ExcShifts { get; set; }
void ReleaseDesignerOutlets ()
{
if (AI_Busy != null) {
AI_Busy.Dispose ();
AI_Busy = null;
}
if (B_Back != null) {
B_Back.Dispose ();
B_Back = null;
}
if (B_ExcNewShift != null) {
B_ExcNewShift.Dispose ();
B_ExcNewShift = null;
}
if (B_ExcSave != null) {
B_ExcSave.Dispose ();
B_ExcSave = null;
}
if (B_NewException != null) {
B_NewException.Dispose ();
B_NewException = null;
}
if (L_Advanced != null) {
L_Advanced.Dispose ();
L_Advanced = null;
}
if (L_Basic != null) {
L_Basic.Dispose ();
L_Basic = null;
}
if (L_CalendarEntryFor != null) {
L_CalendarEntryFor.Dispose ();
L_CalendarEntryFor = null;
}
if (L_Close != null) {
L_Close.Dispose ();
L_Close = null;
}
if (L_DeleteShift != null) {
L_DeleteShift.Dispose ();
L_DeleteShift = null;
}
if (L_ExcSite != null) {
L_ExcSite.Dispose ();
L_ExcSite = null;
}
if (L_Open != null) {
L_Open.Dispose ();
L_Open = null;
}
if (L_ShiftDetails != null) {
L_ShiftDetails.Dispose ();
L_ShiftDetails = null;
}
if (L_Shifts != null) {
L_Shifts.Dispose ();
L_Shifts = null;
}
if (L_SiteIsOpen != null) {
L_SiteIsOpen.Dispose ();
L_SiteIsOpen = null;
}
if (L_UsersOnShift != null) {
L_UsersOnShift.Dispose ();
L_UsersOnShift = null;
}
if (SW_ExcIsOpen != null) {
SW_ExcIsOpen.Dispose ();
SW_ExcIsOpen = null;
}
if (TB_DateForCalendarEntry != null) {
TB_DateForCalendarEntry.Dispose ();
TB_DateForCalendarEntry = null;
}
if (TB_ExcAdvShift != null) {
TB_ExcAdvShift.Dispose ();
TB_ExcAdvShift = null;
}
if (TB_ExcBasicShift != null) {
TB_ExcBasicShift.Dispose ();
TB_ExcBasicShift = null;
}
if (TB_ExcCloseShift != null) {
TB_ExcCloseShift.Dispose ();
TB_ExcCloseShift = null;
}
if (TB_ExcDate != null) {
TB_ExcDate.Dispose ();
TB_ExcDate = null;
}
if (TB_ExcOpenShift != null) {
TB_ExcOpenShift.Dispose ();
TB_ExcOpenShift = null;
}
if (TV_Exceptions != null) {
TV_Exceptions.Dispose ();
TV_Exceptions = null;
}
if (TV_ExcShifts != null) {
TV_ExcShifts.Dispose ();
TV_ExcShifts = null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Pathoschild.Stardew.Automate.Framework.Models;
using Pathoschild.Stardew.Common;
using Pathoschild.Stardew.Common.Integrations.GenericModConfigMenu;
using StardewModdingAPI;
namespace Pathoschild.Stardew.Automate.Framework
{
/// <summary>Registers the mod configuration with Generic Mod Config Menu.</summary>
internal class GenericModConfigMenuIntegrationForAutomate
{
/*********
** Fields
*********/
/// <summary>The Generic Mod Config Menu integration.</summary>
private readonly GenericModConfigMenuIntegration<ModConfig> ConfigMenu;
/// <summary>The internal mod data.</summary>
private readonly DataModel Data;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
/// <param name="manifest">The mod manifest.</param>
/// <param name="data">The internal mod data.</param>
/// <param name="getConfig">Get the current config model.</param>
/// <param name="reset">Reset the config model to the default values.</param>
/// <param name="saveAndApply">Save and apply the current config model.</param>
public GenericModConfigMenuIntegrationForAutomate(IModRegistry modRegistry, IMonitor monitor, IManifest manifest, DataModel data, Func<ModConfig> getConfig, Action reset, Action saveAndApply)
{
this.ConfigMenu = new GenericModConfigMenuIntegration<ModConfig>(modRegistry, monitor, manifest, getConfig, reset, saveAndApply);
this.Data = data;
}
/// <summary>Register the config menu if available.</summary>
public void Register()
{
// get config menu
var menu = this.ConfigMenu;
if (!menu.IsLoaded)
return;
menu.Register();
// main options
menu
.AddSectionTitle(I18n.Config_Title_MainOptions)
.AddCheckbox(
name: I18n.Config_JunimoHutsOutputGems_Name,
tooltip: I18n.Config_JunimoHutsOutputGems_Desc,
get: config => config.PullGemstonesFromJunimoHuts,
set: (config, value) => config.PullGemstonesFromJunimoHuts = value
)
.AddNumberField(
name: I18n.Config_AutomationInterval_Name,
tooltip: I18n.Config_AutomationInterval_Desc,
get: config => config.AutomationInterval,
set: (config, value) => config.AutomationInterval = value,
min: 1,
max: 600
)
.AddKeyBinding(
name: I18n.Config_ToggleOverlayKey_Name,
tooltip: I18n.Config_ToggleOverlayKey_Desc,
get: config => config.Controls.ToggleOverlay,
set: (config, value) => config.Controls.ToggleOverlay = value
);
// mod compatibility
menu
.AddSectionTitle(I18n.Config_Title_ModCompatibility)
.AddCheckbox(
name: I18n.Config_BetterJunimos_Name,
tooltip: I18n.Config_BetterJunimos_Desc,
get: config => config.ModCompatibility.BetterJunimos,
set: (config, value) => config.ModCompatibility.BetterJunimos = value
)
.AddCheckbox(
name: I18n.Config_WarnForMissingBridgeMod_Name,
tooltip: I18n.Config_WarnForMissingBridgeMod_Desc,
get: config => config.ModCompatibility.WarnForMissingBridgeMod,
set: (config, value) => config.ModCompatibility.WarnForMissingBridgeMod = value
);
// connectors
menu.AddSectionTitle(I18n.Config_Title_Connectors);
foreach (DataModelFloor entry in this.Data.FloorNames.Values)
{
int itemId = entry.ItemId;
menu.AddCheckbox(
name: () => GameI18n.GetObjectName(itemId),
tooltip: () => I18n.Config_Connector_Desc(itemName: GameI18n.GetObjectName(itemId)),
get: config => this.HasConnector(config, entry.Name),
set: (config, value) => this.SetConnector(config, entry.Name, value)
);
}
menu.AddTextbox(
name: I18n.Config_CustomConnectors_Name,
tooltip: I18n.Config_CustomConnectors_Desc,
get: config => string.Join(", ", config.ConnectorNames.Where(this.IsCustomConnector)),
set: (config, value) => this.SetCustomConnectors(config, value.Split(',').Select(p => p.Trim()))
);
// machine overrides
menu.AddSectionTitle(I18n.Config_Title_MachineOverrides);
if (this.Data != null)
{
foreach (var entry in this.Data.DefaultMachineOverrides)
{
menu.AddCheckbox(
name: () => this.GetTranslatedMachineName(entry.Key),
tooltip: () => I18n.Config_Override_Desc(machineName: this.GetTranslatedMachineName(entry.Key)),
get: config => this.IsMachineEnabled(config, entry.Key),
set: (config, value) => this.SetCustomOverride(config, entry.Key, value)
);
}
}
menu.AddParagraph(I18n.Config_CustomOverridesNote);
}
/*********
** Private methods
*********/
/****
** Connectors
****/
/// <summary>Get whether the given item name isn't one of the connectors listed in <see cref="DataModel.FloorNames"/>.</summary>
/// <param name="name">The item name.</param>
private bool IsCustomConnector(string name)
{
foreach (DataModelFloor floor in this.Data.FloorNames.Values)
{
if (string.Equals(floor.Name, name, StringComparison.OrdinalIgnoreCase))
return false;
}
return true;
}
/// <summary>Get whether the given item name is enabled as a connector.</summary>
/// <param name="config">The mod configuration to check.</param>
/// <param name="name">The item name.</param>
private bool HasConnector(ModConfig config, string name)
{
return config.ConnectorNames.Contains(name);
}
/// <summary>Set whether the given item name is enabled as a connector.</summary>
/// <param name="config">The mod configuration to check.</param>
/// <param name="name">The item name.</param>
/// <param name="enable">Whether the item should be enabled; else it should be disabled.</param>
private void SetConnector(ModConfig config, string name, bool enable)
{
if (enable)
config.ConnectorNames.Add(name);
else
config.ConnectorNames.Remove(name);
}
/// <summary>Set whether the given item name is enabled as a connector.</summary>
/// <param name="config">The mod configuration to check.</param>
/// <param name="rawNames">The raw connector names to set.</param>
private void SetCustomConnectors(ModConfig config, IEnumerable<string> rawNames)
{
var names = new HashSet<string>(rawNames);
foreach (string name in config.ConnectorNames)
{
if (!names.Contains(name) && this.IsCustomConnector(name))
config.ConnectorNames.Remove(name);
}
foreach (string name in names)
{
if (!string.IsNullOrWhiteSpace(name))
config.ConnectorNames.Add(name);
}
}
/****
** Machine overrides
****/
/// <summary>Get the translated name for a machine.</summary>
/// <param name="key">The unique machine key.</param>
public string GetTranslatedMachineName(string key)
{
return I18n.GetByKey($"config.override.{key}-name").Default(key);
}
/// <summary>Get the custom override for a mod, if any.</summary>
/// <param name="config">The mod configuration.</param>
/// <param name="name">The machine name.</param>
public ModConfigMachine GetCustomOverride(ModConfig config, string name)
{
return config.MachineOverrides.TryGetValue(name, out ModConfigMachine @override) && @override != null
? @override
: null;
}
/// <summary>Get the default override for a mod, if any.</summary>
/// <param name="config">The mod configuration.</param>
/// <param name="name">The machine name.</param>
public ModConfigMachine GetDefaultOverride(string name)
{
if (this.Data != null)
{
return this.Data.DefaultMachineOverrides.TryGetValue(name, out ModConfigMachine @override) && @override != null
? @override
: null;
}
return null;
}
/// <summary>Get whether a machine is currently enabled.</summary>
/// <param name="config">The mod configuration.</param>
/// <param name="name">The machine name.</param>
public bool IsMachineEnabled(ModConfig config, string name)
{
return
this.GetCustomOverride(config, name)?.Enabled
?? this.GetDefaultOverride(name)?.Enabled
?? true;
}
/// <summary>Get the custom override for a mod, if any.</summary>
/// <param name="config">The mod configuration.</param>
/// <param name="name">The machine name.</param>
public void SetCustomOverride(ModConfig config, string name, bool enabled)
{
ModConfigMachine options = this.GetCustomOverride(config, name) ?? new ModConfigMachine { Enabled = enabled };
ModConfigMachine defaults = this.GetDefaultOverride(name);
bool isDefault = defaults != null
? options.Enabled == defaults.Enabled && options.Priority == defaults.Priority
: !options.GetCustomSettings().Any();
if (isDefault)
config.MachineOverrides.Remove(name);
else
config.MachineOverrides[name] = options;
}
}
}
| |
using System;
using System.Collections.Generic;
public class ArrayLastIndexOf4
{
private const int c_MIN_SIZE = 64;
private const int c_MAX_SIZE = 1024;
private const int c_MIN_STRLEN = 1;
private const int c_MAX_STRLEN = 1024;
public static int Main()
{
ArrayLastIndexOf4 ac = new ArrayLastIndexOf4();
TestLibrary.TestFramework.BeginTestCase("Array.LastInexOf(T[] array, T value)");
if (ac.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
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 = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
TestLibrary.TestFramework.LogInformation("");
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
retVal = NegTest9() && retVal;
retVal = NegTest10() && retVal;
return retVal;
}
public bool PosTest1() { return PosIndexOf<Int64>(1, TestLibrary.Generator.GetInt64(-55), TestLibrary.Generator.GetInt64(-55)); }
public bool PosTest2() { return PosIndexOf<Int32>(2, TestLibrary.Generator.GetInt32(-55), TestLibrary.Generator.GetInt32(-55)); }
public bool PosTest3() { return PosIndexOf<Int16>(3, TestLibrary.Generator.GetInt16(-55), TestLibrary.Generator.GetInt16(-55)); }
public bool PosTest4() { return PosIndexOf<Byte>(4, TestLibrary.Generator.GetByte(-55), TestLibrary.Generator.GetByte(-55)); }
public bool PosTest5() { return PosIndexOf<double>(5, TestLibrary.Generator.GetDouble(-55), TestLibrary.Generator.GetDouble(-55)); }
public bool PosTest6() { return PosIndexOf<float>(6, TestLibrary.Generator.GetSingle(-55), TestLibrary.Generator.GetSingle(-55)); }
public bool PosTest7() { return PosIndexOf<char>(7, TestLibrary.Generator.GetCharLetter(-55), TestLibrary.Generator.GetCharLetter(-55)); }
public bool PosTest8() { return PosIndexOf<char>(8, TestLibrary.Generator.GetCharNumber(-55), TestLibrary.Generator.GetCharNumber(-55)); }
public bool PosTest9() { return PosIndexOf<char>(9, TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55)); }
public bool PosTest10() { return PosIndexOf<string>(10, TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN), TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN)); }
public bool PosTest11() { return PosIndexOf2<Int32>(11, 1, 0, 0, 0); }
public bool NegTest1() { return NegIndexOf<Int32>(1, 1); }
// id, defaultValue, length, startIndex, count
public bool NegTest2() { return NegIndexOf2<Int32>( 2, 1, 0, 1, 0); }
public bool NegTest3() { return NegIndexOf2<Int32>( 3, 1, 0, -2, 0); }
public bool NegTest4() { return NegIndexOf2<Int32>( 4, 1, 0, -1, 1); }
public bool NegTest5() { return NegIndexOf2<Int32>( 5, 1, 0, 0, 1); }
public bool NegTest6() { return NegIndexOf2<Int32>( 6, 1, 1, -1, 1); }
public bool NegTest7() { return NegIndexOf2<Int32>( 7, 1, 1, 2, 1); }
public bool NegTest8() { return NegIndexOf2<Int32>( 8, 1, 1, 0, -1); }
public bool NegTest9() { return NegIndexOf2<Int32>( 9, 1, 1, 0, -1); }
public bool NegTest10() { return NegIndexOf2<Int32>(10, 1, 1, 1, 2); }
public bool PosIndexOf<T>(int id, T element, T otherElem)
{
bool retVal = true;
T[] array;
int length;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.LastInexOf(T[] array, T value, int startIndex, int count) (T=="+typeof(T)+") where value is found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = new T[length];
// fill the array
for (int i=0; i<array.Length; i++)
{
array[i] = otherElem;
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
newIndex = Array.LastIndexOf<T>(array, element, array.Length-1, array.Length);
if (index > newIndex)
{
TestLibrary.TestFramework.LogError("000", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")");
retVal = false;
}
if (!element.Equals(array[newIndex]))
{
TestLibrary.TestFramework.LogError("001", "Unexpected value: Expected(" + element + ") Actual(" + array[newIndex] + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosIndexOf2<T>(int id, T defaultValue, int length, int startIndex, int count)
{
bool retVal = true;
T[] array = null;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.LastInexOf(T["+length+"] array, T value, "+startIndex+", "+count+") (T == "+typeof(T)+" where array is null");
try
{
array = new T[ length ];
newIndex = Array.LastIndexOf<T>(array, defaultValue, startIndex, count);
if (-1 != newIndex)
{
TestLibrary.TestFramework.LogError("003", "Unexpected value: Expected(-1) Actual("+newIndex+")");
retVal = false;
}
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegIndexOf<T>(int id, T defaultValue)
{
bool retVal = true;
T[] array = null;
TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.LastInexOf(T[] array, T value, int startIndex, int count) (T == "+typeof(T)+" where array is null");
try
{
Array.LastIndexOf<T>(array, defaultValue, 0, 0);
TestLibrary.TestFramework.LogError("005", "Exepction should have been thrown");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegIndexOf2<T>(int id, T defaultValue, int length, int startIndex, int count)
{
bool retVal = true;
T[] array = null;
TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.LastInexOf(T["+length+"] array, T value, "+startIndex+", "+count+") (T == "+typeof(T)+" where array is null");
try
{
array = new T[ length ];
Array.LastIndexOf<T>(array, defaultValue, startIndex, count);
TestLibrary.TestFramework.LogError("007", "Exepction should have been thrown");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| |
// 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.IO.PortsTests;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Event_Generic : PortsTest
{
// Maximum time to wait for all of the expected events to be firered
private static readonly int MAX_TIME_WAIT = 5000;
// Time to wait in-between triggering events
private static readonly int TRIGERING_EVENTS_WAIT_TIME = 500;
#region Test Cases
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void EventHandlers_CalledSerially()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true);
ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true);
ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true);
int numPinChangedEvents = 0, numErrorEvents = 0, numReceivedEvents = 0;
int iterationWaitTime = 100;
/***************************************************************
Scenario Description: All of the event handlers should be called sequentially never
at the same time on multiple thread. Basically we will block each event handler caller thread and verify
that no other thread is in another event handler
***************************************************************/
Debug.WriteLine("Verifying that event handlers are called serially");
com1.WriteTimeout = 5000;
com2.WriteTimeout = 5000;
com1.Open();
com2.Open();
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
com1.PinChanged += pinChangedEventHandler.HandleEvent;
com1.DataReceived += receivedEventHandler.HandleEvent;
com1.ErrorReceived += errorEventHandler.HandleEvent;
//This should cause ErrorEvent to be fired with a parity error since the
//8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark),
//and com2 is writing 0 for this bit
com1.DataBits = 7;
com1.Parity = Parity.Mark;
com2.BaseStream.Write(new byte[1], 0, 1);
Debug.Print("ERROREvent Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged
//since we are setting DtrEnable to true
com2.DtrEnable = true;
Debug.WriteLine("PinChange Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause ReceivedEvent to be fired with ReceivedChars
//since we are writing some bytes
com1.DataBits = 8;
com1.Parity = Parity.None;
com2.BaseStream.Write(new byte[] { 40 }, 0, 1);
Debug.WriteLine("RxEvent Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause a frame error since the 8th bit is not set,
//and com1 is set to 7 data bits so the 8th bit will +12v where
//com1 expects the stop bit at the 8th bit to be -12v
com1.DataBits = 7;
com1.Parity = Parity.None;
com2.BaseStream.Write(new byte[] { 0x01 }, 0, 1);
Debug.WriteLine("FrameError Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged
//since we are setting RtsEnable to true
com2.RtsEnable = true;
Debug.WriteLine("PinChange Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause ReceivedEvent to be fired with EofReceived
//since we are writing the EOF char
com1.DataBits = 8;
com1.Parity = Parity.None;
com2.BaseStream.Write(new byte[] { 26 }, 0, 1);
Debug.WriteLine("RxEOF Triggered");
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
//This should cause PinChangedEvent to be fired with SerialPinChanges.Break
//since we are setting BreakState to true
com2.BreakState = true;
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
bool threadFound = true;
Stopwatch sw = Stopwatch.StartNew();
while (threadFound && sw.ElapsedMilliseconds < MAX_TIME_WAIT)
{
threadFound = false;
for (int i = 0; i < MAX_TIME_WAIT / iterationWaitTime; ++i)
{
Debug.WriteLine("Event counts: PinChange {0}, Rx {1}, error {2}", numPinChangedEvents, numReceivedEvents, numErrorEvents);
Debug.WriteLine("Waiting for pinchange event {0}ms", iterationWaitTime);
if (pinChangedEventHandler.WaitForEvent(iterationWaitTime, numPinChangedEvents + 1))
{
// A thread is in PinChangedEvent: verify that it is not in any other handler at the same time
if (receivedEventHandler.NumEventsHandled != numReceivedEvents)
{
Fail("Err_191818ahied A thread is in PinChangedEvent and ReceivedEvent");
}
if (errorEventHandler.NumEventsHandled != numErrorEvents)
{
Fail("Err_198119hjaheid A thread is in PinChangedEvent and ErrorEvent");
}
++numPinChangedEvents;
pinChangedEventHandler.ResumeHandleEvent();
threadFound = true;
break;
}
Debug.WriteLine("Waiting for rx event {0}ms", iterationWaitTime);
if (receivedEventHandler.WaitForEvent(iterationWaitTime, numReceivedEvents + 1))
{
// A thread is in ReceivedEvent: verify that it is not in any other handler at the same time
if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents)
{
Fail("Err_2288ajed A thread is in ReceivedEvent and PinChangedEvent");
}
if (errorEventHandler.NumEventsHandled != numErrorEvents)
{
Fail("Err_25158ajeiod A thread is in ReceivedEvent and ErrorEvent");
}
++numReceivedEvents;
receivedEventHandler.ResumeHandleEvent();
threadFound = true;
break;
}
Debug.WriteLine("Waiting for error event {0}ms", iterationWaitTime);
if (errorEventHandler.WaitForEvent(iterationWaitTime, numErrorEvents + 1))
{
// A thread is in ErrorEvent: verify that it is not in any other handler at the same time
if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents)
{
Fail("Err_01208akiehd A thread is in ErrorEvent and PinChangedEvent");
}
if (receivedEventHandler.NumEventsHandled != numReceivedEvents)
{
Fail("Err_1254847ajied A thread is in ErrorEvent and ReceivedEvent");
}
++numErrorEvents;
errorEventHandler.ResumeHandleEvent();
threadFound = true;
break;
}
}
}
Assert.True(pinChangedEventHandler.SuccessfulWait, "pinChangedEventHandler did not receive resume handle event");
Assert.True(receivedEventHandler.SuccessfulWait, "receivedEventHandler did not receive resume handle event");
Assert.True(errorEventHandler.SuccessfulWait, "errorEventHandler did not receive resume handle event");
if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3))
{
Fail("Err_2288ajied Expected 3 PinChangedEvents to be fired and only {0} occurred",
pinChangedEventHandler.NumEventsHandled);
}
if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2))
{
Fail("Err_122808aoeid Expected 2 ReceivedEvents to be fired and only {0} occurred",
receivedEventHandler.NumEventsHandled);
}
if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2))
{
Fail("Err_215887ajeid Expected 3 ErrorEvents to be fired and only {0} occurred",
errorEventHandler.NumEventsHandled);
}
//[] Verify all PinChangedEvents should have occurred
pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0);
pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0);
pinChangedEventHandler.Validate(SerialPinChange.Break, 0);
//[] Verify all ReceivedEvent should have occurred
receivedEventHandler.Validate(SerialData.Chars, 0);
receivedEventHandler.Validate(SerialData.Eof, 0);
//[] Verify all ErrorEvents should have occurred
errorEventHandler.Validate(SerialError.RXParity, 0);
errorEventHandler.Validate(SerialError.Frame, 0);
// It's important that we close com1 BEFORE com2 (the using() block would do this the other way around normally)
// This is because we have our special blocking event handlers hooked onto com1, and closing com2 is likely to
// cause a pin-change event which then hangs and prevents com1 from closing.
// An alternative approach would be to unhook all the event-handlers before leaving the using() block.
com1.Close();
}
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Thread_In_PinChangedEvent()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true);
Debug.WriteLine(
"Verifying that if a thread is blocked in a PinChangedEvent handler the port can still be closed");
com1.Open();
com2.Open();
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
com1.PinChanged += pinChangedEventHandler.HandleEvent;
//This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged
//since we are setting DtrEnable to true
com2.DtrEnable = true;
if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1))
{
Fail("Err_32688ajoid Expected 1 PinChangedEvents to be fired and only {0} occurred",
pinChangedEventHandler.NumEventsHandled);
}
Task task = Task.Run(() => com1.Close());
Thread.Sleep(5000);
pinChangedEventHandler.ResumeHandleEvent();
TCSupport.WaitForTaskCompletion(task);
Assert.True(pinChangedEventHandler.SuccessfulWait, "pinChangedEventHandler did not receive resume handle event");
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Thread_In_ReceivedEvent()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true);
Debug.WriteLine(
"Verifying that if a thread is blocked in a RecevedEvent handler the port can still be closed");
com1.Open();
com2.Open();
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
com1.DataReceived += receivedEventHandler.HandleEvent;
//This should cause ReceivedEvent to be fired with ReceivedChars
//since we are writing some bytes
com1.DataBits = 8;
com1.Parity = Parity.None;
com2.BaseStream.Write(new byte[] { 40 }, 0, 1);
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1))
{
Fail("Err_122808aoeid Expected 1 ReceivedEvents to be fired and only {0} occurred",
receivedEventHandler.NumEventsHandled);
}
Task task = Task.Run(() => com1.Close());
Thread.Sleep(5000);
receivedEventHandler.ResumeHandleEvent();
TCSupport.WaitForTaskCompletion(task);
Assert.True(receivedEventHandler.SuccessfulWait, "receivedEventHandler did not receive resume handle event");
}
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Thread_In_ErrorEvent()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true);
Debug.WriteLine("Verifying that if a thread is blocked in a ErrorEvent handler the port can still be closed");
com1.Open();
com2.Open();
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
com1.ErrorReceived += errorEventHandler.HandleEvent;
//This should cause ErrorEvent to be fired with a parity error since the
//8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark),
//and com2 is writing 0 for this bit
com1.DataBits = 7;
com1.Parity = Parity.Mark;
com2.BaseStream.Write(new byte[1], 0, 1);
Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME);
if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 1))
{
Fail("Err_215887ajeid Expected 1 ErrorEvents to be fired and only {0} occurred", errorEventHandler.NumEventsHandled);
}
Task task = Task.Run(() => com1.Close());
Thread.Sleep(5000);
errorEventHandler.ResumeHandleEvent();
TCSupport.WaitForTaskCompletion(task);
Assert.True(errorEventHandler.SuccessfulWait, "errorEventHandler did not receive resume handle event");
}
}
#endregion
#region Verification for Test Cases
private class PinChangedEventHandler : TestEventHandler<SerialPinChange>
{
public PinChangedEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait)
{
}
public void HandleEvent(object source, SerialPinChangedEventArgs e)
{
HandleEvent(source, e.EventType);
}
}
private class ErrorEventHandler : TestEventHandler<SerialError>
{
public ErrorEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait)
{
}
public void HandleEvent(object source, SerialErrorReceivedEventArgs e)
{
HandleEvent(source, e.EventType);
}
}
private class ReceivedEventHandler : TestEventHandler<SerialData>
{
public ReceivedEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait)
{
}
public void HandleEvent(object source, SerialDataReceivedEventArgs e)
{
HandleEvent(source, e.EventType);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobOperations operations.
/// </summary>
internal partial class JobOperations : IServiceOperations<DataLakeAnalyticsJobManagementClient>, IJobOperations
{
/// <summary>
/// Initializes a new instance of the JobOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal JobOperations(DataLakeAnalyticsJobManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DataLakeAnalyticsJobManagementClient
/// </summary>
public DataLakeAnalyticsJobManagementClient Client { get; private set; }
/// <summary>
/// Gets statistics of the specified job.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// Job Information ID.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<JobStatistics>> GetStatisticsWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlaJobDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("jobIdentity", jobIdentity);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetStatistics", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}/GetStatistics";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix);
_url = _url.Replace("{jobIdentity}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(jobIdentity, this.Client.SerializationSettings).Trim('"')));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<JobStatistics>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<JobStatistics>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the job debug data information specified by the job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<JobDataPath>> GetDebugDataPathWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlaJobDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("jobIdentity", jobIdentity);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetDebugDataPath", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}/GetDebugDataPath";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix);
_url = _url.Replace("{jobIdentity}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(jobIdentity, this.Client.SerializationSettings).Trim('"')));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<JobDataPath>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<JobDataPath>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Builds (compiles) the specified job in the specified Data Lake Analytics
/// account for job correctness and validation.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='parameters'>
/// The parameters to build a job.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<JobInformation>> BuildWithHttpMessagesAsync(string accountName, JobInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlaJobDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Build", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "BuildJob";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix);
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<JobInformation>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<JobInformation>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Cancels the running job specified by the job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID to cancel.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlaJobDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("jobIdentity", jobIdentity);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Cancel", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}/CancelJob";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix);
_url = _url.Replace("{jobIdentity}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(jobIdentity, this.Client.SerializationSettings).Trim('"')));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
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 job information for the specified job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<JobInformation>> GetWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlaJobDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("jobIdentity", jobIdentity);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix);
_url = _url.Replace("{jobIdentity}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(jobIdentity, this.Client.SerializationSettings).Trim('"')));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<JobInformation>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<JobInformation>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Submits a job to the specified Data Lake Analytics account.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// The job ID (a GUID) for the job being submitted.
/// </param>
/// <param name='parameters'>
/// The parameters to submit a job.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<JobInformation>> CreateWithHttpMessagesAsync(string accountName, Guid jobIdentity, JobInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlaJobDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("jobIdentity", jobIdentity);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix);
_url = _url.Replace("{jobIdentity}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(jobIdentity, this.Client.SerializationSettings).Trim('"')));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<JobInformation>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<JobInformation>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='search'>
/// A free form search. A free-text search expression to match for whether a
/// particular entry should be included in the feed, e.g.
/// Categories?$search=blue OR green. Optional.
/// </param>
/// <param name='format'>
/// The return format. Return the response in particular formatxii without
/// access to request headers for standard content-type negotiation (e.g
/// Orders?$format=json). Optional.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<JobInformation>>> ListWithHttpMessagesAsync(string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?), string search = default(string), string format = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlaJobDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("select", select);
tracingParameters.Add("count", count);
tracingParameters.Add("search", search);
tracingParameters.Add("format", format);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix);
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", Uri.EscapeDataString(select)));
}
if (count != null)
{
_queryParameters.Add(string.Format("$count={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(count, this.Client.SerializationSettings).Trim('"'))));
}
if (search != null)
{
_queryParameters.Add(string.Format("$search={0}", Uri.EscapeDataString(search)));
}
if (format != null)
{
_queryParameters.Add(string.Format("$format={0}", Uri.EscapeDataString(format)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<JobInformation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<JobInformation>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<JobInformation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<JobInformation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<JobInformation>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using SteamKit2;
using SteamTrade.Exceptions;
namespace SteamTrade
{
public class TradeManager
{
private const int MaxGapTimeDefault = 15;
private const int MaxTradeTimeDefault = 180;
private const int TradePollingIntervalDefault = 800;
private readonly string ApiKey;
private readonly ISteamWeb SteamWeb;
private DateTime tradeStartTime;
private DateTime lastOtherActionTime;
private DateTime lastTimeoutMessage;
/// <summary>
/// Initializes a new instance of the <see cref="SteamTrade.TradeManager"/> class.
/// </summary>
/// <param name='apiKey'>
/// The Steam Web API key. Cannot be null.
/// </param>
/// <param name="steamWeb">
/// The SteamWeb instances for this bot
/// </param>
public TradeManager (string apiKey, ISteamWeb steamWeb)
{
if (apiKey == null)
throw new ArgumentNullException ("apiKey");
if (steamWeb == null)
throw new ArgumentNullException ("steamWeb");
SetTradeTimeLimits (MaxTradeTimeDefault, MaxGapTimeDefault, TradePollingIntervalDefault);
ApiKey = apiKey;
SteamWeb = steamWeb;
}
#region Public Properties
/// <summary>
/// Gets or the maximum trading time the bot will take in seconds.
/// </summary>
/// <value>
/// The maximum trade time.
/// </value>
public int MaxTradeTimeSec
{
get;
private set;
}
/// <summary>
/// Gets or the maxmium amount of time the bot will wait between actions.
/// </summary>
/// <value>
/// The maximum action gap.
/// </value>
public int MaxActionGapSec
{
get;
private set;
}
/// <summary>
/// Gets the Trade polling interval in milliseconds.
/// </summary>
public int TradePollingInterval
{
get;
private set;
}
/// <summary>
/// Gets or sets a value indicating whether the trade thread running.
/// </summary>
/// <value>
/// <c>true</c> if the trade thread running; otherwise, <c>false</c>.
/// </value>
public bool IsTradeThreadRunning
{
get;
internal set;
}
#endregion Public Properties
#region Public Events
/// <summary>
/// Occurs when the trade times out because either the user didn't complete an
/// action in a set amount of time, or they took too long with the whole trade.
/// </summary>
public EventHandler OnTimeout;
#endregion Public Events
#region Public Methods
/// <summary>
/// Sets the trade time limits.
/// </summary>
/// <param name='maxTradeTime'>
/// Max trade time in seconds.
/// </param>
/// <param name='maxActionGap'>
/// Max gap between user action in seconds.
/// </param>
/// <param name='pollingInterval'>The trade polling interval in milliseconds.</param>
public void SetTradeTimeLimits (int maxTradeTime, int maxActionGap, int pollingInterval)
{
MaxTradeTimeSec = maxTradeTime;
MaxActionGapSec = maxActionGap;
TradePollingInterval = pollingInterval;
}
/// <summary>
/// Creates a trade object and returns it for use.
/// Call <see cref="InitializeTrade"/> before using this method.
/// </summary>
/// <returns>
/// The trade object to use to interact with the Steam trade.
/// </returns>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// If the needed inventories are <c>null</c> then they will be fetched.
/// </remarks>
public Trade CreateTrade (SteamID me, SteamID other)
{
var t = new Trade (me, other, SteamWeb);
t.OnClose += delegate
{
IsTradeThreadRunning = false;
};
return t;
}
/// <summary>
/// Stops the trade thread.
/// </summary>
/// <remarks>
/// Also, nulls out the inventory objects so they have to be fetched
/// again if a new trade is started.
/// </remarks>
public void StopTrade ()
{
// TODO: something to check that trade was the Trade returned from CreateTrade
IsTradeThreadRunning = false;
}
#endregion Public Methods
/// <summary>
/// Starts the actual trade-polling thread.
/// </summary>
public void StartTradeThread (Trade trade)
{
// initialize data to use in thread
tradeStartTime = DateTime.Now;
lastOtherActionTime = DateTime.Now;
lastTimeoutMessage = DateTime.Now.AddSeconds(-1000);
var pollThread = new Thread (() =>
{
IsTradeThreadRunning = true;
DebugPrint ("Trade thread starting.");
// main thread loop for polling
try
{
while(IsTradeThreadRunning)
{
bool action = trade.Poll();
if(action)
lastOtherActionTime = DateTime.Now;
if (trade.HasTradeEnded || CheckTradeTimeout(trade))
{
IsTradeThreadRunning = false;
break;
}
Thread.Sleep(TradePollingInterval);
}
}
catch(Exception ex)
{
// TODO: find a new way to do this w/o the trade events
//if (OnError != null)
// OnError("Error Polling Trade: " + e);
// ok then we should stop polling...
IsTradeThreadRunning = false;
DebugPrint("[TRADEMANAGER] general error caught: " + ex);
trade.FireOnErrorEvent("Unknown error occurred: " + ex.ToString());
}
finally
{
DebugPrint("Trade thread shutting down.");
try //Yikes, that's a lot of nested 'try's. Is there some way to clean this up?
{
if(trade.IsTradeAwaitingConfirmation)
trade.FireOnAwaitingConfirmation();
}
catch(Exception ex)
{
trade.FireOnErrorEvent("Unknown error occurred during OnTradeAwaitingConfirmation: " + ex.ToString());
}
finally
{
try
{
//Make sure OnClose is always fired after OnSuccess, even if OnSuccess throws an exception
//(which it NEVER should, but...)
trade.FireOnCloseEvent();
}
catch (Exception e)
{
DebugError("Error occurred during trade.OnClose()! " + e);
throw;
}
}
}
});
pollThread.Start();
}
private bool CheckTradeTimeout (Trade trade)
{
// User has accepted the trade. Disregard time out.
if (trade.OtherUserAccepted)
return false;
var now = DateTime.Now;
DateTime actionTimeout = lastOtherActionTime.AddSeconds (MaxActionGapSec);
int untilActionTimeout = (int)Math.Round ((actionTimeout - now).TotalSeconds);
DebugPrint (String.Format ("{0} {1}", actionTimeout, untilActionTimeout));
DateTime tradeTimeout = tradeStartTime.AddSeconds (MaxTradeTimeSec);
int untilTradeTimeout = (int)Math.Round ((tradeTimeout - now).TotalSeconds);
double secsSinceLastTimeoutMessage = (now - lastTimeoutMessage).TotalSeconds;
if (untilActionTimeout <= 0 || untilTradeTimeout <= 0)
{
DebugPrint ("timed out...");
if (OnTimeout != null)
{
OnTimeout (this, null);
}
trade.CancelTrade ();
return true;
}
else if (untilActionTimeout <= 20 && secsSinceLastTimeoutMessage >= 10)
{
try
{
trade.SendMessage("Are You AFK? The trade will be canceled in " + untilActionTimeout + " seconds if you don't do something.");
}
catch { }
lastTimeoutMessage = now;
}
return false;
}
[Conditional ("DEBUG_TRADE_MANAGER")]
private static void DebugPrint (string output)
{
// I don't really want to add the Logger as a dependecy to TradeManager so I
// print using the console directly. To enable this for debugging put this:
// #define DEBUG_TRADE_MANAGER
// at the first line of this file.
System.Console.WriteLine (output);
}
private static void DebugError(string output)
{
System.Console.WriteLine(output);
}
}
}
| |
// <copyright file="IFile.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace IX.System.IO;
/// <summary>
/// Abstracts the <see cref="File" /> class' static methods into a mock-able interface.
/// </summary>
[PublicAPI]
public interface IFile
{
#region Methods
/// <summary>
/// Appends lines of text to a specified file path.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
void AppendAllLines(
string path,
IEnumerable<string> contents,
Encoding? encoding = null);
/// <summary>
/// Asynchronously appends lines of text to a specified file path.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task AppendAllLinesAsync(
string path,
IEnumerable<string> contents,
Encoding? encoding = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Appends text to a specified file path.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
void AppendAllText(
string path,
string contents,
Encoding? encoding = null);
/// <summary>
/// Asynchronously appends text to a specified file path.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
/// <remarks>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </remarks>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task AppendAllTextAsync(
string path,
string contents,
Encoding? encoding = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Opens a <see cref="StreamWriter" /> to append text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>A <see cref="StreamWriter" /> that can write to a file.</returns>
StreamWriter AppendText(string path);
/// <summary>
/// Copies a file to another.
/// </summary>
/// <param name="sourceFileName">The source file.</param>
/// <param name="destinationFileName">The destination file.</param>
/// <param name="overwrite">
/// If <see langword="true" />, overwrites the destination file, if one exists, otherwise throws an exception. If a
/// destination file doesn't
/// exist, this parameter is ignored.
/// </param>
void Copy(
string sourceFileName,
string destinationFileName,
bool overwrite = false);
/// <summary>
/// Asynchronously copies a file to another.
/// </summary>
/// <param name="sourceFileName">The source file.</param>
/// <param name="destinationFileName">The destination file.</param>
/// <param name="overwrite">
/// If <see langword="true" />, overwrites the destination file, if one exists, otherwise throws an exception. If a
/// destination file doesn't
/// exist, this parameter is ignored.
/// </param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task CopyAsync(
string sourceFileName,
string destinationFileName,
bool overwrite = false,
CancellationToken cancellationToken = default);
/// <summary>
/// Creates a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="bufferSize">The buffer size to use. Default is 4 kilobytes.</param>
/// <returns>A <see cref="Stream" /> that can read from and write to a file.</returns>
Stream Create(
string path,
int bufferSize = 4096);
/// <summary>
/// Opens a <see cref="StreamWriter" /> to write text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>A <see cref="StreamWriter" /> that can write to a file.</returns>
StreamWriter CreateText(string path);
/// <summary>
/// Deletes a file.
/// </summary>
/// <param name="path">The path of the file.</param>
void Delete(string path);
/// <summary>
/// Asynchronously deletes a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task DeleteAsync(
string path,
CancellationToken cancellationToken = default);
/// <summary>
/// Checks whether a file exists and is accessible.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>
/// Returns <see langword="true" /> if the specified file exists and is accessible, <see langword="false" />
/// otherwise.
/// </returns>
bool Exists(string path);
/// <summary>
/// Asynchronously checks whether a file exists and is accessible.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation, holding <see langword="true" /> if the specified file exists and is
/// accessible, <see langword="false" /> otherwise.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<bool> ExistsAsync(
string path,
CancellationToken cancellationToken = default);
/// <summary>
/// Gets a specific file's creation time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>A <see cref="DateTime" /> in UTC.</returns>
DateTime GetCreationTime(string path);
/// <summary>
/// Gets a specific file's creation time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation, holding a <see cref="DateTime" /> in UTC.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<DateTime> GetCreationTimeAsync(
string path,
CancellationToken cancellationToken = default);
/// <summary>
/// Gets a specific file's last access time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>A <see cref="DateTime" /> in UTC.</returns>
DateTime GetLastAccessTime(string path);
/// <summary>
/// Gets a specific file's last access time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation, holding a <see cref="DateTime" /> in UTC.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<DateTime> GetLastAccessTimeAsync(
string path,
CancellationToken cancellationToken = default);
/// <summary>
/// Gets a specific file's last write time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>A <see cref="DateTime" /> in UTC.</returns>
DateTime GetLastWriteTime(string path);
/// <summary>
/// Asynchronously gets a specific file's last write time, in UTC.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation, holding a <see cref="DateTime" /> in UTC.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<DateTime> GetLastWriteTimeAsync(
string path,
CancellationToken cancellationToken = default);
/// <summary>
/// Moves a file.
/// </summary>
/// <param name="sourceFileName">The source file name.</param>
/// <param name="destinationFileName">The destination file name.</param>
void Move(
string sourceFileName,
string destinationFileName);
/// <summary>
/// Asynchronously moves a file.
/// </summary>
/// <param name="sourceFileName">The source file name.</param>
/// <param name="destinationFileName">The destination file name.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task MoveAsync(
string sourceFileName,
string destinationFileName,
CancellationToken cancellationToken = default);
/// <summary>
/// Opens a <see cref="Stream" /> to read from a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>A <see cref="Stream" /> that can read from a file.</returns>
Stream OpenRead(string path);
/// <summary>
/// Opens a <see cref="StreamReader" /> to read text from a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>A <see cref="StreamReader" /> that can read from a file.</returns>
StreamReader OpenText(string path);
/// <summary>
/// Opens a <see cref="Stream" /> to write to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>A <see cref="Stream" /> that can write to a file.</returns>
Stream OpenWrite(string path);
/// <summary>
/// Reads the entire contents of a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <returns>The contents of a file, in binary.</returns>
byte[] ReadAllBytes(string path);
/// <summary>
/// Asynchronously reads the entire contents of a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation, holding the contents of a file, in binary.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<byte[]> ReadAllBytesAsync(
string path,
CancellationToken cancellationToken = default);
/// <summary>
/// Reads the entire contents of a file and splits them by end-of-line markers.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <returns>An array of <see cref="string" />.</returns>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
string[] ReadAllLines(
string path,
Encoding? encoding = null);
/// <summary>
/// Asynchronously reads the entire contents of a file and splits them by end-of-line markers.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation, holding an array of <see cref="string" />.
/// </returns>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<string[]> ReadAllLinesAsync(
string path,
Encoding? encoding = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Reads the entire contents of a file as text.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <returns>The entire file contents as a string.</returns>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
string ReadAllText(
string path,
Encoding? encoding = null);
/// <summary>
/// Asynchronously reads the entire contents of a file as text.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation, holding the entire file contents as a <see cref="string" />.
/// </returns>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task<string> ReadAllTextAsync(
string path,
Encoding? encoding = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Reads file contents as text line by line.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <returns>An enumerable of strings, each representing one line of text.</returns>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
IEnumerable<string> ReadLines(
string path,
Encoding? encoding = null);
/// <summary>
/// Sets the file's creation time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="creationTime">A <see cref="DateTime" /> with the file attribute to set.</param>
void SetCreationTime(
string path,
DateTime creationTime);
/// <summary>
/// Asynchronously sets the file's creation time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="creationTime">A <see cref="DateTime" /> with the file attribute to set.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task SetCreationTimeAsync(
string path,
DateTime creationTime,
CancellationToken cancellationToken = default);
/// <summary>
/// Sets the file's last access time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lastAccessTime">A <see cref="DateTime" /> with the file attribute to set.</param>
void SetLastAccessTime(
string path,
DateTime lastAccessTime);
/// <summary>
/// Asynchronously sets the file's last access time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lastAccessTime">A <see cref="DateTime" /> with the file attribute to set.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task SetLastAccessTimeAsync(
string path,
DateTime lastAccessTime,
CancellationToken cancellationToken = default);
/// <summary>
/// Sets the file's last write time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lastWriteTime">A <see cref="DateTime" /> with the file attribute to set.</param>
void SetLastWriteTime(
string path,
DateTime lastWriteTime);
/// <summary>
/// Asynchronously sets the file's last write time.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lastWriteTime">A <see cref="DateTime" /> with the file attribute to set.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task SetLastWriteTimeAsync(
string path,
DateTime lastWriteTime,
CancellationToken cancellationToken = default);
/// <summary>
/// Writes binary contents to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="bytes">The contents to write.</param>
void WriteAllBytes(
string path,
byte[] bytes);
/// <summary>
/// Asynchronously writes binary contents to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="bytes">The contents to write.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task WriteAllBytesAsync(
string path,
byte[] bytes,
CancellationToken cancellationToken = default);
/// <summary>
/// Writes lines of text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents to write.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
void WriteAllLines(
string path,
IEnumerable<string> contents,
Encoding? encoding = null);
/// <summary>
/// Asynchronously writes lines of text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents to write.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task WriteAllLinesAsync(
string path,
IEnumerable<string> contents,
Encoding? encoding = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Writes text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents to write.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
void WriteAllText(
string path,
string contents,
Encoding? encoding = null);
/// <summary>
/// Writes text to a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="contents">The contents to write.</param>
/// <param name="encoding">The encoding to use. Can be <see langword="null" />.</param>
/// <remarks>
/// <para>
/// This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
/// <see langword="null" />, an implementation-specific
/// encoding will be used.
/// </para>
/// </remarks>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A task representing the current operation.
/// </returns>
// TODO BREAKING: In next breaking-changes version, switch this to a ValueTask-returning method
Task WriteAllTextAsync(
string path,
string contents,
Encoding? encoding = null,
CancellationToken cancellationToken = default);
#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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableSortedSet{T}.Builder"/> class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableSortedSet<T>
{
/// <summary>
/// A sorted set that mutates with little or no memory allocations,
/// can produce and/or build on immutable sorted set instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// While <see cref="ImmutableSortedSet{T}.Union"/> and other bulk change methods
/// already provide fast bulk change operations on the collection, this class allows
/// multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableSortedSetBuilderDebuggerProxy<>))]
public sealed class Builder : ISortKeyCollection<T>, IReadOnlyCollection<T>, ISet<T>, ICollection
{
/// <summary>
/// The root of the binary tree that stores the collection. Contents are typically not entirely frozen.
/// </summary>
private ImmutableSortedSet<T>.Node _root = ImmutableSortedSet<T>.Node.EmptyNode;
/// <summary>
/// The comparer to use for sorting the set.
/// </summary>
private IComparer<T> _comparer = Comparer<T>.Default;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableSortedSet<T> _immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int _version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object _syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="set">A set to act as the basis for a new set.</param>
internal Builder(ImmutableSortedSet<T> set)
{
Requires.NotNull(set, nameof(set));
_root = set._root;
_comparer = set.KeyComparer;
_immutable = set;
}
#region ISet<T> Properties
/// <summary>
/// Gets the number of elements in this set.
/// </summary>
public int Count
{
get { return this.Root.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read-only.
/// </summary>
/// <value>Always <c>false</c>.</value>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Gets the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>The element at the given position.</returns>
/// <remarks>
/// No index setter is offered because the element being replaced may not sort
/// to the same position in the sorted collection as the replacing element.
/// </remarks>
public T this[int index]
{
#if !NETSTANDARD10
get { return _root.ItemRef(index); }
#else
get { return _root[index]; }
#endif
}
#if !NETSTANDARD10
/// <summary>
/// Gets a read-only reference to the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>A read-only reference to the element at the given position.</returns>
public ref readonly T ItemRef(int index)
{
return ref _root.ItemRef(index);
}
#endif
/// <summary>
/// Gets the maximum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The maximum value in the set.</value>
public T Max
{
get { return _root.Max; }
}
/// <summary>
/// Gets the minimum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The minimum value in the set.</value>
public T Min
{
get { return _root.Min; }
}
/// <summary>
/// Gets or sets the <see cref="IComparer{T}"/> object that is used to determine equality for the values in the <see cref="ImmutableSortedSet{T}"/>.
/// </summary>
/// <value>The comparer that is used to determine equality for the values in the set.</value>
/// <remarks>
/// When changing the comparer in such a way as would introduce collisions, the conflicting elements are dropped,
/// leaving only one of each matching pair in the collection.
/// </remarks>
public IComparer<T> KeyComparer
{
get
{
return _comparer;
}
set
{
Requires.NotNull(value, nameof(value));
if (value != _comparer)
{
var newRoot = Node.EmptyNode;
foreach (T item in this)
{
bool mutated;
newRoot = newRoot.Add(item, value, out mutated);
}
_immutable = null;
_comparer = value;
this.Root = newRoot;
}
}
}
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return _version; }
}
/// <summary>
/// Gets or sets the root node that represents the data in this collection.
/// </summary>
private Node Root
{
get
{
return _root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
_version++;
if (_root != value)
{
_root = value;
// Clear any cached value for the immutable view since it is now invalidated.
_immutable = null;
}
}
}
#region ISet<T> Methods
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the
/// element was successfully added.
/// </summary>
/// <param name="item">The element to add to the set.</param>
/// <returns>true if the element is added to the set; false if the element is already in the set.</returns>
public bool Add(T item)
{
bool mutated;
this.Root = this.Root.Add(item, _comparer, out mutated);
return mutated;
}
/// <summary>
/// Removes all elements in the specified collection from the current set.
/// </summary>
/// <param name="other">The collection of items to remove from the set.</param>
public void ExceptWith(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
foreach (T item in other)
{
bool mutated;
this.Root = this.Root.Remove(item, _comparer, out mutated);
}
}
/// <summary>
/// Modifies the current set so that it contains only elements that are also in a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void IntersectWith(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
var result = ImmutableSortedSet<T>.Node.EmptyNode;
foreach (T item in other)
{
if (this.Contains(item))
{
bool mutated;
result = result.Add(item, _comparer, out mutated);
}
}
this.Root = result;
}
/// <summary>
/// Determines whether the current set is a proper (strict) subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct subset of other; otherwise, false.</returns>
public bool IsProperSubsetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsProperSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a proper (strict) superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
public bool IsProperSupersetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsProperSupersetOf(other);
}
/// <summary>
/// Determines whether the current set is a subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a subset of other; otherwise, false.</returns>
public bool IsSubsetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
public bool IsSupersetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsSupersetOf(other);
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set and other share at least one common element; otherwise, false.</returns>
public bool Overlaps(IEnumerable<T> other)
{
return this.ToImmutable().Overlaps(other);
}
/// <summary>
/// Determines whether the current set and the specified collection contain the same elements.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is equal to other; otherwise, false.</returns>
public bool SetEquals(IEnumerable<T> other)
{
return this.ToImmutable().SetEquals(other);
}
/// <summary>
/// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void SymmetricExceptWith(IEnumerable<T> other)
{
this.Root = this.ToImmutable().SymmetricExcept(other)._root;
}
/// <summary>
/// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void UnionWith(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
foreach (T item in other)
{
bool mutated;
this.Root = this.Root.Add(item, _comparer, out mutated);
}
}
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the
/// element was successfully added.
/// </summary>
/// <param name="item">The element to add to the set.</param>
void ICollection<T>.Add(T item)
{
this.Add(item);
}
/// <summary>
/// Removes all elements from this set.
/// </summary>
public void Clear()
{
this.Root = ImmutableSortedSet<T>.Node.EmptyNode;
}
/// <summary>
/// Determines whether the set contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the set.</param>
/// <returns>true if item is found in the set; false otherwise.</returns>
public bool Contains(T item)
{
return this.Root.Contains(item, _comparer);
}
/// <summary>
/// See <see cref="ICollection{T}"/>
/// </summary>
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
_root.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of a specific object from the set.
/// </summary>
/// <param name="item">The object to remove from the set.</param>
/// <returns><c>true</c> if the item was removed from the set; <c>false</c> if the item was not found in the set.</returns>
public bool Remove(T item)
{
bool mutated;
this.Root = this.Root.Remove(item, _comparer, out mutated);
return mutated;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
public ImmutableSortedSet<T>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.Root.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an <see cref="IEnumerable{T}"/> that iterates over this
/// collection in reverse order.
/// </summary>
/// <returns>
/// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}.Builder"/>
/// in reverse order.
/// </returns>
[Pure]
public IEnumerable<T> Reverse()
{
return new ReverseEnumerable(_root);
}
/// <summary>
/// Creates an immutable sorted set based on the contents of this instance.
/// </summary>
/// <returns>An immutable set.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableSortedSet<T> ToImmutable()
{
// Creating an instance of ImmutableSortedSet<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (_immutable == null)
{
_immutable = ImmutableSortedSet<T>.Wrap(this.Root, _comparer);
}
return _immutable;
}
#region ICollection members
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
#endregion
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace System.Net.WebSockets
{
public sealed class ClientWebSocket : WebSocket
{
private enum InternalState
{
Created = 0,
Connecting = 1,
Connected = 2,
Disposed = 3
}
private const string WebSocketAvailableApiCheck = "WinHttpWebSocketCompleteUpgrade";
private readonly ClientWebSocketOptions _options;
private WinHttpWebSocket _innerWebSocket;
private readonly CancellationTokenSource _cts;
// NOTE: this is really an InternalState value, but Interlocked doesn't support
// operations on values of enum types.
private int _state;
public ClientWebSocket()
{
if (Logging.On)
{
Logging.Enter(Logging.WebSockets, this, ".ctor", null);
}
CheckPlatformSupport();
_state = (int)InternalState.Created;
_options = new ClientWebSocketOptions();
_cts = new CancellationTokenSource();
if (Logging.On)
{
Logging.Exit(Logging.WebSockets, this, ".ctor", null);
}
}
#region Properties
public ClientWebSocketOptions Options
{
get
{
return _options;
}
}
public override WebSocketCloseStatus? CloseStatus
{
get
{
if (_innerWebSocket != null)
{
return _innerWebSocket.CloseStatus;
}
return null;
}
}
public override string CloseStatusDescription
{
get
{
if (_innerWebSocket != null)
{
return _innerWebSocket.CloseStatusDescription;
}
return null;
}
}
public override string SubProtocol
{
get
{
if (_innerWebSocket != null)
{
return _innerWebSocket.SubProtocol;
}
return null;
}
}
public override WebSocketState State
{
get
{
// state == Connected or Disposed
if (_innerWebSocket != null)
{
return _innerWebSocket.State;
}
switch ((InternalState)_state)
{
case InternalState.Created:
return WebSocketState.None;
case InternalState.Connecting:
return WebSocketState.Connecting;
default: // We only get here if disposed before connecting
Debug.Assert((InternalState)_state == InternalState.Disposed);
return WebSocketState.Closed;
}
}
}
#endregion Properties
public Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (!uri.IsAbsoluteUri)
{
throw new ArgumentException(SR.net_uri_NotAbsolute, "uri");
}
if (uri.Scheme != UriScheme.Ws && uri.Scheme != UriScheme.Wss)
{
throw new ArgumentException(SR.net_WebSockets_Scheme, "uri");
}
// Check that we have not started already
var priorState = (InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connecting, (int)InternalState.Created);
if (priorState == InternalState.Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
else if (priorState != InternalState.Created)
{
throw new InvalidOperationException(SR.net_WebSockets_AlreadyStarted);
}
_options.SetToReadOnly();
return ConnectAsyncCore(uri, cancellationToken);
}
private Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken)
{
_innerWebSocket = new WinHttpWebSocket();
try
{
// Change internal state to 'connected' to enable the other methods
if ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connected, (int)InternalState.Connecting) != InternalState.Connecting)
{
// Aborted/Disposed during connect.
throw new ObjectDisposedException(GetType().FullName);
}
return _innerWebSocket.ConnectAsync(uri, cancellationToken, _options);
}
catch (Win32Exception ex)
{
WebSocketException wex = new WebSocketException(SR.net_webstatus_ConnectFailure, ex);
if (Logging.On)
{
Logging.Exception(Logging.WebSockets, this, "ConnectAsync", wex);
}
throw wex;
}
catch (Exception ex)
{
if (Logging.On)
{
Logging.Exception(Logging.WebSockets, this, "ConnectAsync", ex);
}
throw;
}
}
public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage,
CancellationToken cancellationToken)
{
ThrowIfNotConnected();
if (!((messageType == WebSocketMessageType.Text) || (messageType == WebSocketMessageType.Binary)))
{
string errorMessage = SR.Format(
SR.net_WebSockets_Argument_InvalidMessageType,
"Close",
"SendAsync",
"Binary",
"Text",
"CloseOutputAsync");
throw new ArgumentException(errorMessage, "messageType");
}
WebSocketValidate.ValidateArraySegment<byte>(buffer, "buffer");
return _innerWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
}
public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
ThrowIfNotConnected();
WebSocketValidate.ValidateArraySegment<byte>(buffer, "buffer");
return _innerWebSocket.ReceiveAsync(buffer, cancellationToken);
}
public override Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription,
CancellationToken cancellationToken)
{
ThrowIfNotConnected();
WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription);
return _innerWebSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
}
public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription,
CancellationToken cancellationToken)
{
ThrowIfNotConnected();
WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription);
return _innerWebSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
}
public override void Abort()
{
if ((InternalState)_state == InternalState.Disposed)
{
return;
}
if (_innerWebSocket != null)
{
_innerWebSocket.Abort();
}
Dispose();
}
public override void Dispose()
{
var priorState = (InternalState)Interlocked.Exchange(ref _state, (int)InternalState.Disposed);
if (priorState == InternalState.Disposed)
{
// No cleanup required.
return;
}
_cts.Cancel(false);
_cts.Dispose();
if (_innerWebSocket != null)
{
_innerWebSocket.Dispose();
}
}
private void ThrowIfNotConnected()
{
if ((InternalState)_state == InternalState.Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
else if ((InternalState)_state != InternalState.Connected)
{
throw new InvalidOperationException(SR.net_WebSockets_NotConnected);
}
}
private void CheckPlatformSupport()
{
bool isPlatformSupported = false;
using (SafeLibraryHandle libHandle = Interop.mincore.LoadLibraryExW(Interop.Libraries.WinHttp, IntPtr.Zero, 0))
{
isPlatformSupported = Interop.mincore.GetProcAddress(libHandle, WebSocketAvailableApiCheck) != IntPtr.Zero;
}
if (!isPlatformSupported)
{
WebSocketValidate.ThrowPlatformNotSupportedException();
}
}
}
}
| |
#region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
namespace FluentMigrator.Builders.Create.Column
{
public class CreateColumnExpressionBuilder : ExpressionBuilderWithColumnTypesBase<CreateColumnExpression, ICreateColumnOptionSyntax>,
ICreateColumnOnTableSyntax,
ICreateColumnAsTypeOrInSchemaSyntax,
ICreateColumnOptionOrForeignKeyCascadeSyntax,
IColumnExpressionBuilder
{
private readonly IMigrationContext _context;
public CreateColumnExpressionBuilder(CreateColumnExpression expression, IMigrationContext context)
: base(expression)
{
_context = context;
ColumnHelper = new ColumnExpressionBuilderHelper(this, context);
}
public ForeignKeyDefinition CurrentForeignKey { get; set; }
public ColumnExpressionBuilderHelper ColumnHelper { get; set; }
public ICreateColumnAsTypeOrInSchemaSyntax OnTable(string name)
{
Expression.TableName = name;
return this;
}
public ICreateColumnAsTypeSyntax InSchema(string schemaName)
{
Expression.SchemaName = schemaName;
return this;
}
public ICreateColumnOptionSyntax WithDefault(SystemMethods method)
{
Expression.Column.DefaultValue = method;
return this;
}
public ICreateColumnOptionSyntax WithDefaultValue(object value)
{
Expression.Column.DefaultValue = value;
return this;
}
public ICreateColumnOptionSyntax SetExistingRowsTo(object value)
{
ColumnHelper.SetExistingRowsTo(value);
return this;
}
public ICreateColumnOptionSyntax WithColumnDescription(string description)
{
Expression.Column.ColumnDescription = description;
return this;
}
public ICreateColumnOptionSyntax Identity()
{
Expression.Column.IsIdentity = true;
return this;
}
public ICreateColumnOptionSyntax Indexed()
{
return Indexed(null);
}
public ICreateColumnOptionSyntax Indexed(string indexName)
{
ColumnHelper.Indexed(indexName);
return this;
}
public ICreateColumnOptionSyntax PrimaryKey()
{
Expression.Column.IsPrimaryKey = true;
return this;
}
public ICreateColumnOptionSyntax PrimaryKey(string primaryKeyName)
{
Expression.Column.IsPrimaryKey = true;
Expression.Column.PrimaryKeyName = primaryKeyName;
return this;
}
public ICreateColumnOptionSyntax Nullable()
{
ColumnHelper.SetNullable(true);
return this;
}
public ICreateColumnOptionSyntax NotNullable()
{
ColumnHelper.SetNullable(false);
return this;
}
public ICreateColumnOptionSyntax Unique()
{
ColumnHelper.Unique(null);
return this;
}
public ICreateColumnOptionSyntax Unique(string indexName)
{
ColumnHelper.Unique(indexName);
return this;
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string primaryTableName, string primaryColumnName)
{
return ForeignKey(null, null, primaryTableName, primaryColumnName);
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string foreignKeyName, string primaryTableName, string primaryColumnName)
{
return ForeignKey(foreignKeyName, null, primaryTableName, primaryColumnName);
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string foreignKeyName, string primaryTableSchema, string primaryTableName,
string primaryColumnName)
{
Expression.Column.IsForeignKey = true;
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = primaryTableName,
PrimaryTableSchema = primaryTableSchema,
ForeignTable = Expression.TableName,
ForeignTableSchema = Expression.SchemaName
}
};
fk.ForeignKey.PrimaryColumns.Add(primaryColumnName);
fk.ForeignKey.ForeignColumns.Add(Expression.Column.Name);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
Expression.Column.ForeignKey = fk.ForeignKey;
return this;
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignTableName, string foreignColumnName)
{
return ReferencedBy(null, null, foreignTableName, foreignColumnName);
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignKeyName, string foreignTableName, string foreignColumnName)
{
return ReferencedBy(foreignKeyName, null, foreignTableName, foreignColumnName);
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignKeyName, string foreignTableSchema, string foreignTableName,
string foreignColumnName)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(Expression.Column.Name);
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
return this;
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax ForeignKey()
{
Expression.Column.IsForeignKey = true;
return this;
}
[Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")]
public ICreateColumnOptionSyntax References(string foreignKeyName, string foreignTableName, IEnumerable<string> foreignColumnNames)
{
return References(foreignKeyName, null, foreignTableName, foreignColumnNames);
}
[Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")]
public ICreateColumnOptionSyntax References(string foreignKeyName, string foreignTableSchema, string foreignTableName,
IEnumerable<string> foreignColumnNames)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(Expression.Column.Name);
foreach (var foreignColumnName in foreignColumnNames)
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
return this;
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax OnDelete(Rule rule)
{
CurrentForeignKey.OnDelete = rule;
return this;
}
public ICreateColumnOptionOrForeignKeyCascadeSyntax OnUpdate(Rule rule)
{
CurrentForeignKey.OnUpdate = rule;
return this;
}
public ICreateColumnOptionSyntax OnDeleteOrUpdate(Rule rule)
{
OnDelete(rule);
OnUpdate(rule);
return this;
}
public override ColumnDefinition GetColumnForType()
{
return Expression.Column;
}
string IColumnExpressionBuilder.SchemaName
{
get
{
return Expression.SchemaName;
}
}
string IColumnExpressionBuilder.TableName
{
get
{
return Expression.TableName;
}
}
ColumnDefinition IColumnExpressionBuilder.Column
{
get
{
return Expression.Column;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Configuration;
using System.Xml.Linq;
using MarkdownSharp;
using ServiceStack.Common.ServiceModel;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.Logging.Support.Logging;
using ServiceStack.Markdown;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceModel;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Extensions;
using ServiceStack.WebHost.Endpoints.Support;
namespace ServiceStack.WebHost.Endpoints
{
public class EndpointHostConfig
{
private static ILog log = LogManager.GetLogger(typeof(EndpointHostConfig));
public static readonly string PublicKey = "<RSAKeyValue><Modulus>xRzMrP3m+3kvT6239OP1YuWIfc/S7qF5NJiPe2/kXnetXiuYtSL4bQRIX1qYh4Cz+dXqZE/sNGJJ4jl2iJQa1tjp+rK28EG6gcuTDHJdvOBBF+aSwJy1MSiT8D0KtP6pe2uvjl9m3jZP/8uRePZTSkt/GjlPOk85JXzOsyzemlaLFiJoGImGvp8dw8vQ7jzA3Ynmywpt5OQxklJfrfALHJ93ny1M5lN5Q+bGPEHLXNCXfF05EA0l9mZpa4ouicYvlbY/OAwefFXIwPQN9ER6Pu7Eq9XWLvnh1YUH8HDckuKK+ESWbAuOgnVbUDEF1BreoWutJ//a/oLDR87Q36cmwQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
public static readonly string LicensePublicKey = "<RSAKeyValue><Modulus>19kx2dJoOIrMYypMTf8ssiCALJ7RS/Iz2QG0rJtYJ2X0+GI+NrgOCapkh/9aDVBieobdClnuBgW08C5QkfBdLRqsptiSu50YIqzVaNBMwZPT0e7Ke02L/fV/M/fVPsolHwzMstKhdWGdK8eNLF4SsLEcvnb79cx3/GnZbXku/ro5eOrTseKL3s4nM4SdMRNn7rEAU0o0Ijb3/RQbhab8IIRB4pHwk1mB+j/mcAQAtMerwpHfwpEBLWlQyVpu0kyKJCEkQjbaPzvfglDRpyBOT5GMUnrcTT/sBr5kSJYpYrgHnA5n4xJnvrnyFqdzXwgGFlikRTbc60pk1cQEWcHgYw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
public static bool SkipPathValidation = false;
/// <summary>
/// Use: \[Route\("[^\/] regular expression to find violating routes in your sln
/// </summary>
public static bool SkipRouteValidation = false;
public static string ServiceStackPath = null;
private static EndpointHostConfig instance;
public static EndpointHostConfig Instance
{
get
{
if (instance == null)
{
instance = new EndpointHostConfig
{
MetadataTypesConfig = new MetadataTypesConfig(
addDefaultXmlNamespace: "http://schemas.servicestack.net/types"),
WsdlServiceNamespace = "http://schemas.servicestack.net/types",
WsdlSoapActionNamespace = "http://schemas.servicestack.net/types",
MetadataPageBodyHtml = @"<br />
<h3><a href=""https://github.com/ServiceStack/ServiceStack/wiki/Clients-overview"">Clients Overview</a></h3>",
MetadataOperationPageBodyHtml = @"<br />
<h3><a href=""https://github.com/ServiceStack/ServiceStack/wiki/Clients-overview"">Clients Overview</a></h3>",
MetadataCustomPath = "Views/Templates/Metadata/",
UseCustomMetadataTemplates = false,
LogFactory = new NullLogFactory(),
EnableAccessRestrictions = true,
WebHostPhysicalPath = "~".MapServerPath(),
ServiceStackHandlerFactoryPath = ServiceStackPath,
MetadataRedirectPath = null,
DefaultContentType = null,
AllowJsonpRequests = true,
AllowRouteContentTypeExtensions = true,
AllowNonHttpOnlyCookies = false,
UseHttpsLinks = false,
DebugMode = false,
DefaultDocuments = new List<string> {
"default.htm",
"default.html",
"default.cshtml",
"default.md",
"index.htm",
"index.html",
"default.aspx",
"default.ashx",
},
GlobalResponseHeaders = new Dictionary<string, string> { { "X-Powered-By", Env.ServerUserAgent } },
IgnoreFormatsInMetadata = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase),
AllowFileExtensions = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
{
"js", "css", "htm", "html", "shtm", "txt", "xml", "rss", "csv", "pdf",
"jpg", "jpeg", "gif", "png", "bmp", "ico", "tif", "tiff", "svg",
"avi", "divx", "m3u", "mov", "mp3", "mpeg", "mpg", "qt", "vob", "wav", "wma", "wmv",
"flv", "xap", "xaml", "ogg", "mp4", "webm", "eot", "ttf", "woff"
},
DebugAspNetHostEnvironment = Env.IsMono ? "FastCGI" : "IIS7",
DebugHttpListenerHostEnvironment = Env.IsMono ? "XSP" : "WebServer20",
EnableFeatures = Feature.All,
WriteErrorsToResponse = true,
ReturnsInnerException = true,
MarkdownOptions = new MarkdownOptions(),
MarkdownBaseType = typeof(MarkdownViewBase),
MarkdownGlobalHelpers = new Dictionary<string, Type>(),
HtmlReplaceTokens = new Dictionary<string, string>(),
AddMaxAgeForStaticMimeTypes = new Dictionary<string, TimeSpan> {
{ "image/gif", TimeSpan.FromHours(1) },
{ "image/png", TimeSpan.FromHours(1) },
{ "image/jpeg", TimeSpan.FromHours(1) },
},
AppendUtf8CharsetOnContentTypes = new HashSet<string> { ContentType.Json, },
RawHttpHandlers = new List<Func<IHttpRequest, IHttpHandler>>(),
RouteNamingConventions = new List<RouteNamingConventionDelegate> {
RouteNamingConvention.WithRequestDtoName,
RouteNamingConvention.WithMatchingAttributes,
RouteNamingConvention.WithMatchingPropertyNames
},
CustomHttpHandlers = new Dictionary<HttpStatusCode, IServiceStackHttpHandler>(),
GlobalHtmlErrorHttpHandler = null,
MapExceptionToStatusCode = new Dictionary<Type, int>(),
OnlySendSessionCookiesSecurely = false,
RestrictAllCookiesToDomain = null,
DefaultJsonpCacheExpiration = new TimeSpan(0, 20, 0),
MetadataVisibility = EndpointAttributes.Any,
Return204NoContentForEmptyResponse = true,
AllowPartialResponses = true,
IgnoreWarningsOnPropertyNames = new List<string>() {
"format", "callback", "debug", "_"
}
};
if (instance.ServiceStackHandlerFactoryPath == null)
{
InferHttpHandlerPath();
}
}
return instance;
}
}
public EndpointHostConfig(string serviceName, ServiceManager serviceManager)
: this()
{
this.ServiceName = serviceName;
this.ServiceManager = serviceManager;
}
public EndpointHostConfig()
{
if (instance == null) return;
//Get a copy of the singleton already partially configured
this.MetadataTypesConfig = instance.MetadataTypesConfig;
this.WsdlServiceNamespace = instance.WsdlServiceNamespace;
this.WsdlSoapActionNamespace = instance.WsdlSoapActionNamespace;
this.MetadataPageBodyHtml = instance.MetadataPageBodyHtml;
this.MetadataOperationPageBodyHtml = instance.MetadataOperationPageBodyHtml;
this.MetadataCustomPath = instance.MetadataCustomPath;
this.UseCustomMetadataTemplates = instance.UseCustomMetadataTemplates;
this.EnableAccessRestrictions = instance.EnableAccessRestrictions;
this.ServiceEndpointsMetadataConfig = instance.ServiceEndpointsMetadataConfig;
this.LogFactory = instance.LogFactory;
this.EnableAccessRestrictions = instance.EnableAccessRestrictions;
this.WebHostUrl = instance.WebHostUrl;
this.WebHostPhysicalPath = instance.WebHostPhysicalPath;
this.DefaultRedirectPath = instance.DefaultRedirectPath;
this.MetadataRedirectPath = instance.MetadataRedirectPath;
this.ServiceStackHandlerFactoryPath = instance.ServiceStackHandlerFactoryPath;
this.DefaultContentType = instance.DefaultContentType;
this.AllowJsonpRequests = instance.AllowJsonpRequests;
this.AllowRouteContentTypeExtensions = instance.AllowRouteContentTypeExtensions;
this.DebugMode = instance.DebugMode;
this.DefaultDocuments = instance.DefaultDocuments;
this.GlobalResponseHeaders = instance.GlobalResponseHeaders;
this.IgnoreFormatsInMetadata = instance.IgnoreFormatsInMetadata;
this.AllowFileExtensions = instance.AllowFileExtensions;
this.EnableFeatures = instance.EnableFeatures;
this.WriteErrorsToResponse = instance.WriteErrorsToResponse;
this.ReturnsInnerException = instance.ReturnsInnerException;
this.MarkdownOptions = instance.MarkdownOptions;
this.MarkdownBaseType = instance.MarkdownBaseType;
this.MarkdownGlobalHelpers = instance.MarkdownGlobalHelpers;
this.HtmlReplaceTokens = instance.HtmlReplaceTokens;
this.AddMaxAgeForStaticMimeTypes = instance.AddMaxAgeForStaticMimeTypes;
this.AppendUtf8CharsetOnContentTypes = instance.AppendUtf8CharsetOnContentTypes;
this.RawHttpHandlers = instance.RawHttpHandlers;
this.RouteNamingConventions = instance.RouteNamingConventions;
this.CustomHttpHandlers = instance.CustomHttpHandlers;
this.GlobalHtmlErrorHttpHandler = instance.GlobalHtmlErrorHttpHandler;
this.MapExceptionToStatusCode = instance.MapExceptionToStatusCode;
this.OnlySendSessionCookiesSecurely = instance.OnlySendSessionCookiesSecurely;
this.RestrictAllCookiesToDomain = instance.RestrictAllCookiesToDomain;
this.DefaultJsonpCacheExpiration = instance.DefaultJsonpCacheExpiration;
this.MetadataVisibility = instance.MetadataVisibility;
this.Return204NoContentForEmptyResponse = Return204NoContentForEmptyResponse;
this.AllowNonHttpOnlyCookies = instance.AllowNonHttpOnlyCookies;
this.AllowPartialResponses = instance.AllowPartialResponses;
this.IgnoreWarningsOnPropertyNames = instance.IgnoreWarningsOnPropertyNames;
this.PreExecuteServiceFilter = instance.PreExecuteServiceFilter;
this.PostExecuteServiceFilter = instance.PostExecuteServiceFilter;
this.FallbackRestPath = instance.FallbackRestPath;
}
public static string GetAppConfigPath()
{
if (EndpointHost.AppHost == null) return null;
var configPath = "~/web.config".MapHostAbsolutePath();
if (File.Exists(configPath))
return configPath;
configPath = "~/Web.config".MapHostAbsolutePath(); //*nix FS FTW!
if (File.Exists(configPath))
return configPath;
var appHostDll = new FileInfo(EndpointHost.AppHost.GetType().Assembly.Location).Name;
configPath = "~/{0}.config".Fmt(appHostDll).MapAbsolutePath();
return File.Exists(configPath) ? configPath : null;
}
const string NamespacesAppSettingsKey = "servicestack.razor.namespaces";
private static HashSet<string> razorNamespaces;
public static HashSet<string> RazorNamespaces
{
get
{
if (razorNamespaces != null)
return razorNamespaces;
razorNamespaces = new HashSet<string>();
//Infer from <system.web.webPages.razor> - what VS.NET's intell-sense uses
var configPath = GetAppConfigPath();
if (configPath != null)
{
var xml = configPath.ReadAllText();
var doc = XElement.Parse(xml);
doc.AnyElement("system.web.webPages.razor")
.AnyElement("pages")
.AnyElement("namespaces")
.AllElements("add").ToList()
.ForEach(x => razorNamespaces.Add(x.AnyAttribute("namespace").Value));
}
//E.g. <add key="servicestack.razor.namespaces" value="System,ServiceStack.Text" />
if (ConfigUtils.GetNullableAppSetting(NamespacesAppSettingsKey) != null)
{
ConfigUtils.GetListFromAppSetting(NamespacesAppSettingsKey)
.ForEach(x => razorNamespaces.Add(x));
}
//log.Debug("Loaded Razor Namespaces: in {0}: {1}: {2}"
// .Fmt(configPath, "~/Web.config".MapHostAbsolutePath(), razorNamespaces.Dump()));
return razorNamespaces;
}
}
private static System.Configuration.Configuration GetAppConfig()
{
Assembly entryAssembly;
//Read the user-defined path in the Web.Config
if (EndpointHost.AppHost is AppHostBase)
return WebConfigurationManager.OpenWebConfiguration("~/");
if ((entryAssembly = Assembly.GetEntryAssembly()) != null)
return ConfigurationManager.OpenExeConfiguration(entryAssembly.Location);
return null;
}
private static void InferHttpHandlerPath()
{
try
{
var config = GetAppConfig();
if (config == null) return;
SetPathsFromConfiguration(config, null);
if (instance.MetadataRedirectPath == null)
{
foreach (ConfigurationLocation location in config.Locations)
{
SetPathsFromConfiguration(location.OpenConfiguration(), (location.Path ?? "").ToLower());
if (instance.MetadataRedirectPath != null) { break; }
}
}
if (!SkipPathValidation && instance.MetadataRedirectPath == null)
{
throw new ConfigurationErrorsException(
"Unable to infer ServiceStack's <httpHandler.Path/> from the Web.Config\n"
+ "Check with http://www.servicestack.net/ServiceStack.Hello/ to ensure you have configured ServiceStack properly.\n"
+ "Otherwise you can explicitly set your httpHandler.Path by setting: EndpointHostConfig.ServiceStackPath");
}
}
catch (Exception) { }
}
private static void SetPathsFromConfiguration(System.Configuration.Configuration config, string locationPath)
{
if (config == null)
return;
//standard config
var handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection;
if (handlersSection != null)
{
for (var i = 0; i < handlersSection.Handlers.Count; i++)
{
var httpHandler = handlersSection.Handlers[i];
if (!httpHandler.Type.StartsWith("ServiceStack"))
continue;
SetPaths(httpHandler.Path, locationPath);
break;
}
}
//IIS7+ integrated mode system.webServer/handlers
var pathsNotSet = instance.MetadataRedirectPath == null;
if (pathsNotSet)
{
var webServerSection = config.GetSection("system.webServer");
if (webServerSection != null)
{
var rawXml = webServerSection.SectionInformation.GetRawXml();
if (!string.IsNullOrEmpty(rawXml))
{
SetPaths(ExtractHandlerPathFromWebServerConfigurationXml(rawXml), locationPath);
}
}
//In some MVC Hosts auto-inferencing doesn't work, in these cases assume the most likely default of "/api" path
pathsNotSet = instance.MetadataRedirectPath == null;
if (pathsNotSet)
{
var isMvcHost = Type.GetType("System.Web.Mvc.Controller") != null;
if (isMvcHost)
{
SetPaths("api", null);
}
}
}
}
private static void SetPaths(string handlerPath, string locationPath)
{
if (handlerPath == null) return;
if (locationPath == null)
{
handlerPath = handlerPath.Replace("*", String.Empty);
}
instance.ServiceStackHandlerFactoryPath = locationPath ??
(string.IsNullOrEmpty(handlerPath) ? null : handlerPath);
instance.MetadataRedirectPath = PathUtils.CombinePaths(
null != locationPath ? instance.ServiceStackHandlerFactoryPath : handlerPath
, "metadata");
}
private static string ExtractHandlerPathFromWebServerConfigurationXml(string rawXml)
{
return XDocument.Parse(rawXml).Root.Element("handlers")
.Descendants("add")
.Where(handler => EnsureHandlerTypeAttribute(handler).StartsWith("ServiceStack"))
.Select(handler => handler.Attribute("path").Value)
.FirstOrDefault();
}
private static string EnsureHandlerTypeAttribute(XElement handler)
{
if (handler.Attribute("type") != null && !string.IsNullOrEmpty(handler.Attribute("type").Value))
{
return handler.Attribute("type").Value;
}
return string.Empty;
}
public ServiceManager ServiceManager { get; internal set; }
public ServiceMetadata Metadata { get { return ServiceManager.Metadata; } }
public IServiceController ServiceController { get { return ServiceManager.ServiceController; } }
public MetadataTypesConfig MetadataTypesConfig { get; set; }
public string WsdlServiceNamespace { get; set; }
public string WsdlSoapActionNamespace { get; set; }
private EndpointAttributes metadataVisibility;
public EndpointAttributes MetadataVisibility
{
get { return metadataVisibility; }
set { metadataVisibility = value.ToAllowedFlagsSet(); }
}
public string MetadataPageBodyHtml { get; set; }
public string MetadataOperationPageBodyHtml { get; set; }
public string MetadataCustomPath { get; set; }
public bool UseCustomMetadataTemplates { get; set; }
public string ServiceName { get; set; }
public string DefaultContentType { get; set; }
public bool AllowJsonpRequests { get; set; }
public bool AllowRouteContentTypeExtensions { get; set; }
public bool DebugMode { get; set; }
public bool DebugOnlyReturnRequestInfo { get; set; }
public string DebugAspNetHostEnvironment { get; set; }
public string DebugHttpListenerHostEnvironment { get; set; }
public List<string> DefaultDocuments { get; private set; }
public List<string> IgnoreWarningsOnPropertyNames { get; private set; }
public HashSet<string> IgnoreFormatsInMetadata { get; set; }
public HashSet<string> AllowFileExtensions { get; set; }
public string WebHostUrl { get; set; }
public string WebHostPhysicalPath { get; set; }
public string ServiceStackHandlerFactoryPath { get; set; }
public string DefaultRedirectPath { get; set; }
public string MetadataRedirectPath { get; set; }
public ServiceEndpointsMetadataConfig ServiceEndpointsMetadataConfig { get; set; }
public ILogFactory LogFactory { get; set; }
public bool EnableAccessRestrictions { get; set; }
public bool UseBclJsonSerializers { get; set; }
public Dictionary<string, string> GlobalResponseHeaders { get; set; }
public Feature EnableFeatures { get; set; }
public bool ReturnsInnerException { get; set; }
public bool WriteErrorsToResponse { get; set; }
public MarkdownOptions MarkdownOptions { get; set; }
public Type MarkdownBaseType { get; set; }
public Dictionary<string, Type> MarkdownGlobalHelpers { get; set; }
public Dictionary<string, string> HtmlReplaceTokens { get; set; }
public HashSet<string> AppendUtf8CharsetOnContentTypes { get; set; }
public Dictionary<string, TimeSpan> AddMaxAgeForStaticMimeTypes { get; set; }
public List<Func<IHttpRequest, IHttpHandler>> RawHttpHandlers { get; set; }
public List<RouteNamingConventionDelegate> RouteNamingConventions { get; set; }
public Dictionary<HttpStatusCode, IServiceStackHttpHandler> CustomHttpHandlers { get; set; }
public IServiceStackHttpHandler GlobalHtmlErrorHttpHandler { get; set; }
public Dictionary<Type, int> MapExceptionToStatusCode { get; set; }
public bool OnlySendSessionCookiesSecurely { get; set; }
public string RestrictAllCookiesToDomain { get; set; }
public TimeSpan DefaultJsonpCacheExpiration { get; set; }
public bool Return204NoContentForEmptyResponse { get; set; }
public bool AllowPartialResponses { get; set; }
public bool AllowNonHttpOnlyCookies { get; set; }
public bool UseHttpsLinks { get; set; }
private string defaultOperationNamespace;
public string DefaultOperationNamespace
{
get
{
if (this.defaultOperationNamespace == null)
{
this.defaultOperationNamespace = GetDefaultNamespace();
}
return this.defaultOperationNamespace;
}
set
{
this.defaultOperationNamespace = value;
}
}
private string GetDefaultNamespace()
{
if (!String.IsNullOrEmpty(this.defaultOperationNamespace)
|| this.ServiceController == null) return null;
foreach (var operationType in this.Metadata.RequestTypes)
{
var attrs = operationType.GetCustomAttributes(
typeof(DataContractAttribute), false);
if (attrs.Length <= 0) continue;
var attr = (DataContractAttribute)attrs[0];
if (String.IsNullOrEmpty(attr.Namespace)) continue;
return attr.Namespace;
}
return null;
}
public bool HasFeature(Feature feature)
{
return (feature & EndpointHost.Config.EnableFeatures) == feature;
}
public void AssertFeatures(Feature usesFeatures)
{
if (EndpointHost.Config.EnableFeatures == Feature.All) return;
if (!HasFeature(usesFeatures))
{
throw new UnauthorizedAccessException(
String.Format("'{0}' Features have been disabled by your administrator", usesFeatures));
}
}
public UnauthorizedAccessException UnauthorizedAccess(EndpointAttributes requestAttrs)
{
return new UnauthorizedAccessException(
String.Format("Request with '{0}' is not allowed", requestAttrs));
}
public void AssertContentType(string contentType)
{
if (EndpointHost.Config.EnableFeatures == Feature.All) return;
var contentTypeFeature = ContentType.ToFeature(contentType);
AssertFeatures(contentTypeFeature);
}
public MetadataPagesConfig MetadataPagesConfig
{
get
{
return new MetadataPagesConfig(
Metadata,
ServiceEndpointsMetadataConfig,
IgnoreFormatsInMetadata,
EndpointHost.ContentTypeFilter.ContentTypeFormats.Keys.ToList());
}
}
public bool HasAccessToMetadata(IHttpRequest httpReq, IHttpResponse httpRes)
{
if (!HasFeature(Feature.Metadata))
{
EndpointHost.Config.HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Metadata Not Available");
return false;
}
if (MetadataVisibility != EndpointAttributes.Any)
{
var actualAttributes = httpReq.GetAttributes();
if ((actualAttributes & MetadataVisibility) != MetadataVisibility)
{
HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Metadata Not Visible");
return false;
}
}
return true;
}
public void HandleErrorResponse(IHttpRequest httpReq, IHttpResponse httpRes, HttpStatusCode errorStatus, string errorStatusDescription=null)
{
if (httpRes.IsClosed) return;
httpRes.StatusDescription = errorStatusDescription;
var handler = GetHandlerForErrorStatus(errorStatus);
handler.ProcessRequest(httpReq, httpRes, httpReq.OperationName);
}
public IServiceStackHttpHandler GetHandlerForErrorStatus(HttpStatusCode errorStatus)
{
var httpHandler = GetCustomErrorHandler(errorStatus);
switch (errorStatus)
{
case HttpStatusCode.Forbidden:
return httpHandler ?? new ForbiddenHttpHandler();
case HttpStatusCode.NotFound:
return httpHandler ?? new NotFoundHttpHandler();
}
if (CustomHttpHandlers != null)
{
CustomHttpHandlers.TryGetValue(HttpStatusCode.NotFound, out httpHandler);
}
return httpHandler ?? new NotFoundHttpHandler();
}
public IServiceStackHttpHandler GetCustomErrorHandler(int errorStatusCode)
{
try
{
return GetCustomErrorHandler((HttpStatusCode) errorStatusCode);
}
catch
{
return null;
}
}
public IServiceStackHttpHandler GetCustomErrorHandler(HttpStatusCode errorStatus)
{
IServiceStackHttpHandler httpHandler = null;
if (CustomHttpHandlers != null)
{
CustomHttpHandlers.TryGetValue(errorStatus, out httpHandler);
}
return httpHandler ?? GlobalHtmlErrorHttpHandler;
}
public IHttpHandler GetCustomErrorHttpHandler(HttpStatusCode errorStatus)
{
var ssHandler = GetCustomErrorHandler(errorStatus);
if (ssHandler == null) return null;
var httpHandler = ssHandler as IHttpHandler;
return httpHandler ?? new ServiceStackHttpHandler(ssHandler);
}
public Action<object, IHttpRequest, IHttpResponse> PreExecuteServiceFilter { get; set; }
public Action<object, IHttpRequest, IHttpResponse> PostExecuteServiceFilter { get; set; }
public FallbackRestPathDelegate FallbackRestPath { get; set; }
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SpatialAnalysis.FieldUtility;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using SpatialAnalysis.Events;
using SpatialAnalysis.Miscellaneous;
namespace SpatialAnalysis.Data.Visualization
{
/// <summary>
/// Class GaussianFilterUI.
/// </summary>
/// <seealso cref="System.Windows.Window" />
public partial class GaussianFilterUI : Window
{
#region _host Definition
private static DependencyProperty _hostProperty =
DependencyProperty.Register("_host", typeof(OSMDocument), typeof(GaussianFilterUI),
new FrameworkPropertyMetadata(null, _hostPropertyChanged, _propertyCoerce));
private OSMDocument _host
{
get { return (OSMDocument)GetValue(_hostProperty); }
set { SetValue(_hostProperty, value); }
}
private static void _hostPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
GaussianFilterUI createTrail = (GaussianFilterUI)obj;
createTrail._host = (OSMDocument)args.NewValue;
}
private static object _propertyCoerce(DependencyObject obj, object value)
{
return value;
}
#endregion
#region Hiding the close button
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
private void GuassianFilterUI_Loaded(object sender, RoutedEventArgs e)
{
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="GaussianFilterUI"/> class.
/// </summary>
/// <param name="host">The main document to which this window belongs</param>
public GaussianFilterUI(OSMDocument host)
{
InitializeComponent();
this._host = host;
this.Owner = this._host;
TextBlock cellularDataNames = new TextBlock()
{
Text = "Data".ToUpper(),
FontSize = 14,
FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.DarkGray)
};
this.dataNames.Items.Add(cellularDataNames);
foreach (Function item in this._host.cellularFloor.AllSpatialDataFields.Values)
{
SpatialDataField data = item as SpatialDataField;
if (data != null)
{
this.dataNames.Items.Add(data);
}
}
TextBlock fieldNames = new TextBlock()
{
Text = "Activity".ToUpper(),
FontSize = 14,
FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.DarkGray)
};
if (this._host.AllActivities.Count > 0)
{
this.dataNames.Items.Add(fieldNames);
foreach (KeyValuePair<string, Activity> item in this._host.AllActivities)
{
this.dataNames.Items.Add(item.Value);
}
}
TextBlock eventNames = new TextBlock
{
Text = "Occupancy Events".ToUpper(),
FontSize = 14,
FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.DarkGray)
};
if (this._host.AllOccupancyEvent.Count > 0)
{
this.dataNames.Items.Add(eventNames);
foreach (SpatialAnalysis.Events.EvaluationEvent item in this._host.AllOccupancyEvent.Values)
{
this.dataNames.Items.Add(item);
}
}
TextBlock simulationNames = new TextBlock
{
Text = "Simulation Results".ToUpper(),
FontSize = 14,
FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.DarkGray)
};
if (this._host.AllSimulationResults.Count > 0)
{
this.dataNames.Items.Add(simulationNames);
foreach (SimulationResult item in this._host.AllSimulationResults.Values)
{
this.dataNames.Items.Add(item);
}
}
if (this._host.ViewBasedGaussianFilter != null)
{
this._range.Text = this._host.ViewBasedGaussianFilter.Range.ToString();
}
this.Loaded += GuassianFilterUI_Loaded;
this.dataNames.SelectionChanged += dataNames_SelectionChanged;
this._apply.Click += _apply_Click;
this._cancel.Click += _cancel_Click;
this.dataNames.SelectionChanged += DataNames_SelectionChanged;
}
private void DataNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.dataNames.SelectedIndex != -1)
{
try
{
this._name.Text = dataNames.SelectedItem.ToString();
}
catch (Exception error)
{
MessageBox.Show(error.Report());
}
}
}
void dataNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.dataNames.SelectionChanged -= dataNames_SelectionChanged;
try
{
TextBlock selected = this.dataNames.SelectedItem as TextBlock;
if (selected != null)
{
this.dataNames.SelectedIndex = -1;
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
this.dataNames.SelectionChanged += dataNames_SelectionChanged;
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
this.dataNames.SelectionChanged -= dataNames_SelectionChanged;
this._apply.Click -= _apply_Click;
this._cancel.Click -= _cancel_Click;
this.dataNames.Items.Clear();
this.Loaded -= GuassianFilterUI_Loaded;
base.OnClosing(e);
}
void _cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
void _apply_Click(object sender, RoutedEventArgs e)
{
#region input validation
double _n = 0;
if (!double.TryParse(this._range.Text, out _n))
{
MessageBox.Show("'Neighborhood Size' should be a valid number larger than 0",
"Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
int n = (int)_n;
if (n < 1)
{
MessageBox.Show("'Neighborhood Size' should be a valid number larger than 0",
"Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
if (this.dataNames.SelectedIndex == -1)
{
MessageBox.Show("Select a data field to continue",
"Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
ISpatialData data = this.dataNames.SelectedItem as ISpatialData;
if (data == null)
{
MessageBox.Show("Cannot cast selection to data!");
return;
}
if (string.IsNullOrEmpty(this._name.Text) || string.IsNullOrWhiteSpace(this._name.Text))
{
MessageBox.Show("Enter a name for the new data field",
"Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
switch (data.Type)
{
case DataType.SpatialData:
if (this._host.cellularFloor.AllSpatialDataFields.ContainsKey(this._name.Text))
{
MessageBox.Show("A spatial data field with the given name Already exists.\n Change the name to continue", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
break;
case DataType.ActivityPotentialField:
if (this._host.AllActivities.ContainsKey(this._name.Text))
{
MessageBox.Show("An activity with the given name Already exists.\n Change the name to continue", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
break;
case DataType.OccupancyEvent:
if (this._host.AllOccupancyEvent.ContainsKey(this._name.Text))
{
MessageBox.Show("An occupancy even with the given name Already exists.\n Change the name to continue", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
break;
case DataType.SimulationResult:
if (this._host.AllSimulationResults.ContainsKey(this._name.Text))
{
MessageBox.Show("An simulation result with the given name Already exists.\n Change the name to continue", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
break;
}
#endregion
//update filter
if (this._host.ViewBasedGaussianFilter != null)
{
if (this._host.ViewBasedGaussianFilter.Range != n)
{
try
{
this._host.ViewBasedGaussianFilter = new IsovistClippedGaussian(this._host.cellularFloor, n);
}
catch (Exception error)
{
MessageBox.Show(error.Report(), "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
}
}
else
{
try
{
this._host.ViewBasedGaussianFilter = new IsovistClippedGaussian(this._host.cellularFloor, n);
}
catch (Exception error)
{
MessageBox.Show(error.Report(), "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
}
try
{
//apply filter
ISpatialData filteredData = this._host.ViewBasedGaussianFilter.ApplyParallel(data, this._name.Text);
//ISpatialData filteredData = this._host.GaussianFilter.Apply(data, this._name.Text);
//add new data to the document
switch (filteredData.Type)
{
case DataType.SpatialData:
this._host.cellularFloor.AddSpatialDataField(filteredData as SpatialDataField);
break;
case DataType.ActivityPotentialField:
this._host.AddActivity(filteredData as Activity);
break;
case DataType.OccupancyEvent:
this._host.AllOccupancyEvent.Add(filteredData.Name, filteredData as EvaluationEvent);
break;
case DataType.SimulationResult:
this._host.AllSimulationResults.Add(filteredData.Name, filteredData as SimulationResult);
break;
}
}
catch (Exception error2)
{
MessageBox.Show(error2.Report(),"Exception!", MessageBoxButton.OK, MessageBoxImage.Error);
}
this.Close();
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using tk2dRuntime.TileMap;
[System.Flags]
public enum tk2dTileFlags {
None = 0x00000000,
FlipX = 0x01000000,
FlipY = 0x02000000,
Rot90 = 0x04000000,
}
[ExecuteInEditMode]
[AddComponentMenu("2D Toolkit/TileMap/TileMap")]
/// <summary>
/// Tile Map
/// </summary>
public class tk2dTileMap : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild
{
/// <summary>
/// This is a link to the editor data object (tk2dTileMapEditorData).
/// It contains presets, and other data which isn't really relevant in game.
/// </summary>
public string editorDataGUID = "";
/// <summary>
/// Tile map data, stores shared parameters for tilemaps
/// </summary>
public tk2dTileMapData data;
/// <summary>
/// Tile map render and collider object
/// </summary>
public GameObject renderData;
/// <summary>
/// The sprite collection used by the tilemap
/// </summary>
[SerializeField]
private tk2dSpriteCollectionData spriteCollection = null;
public tk2dSpriteCollectionData Editor__SpriteCollection
{
get
{
return spriteCollection;
}
set
{
_spriteCollectionInst = null;
spriteCollection = value;
if (spriteCollection != null)
_spriteCollectionInst = spriteCollection.inst;
}
}
tk2dSpriteCollectionData _spriteCollectionInst = null;
public tk2dSpriteCollectionData SpriteCollectionInst
{
get
{
if (_spriteCollectionInst == null && spriteCollection != null)
_spriteCollectionInst = spriteCollection.inst;
return _spriteCollectionInst;
}
}
[SerializeField]
int spriteCollectionKey;
/// <summary>Width of the tilemap</summary>
public int width = 128;
/// <summary>Height of the tilemap</summary>
public int height = 128;
/// <summary>X axis partition size for this tilemap</summary>
public int partitionSizeX = 32;
/// <summary>Y axis partition size for this tilemap</summary>
public int partitionSizeY = 32;
[SerializeField]
Layer[] layers;
[SerializeField]
ColorChannel colorChannel;
[SerializeField]
GameObject prefabsRoot;
[System.Serializable]
public class TilemapPrefabInstance {
public int x, y, layer;
public GameObject instance;
}
[SerializeField]
List<TilemapPrefabInstance> tilePrefabsList = new List<TilemapPrefabInstance>();
[SerializeField]
bool _inEditMode = false;
public bool AllowEdit { get { return _inEditMode; } }
// holds a path to a serialized mesh, uses this to work out dump directory for meshes
public string serializedMeshPath;
void Awake()
{
if (spriteCollection != null)
_spriteCollectionInst = spriteCollection.inst;
bool spriteCollectionKeyMatch = true;
if (SpriteCollectionInst && SpriteCollectionInst.buildKey != spriteCollectionKey) spriteCollectionKeyMatch = false;
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.OSXEditor)
{
if ((Application.isPlaying && _inEditMode == true) || !spriteCollectionKeyMatch)
{
// Switched to edit mode while still in edit mode, rebuild
EndEditMode();
}
}
else
{
if (_inEditMode == true)
{
Debug.LogError("Tilemap " + name + " is still in edit mode. Please fix." +
"Building overhead will be significant.");
EndEditMode();
}
else if (!spriteCollectionKeyMatch)
{
Build(BuildFlags.ForceBuild);
}
}
}
#if UNITY_EDITOR
void OnDrawGizmos() {
if (data != null) {
Vector3 p0 = data.tileOrigin;
Vector3 p1 = new Vector3(p0.x + data.tileSize.x * width, p0.y + data.tileSize.y * height, 0.0f);
Gizmos.color = Color.clear;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawCube((p0 + p1) * 0.5f, (p1 - p0));
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = Color.white;
}
}
#endif
[System.Flags]
public enum BuildFlags {
Default = 0,
EditMode = 1,
ForceBuild = 2
};
/// <summary>
/// Builds the tilemap. Call this after using the SetTile functions to
/// rebuild the affected partitions. Build only rebuilds affected partitions
/// and is efficent enough to use at runtime if you don't use Unity colliders.
/// Avoid building tilemaps every frame if you use Unity colliders as it will
/// likely be too slow for runtime use.
/// </summary>
public void Build() { Build(BuildFlags.Default); }
/// <summary>
/// Like <see cref="T:Build"/> above, but forces a build of all partitions.
/// </summary>
public void ForceBuild() { Build(BuildFlags.ForceBuild); }
// Clears all spawned instances, but retains the renderData object
void ClearSpawnedInstances()
{
if (layers == null)
return;
for (int layerIdx = 0; layerIdx < layers.Length; ++layerIdx)
{
Layer layer = layers[layerIdx];
for (int chunkIdx = 0; chunkIdx < layer.spriteChannel.chunks.Length; ++chunkIdx)
{
var chunk = layer.spriteChannel.chunks[chunkIdx];
if (chunk.gameObject == null)
continue;
var transform = chunk.gameObject.transform;
List<Transform> children = new List<Transform>();
for (int i = 0; i < transform.childCount; ++i)
children.Add(transform.GetChild(i));
for (int i = 0; i < children.Count; ++i)
DestroyImmediate(children[i].gameObject);
}
}
}
void SetPrefabsRootActive(bool active) {
if (prefabsRoot != null)
#if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9
prefabsRoot.SetActiveRecursively(active);
#else
prefabsRoot.SetActive(active);
#endif
}
public void Build(BuildFlags buildFlags)
{
if (spriteCollection != null)
_spriteCollectionInst = spriteCollection.inst;
#if UNITY_EDITOR || !UNITY_FLASH
// Sanitize tilePrefabs input, to avoid branches later
if (data != null && spriteCollection != null)
{
if (data.tilePrefabs == null)
data.tilePrefabs = new Object[SpriteCollectionInst.Count];
else if (data.tilePrefabs.Length != SpriteCollectionInst.Count)
System.Array.Resize(ref data.tilePrefabs, SpriteCollectionInst.Count);
// Fix up data if necessary
BuilderUtil.InitDataStore(this);
}
else
{
return;
}
// Sanitize sprite collection material ids
if (SpriteCollectionInst)
SpriteCollectionInst.InitMaterialIds();
bool forceBuild = (buildFlags & BuildFlags.ForceBuild) != 0;
// When invalid, everything needs to be rebuilt
if (SpriteCollectionInst && SpriteCollectionInst.buildKey != spriteCollectionKey)
forceBuild = true;
if (forceBuild)
ClearSpawnedInstances();
BuilderUtil.CreateRenderData(this, _inEditMode);
RenderMeshBuilder.Build(this, _inEditMode, forceBuild);
if (!_inEditMode)
{
ColliderBuilder.Build(this, forceBuild);
BuilderUtil.SpawnPrefabs(this, forceBuild);
}
// Clear dirty flag on everything
foreach (var layer in layers)
layer.ClearDirtyFlag();
if (colorChannel != null)
colorChannel.ClearDirtyFlag();
// Update sprite collection key
if (SpriteCollectionInst)
spriteCollectionKey = SpriteCollectionInst.buildKey;
#endif
}
/// <summary>
/// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers
/// Returns true if the position is within the tilemap bounds
/// </summary>
public bool GetTileAtPosition(Vector3 position, out int x, out int y)
{
float ox, oy;
bool b = GetTileFracAtPosition(position, out ox, out oy);
x = (int)ox;
y = (int)oy;
return b;
}
/// <summary>
/// Gets the tile coordinate at position. This can be used to obtain tile or color data explicitly from layers
/// The fractional value returned is the fraction into the current tile
/// Returns true if the position is within the tilemap bounds
/// </summary>
public bool GetTileFracAtPosition(Vector3 position, out float x, out float y)
{
switch (data.tileType)
{
case tk2dTileMapData.TileType.Rectangular:
{
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x;
y = (localPosition.y - data.tileOrigin.y) / data.tileSize.y;
return (x >= 0 && x <= width && y >= 0 && y <= height);
}
case tk2dTileMapData.TileType.Isometric:
{
if (data.tileSize.x == 0.0f)
break;
float tileAngle = Mathf.Atan2(data.tileSize.y, data.tileSize.x / 2.0f);
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
x = (localPosition.x - data.tileOrigin.x) / data.tileSize.x;
y = ((localPosition.y - data.tileOrigin.y) / (data.tileSize.y));
float fy = y * 0.5f;
int iy = (int)fy;
float fry = fy - iy;
float frx = x % 1.0f;
x = (int)x;
y = iy * 2;
if (frx > 0.5f)
{
if (fry > 0.5f && Mathf.Atan2(1.0f - fry, (frx - 0.5f) * 2) < tileAngle)
y += 1;
else if (fry < 0.5f && Mathf.Atan2(fry, (frx - 0.5f) * 2) < tileAngle)
y -= 1;
}
else if (frx < 0.5f)
{
if (fry > 0.5f && Mathf.Atan2(fry - 0.5f, frx * 2) > tileAngle)
{
y += 1;
x -= 1;
}
if (fry < 0.5f && Mathf.Atan2(fry, (0.5f - frx) * 2) < tileAngle)
{
y -= 1;
x -= 1;
}
}
return (x >= 0 && x <= width && y >= 0 && y <= height);
}
}
x = 0.0f;
y = 0.0f;
return false;
}
/// <summary>
/// Returns the tile position in world space
/// </summary>
public Vector3 GetTilePosition(int x, int y)
{
switch (data.tileType)
{
case tk2dTileMapData.TileType.Rectangular:
default:
{
Vector3 localPosition = new Vector3(
x * data.tileSize.x + data.tileOrigin.x,
y * data.tileSize.y + data.tileOrigin.y,
0);
return transform.localToWorldMatrix.MultiplyPoint(localPosition);
}
case tk2dTileMapData.TileType.Isometric:
{
Vector3 localPosition = new Vector3(
((float)x + (((y & 1) == 0) ? 0.0f : 0.5f)) * data.tileSize.x + data.tileOrigin.x,
y * data.tileSize.y + data.tileOrigin.y,
0);
return transform.localToWorldMatrix.MultiplyPoint(localPosition);
}
}
}
/// <summary>
/// Gets the tile at position. This can be used to obtain tile data, etc
/// -1 = no data or empty tile
/// </summary>
public int GetTileIdAtPosition(Vector3 position, int layer)
{
if (layer < 0 || layer >= layers.Length)
return -1;
int x, y;
if (!GetTileAtPosition(position, out x, out y))
return -1;
return layers[layer].GetTile(x, y);
}
/// <summary>
/// Returns the tile info chunk for the tile. Use this to store additional metadata
/// </summary>
public tk2dRuntime.TileMap.TileInfo GetTileInfoForTileId(int tileId)
{
return data.GetTileInfoForSprite(tileId);
}
/// <summary>
/// Gets the tile at position. This can be used to obtain tile data, etc
/// -1 = no data or empty tile
/// </summary>
public Color GetInterpolatedColorAtPosition(Vector3 position)
{
Vector3 localPosition = transform.worldToLocalMatrix.MultiplyPoint(position);
int x = (int)((localPosition.x - data.tileOrigin.x) / data.tileSize.x);
int y = (int)((localPosition.y - data.tileOrigin.y) / data.tileSize.y);
if (colorChannel == null || colorChannel.IsEmpty)
return Color.white;
if (x < 0 || x >= width ||
y < 0 || y >= height)
{
return colorChannel.clearColor;
}
int offset;
ColorChunk colorChunk = colorChannel.FindChunkAndCoordinate(x, y, out offset);
if (colorChunk.Empty)
{
return colorChannel.clearColor;
}
else
{
int colorChunkRowOffset = partitionSizeX + 1;
Color tileColorx0y0 = colorChunk.colors[offset];
Color tileColorx1y0 = colorChunk.colors[offset + 1];
Color tileColorx0y1 = colorChunk.colors[offset + colorChunkRowOffset];
Color tileColorx1y1 = colorChunk.colors[offset + colorChunkRowOffset + 1];
float wx = x * data.tileSize.x + data.tileOrigin.x;
float wy = y * data.tileSize.y + data.tileOrigin.y;
float ix = (localPosition.x - wx) / data.tileSize.x;
float iy = (localPosition.y - wy) / data.tileSize.y;
Color cy0 = Color.Lerp(tileColorx0y0, tileColorx1y0, ix);
Color cy1 = Color.Lerp(tileColorx0y1, tileColorx1y1, ix);
return Color.Lerp(cy0, cy1, iy);
}
}
// ISpriteCollectionBuilder
public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection)
{
return spriteCollection == this.spriteCollection || _spriteCollectionInst == spriteCollection;
}
// We might need to end edit mode when running in game
public void EndEditMode()
{
_inEditMode = false;
SetPrefabsRootActive(true);
Build(BuildFlags.ForceBuild);
if (prefabsRoot != null) {
GameObject.DestroyImmediate(prefabsRoot);
prefabsRoot = null;
}
}
#if UNITY_EDITOR
public void BeginEditMode()
{
if (layers == null) {
_inEditMode = true;
return;
}
if (!_inEditMode) {
_inEditMode = true;
// Destroy all children
// Only necessary when switching INTO edit mode
BuilderUtil.HideTileMapPrefabs(this);
SetPrefabsRootActive(false);
}
Build(BuildFlags.ForceBuild);
}
public bool AreSpritesInitialized()
{
return layers != null;
}
public bool HasColorChannel()
{
return (colorChannel != null && !colorChannel.IsEmpty);
}
public void CreateColorChannel()
{
colorChannel = new ColorChannel(width, height, partitionSizeX, partitionSizeY);
colorChannel.Create();
}
public void DeleteColorChannel()
{
colorChannel.Delete();
}
public void DeleteSprites(int layerId, int x0, int y0, int x1, int y1)
{
x0 = Mathf.Clamp(x0, 0, width - 1);
y0 = Mathf.Clamp(y0, 0, height - 1);
x1 = Mathf.Clamp(x1, 0, width - 1);
y1 = Mathf.Clamp(y1, 0, height - 1);
int numTilesX = x1 - x0 + 1;
int numTilesY = y1 - y0 + 1;
var layer = layers[layerId];
for (int y = 0; y < numTilesY; ++y)
{
for (int x = 0; x < numTilesX; ++x)
{
layer.SetTile(x0 + x, y0 + y, -1);
}
}
layer.OptimizeIncremental();
}
#endif
public void TouchMesh(Mesh mesh)
{
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(mesh);
#endif
}
public void DestroyMesh(Mesh mesh)
{
#if UNITY_EDITOR
if (UnityEditor.AssetDatabase.GetAssetPath(mesh).Length != 0)
{
mesh.Clear();
UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(mesh));
}
else
{
DestroyImmediate(mesh);
}
#else
DestroyImmediate(mesh);
#endif
}
public int GetTilePrefabsListCount() {
return tilePrefabsList.Count;
}
public List<TilemapPrefabInstance> TilePrefabsList {
get {
return tilePrefabsList;
}
}
public void GetTilePrefabsListItem(int index, out int x, out int y, out int layer, out GameObject instance) {
TilemapPrefabInstance item = tilePrefabsList[index];
x = item.x;
y = item.y;
layer = item.layer;
instance = item.instance;
}
public void SetTilePrefabsList(List<int> xs, List<int> ys, List<int> layers, List<GameObject> instances) {
int n = instances.Count;
tilePrefabsList = new List<TilemapPrefabInstance>(n);
for (int i = 0; i < n; ++i) {
TilemapPrefabInstance item = new TilemapPrefabInstance();
item.x = xs[i];
item.y = ys[i];
item.layer = layers[i];
item.instance = instances[i];
tilePrefabsList.Add(item);
}
}
/// <summary>
/// Gets or sets the layers.
/// </summary>
public Layer[] Layers
{
get { return layers; }
set { layers = value; }
}
/// <summary>
/// Gets or sets the color channel.
/// </summary>
public ColorChannel ColorChannel
{
get { return colorChannel; }
set { colorChannel = value; }
}
/// <summary>
/// Gets or sets the prefabs root.
/// </summary>
public GameObject PrefabsRoot
{
get { return prefabsRoot; }
set { prefabsRoot = value; }
}
/// <summary>Gets the tile on a layer at x, y</summary>
/// <returns>The tile - either a sprite Id or -1 if the tile is empty.</returns>
public int GetTile(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return -1;
return layers[layer].GetTile(x, y);
}
/// <summary>Gets the tile flags on a layer at x, y</summary>
/// <returns>The tile flags - a combination of tk2dTileFlags</returns>
public tk2dTileFlags GetTileFlags(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return tk2dTileFlags.None;
return layers[layer].GetTileFlags(x, y);
}
/// <summary>Sets the tile on a layer at x, y - either a sprite Id or -1 if the tile is empty.</summary>
public void SetTile(int x, int y, int layer, int tile) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].SetTile(x, y, tile);
}
/// <summary>Sets the tile flags on a layer at x, y - a combination of tk2dTileFlags</summary>
public void SetTileFlags(int x, int y, int layer, tk2dTileFlags flags) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].SetTileFlags(x, y, flags);
}
/// <summary>Clears the tile on a layer at x, y</summary>
public void ClearTile(int x, int y, int layer) {
if (layer < 0 || layer >= layers.Length)
return;
layers[layer].ClearTile(x, y);
}
}
| |
// 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 Microsoft.Azure.Management.ServiceBus
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.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;
/// <summary>
/// PremiumMessagingRegionsOperations operations.
/// </summary>
internal partial class PremiumMessagingRegionsOperations : IServiceOperations<ServiceBusManagementClient>, IPremiumMessagingRegionsOperations
{
/// <summary>
/// Initializes a new instance of the PremiumMessagingRegionsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PremiumMessagingRegionsOperations(ServiceBusManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ServiceBusManagementClient
/// </summary>
public ServiceBusManagementClient Client { get; private set; }
/// <summary>
/// Gets the available premium messaging regions for servicebus
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<PremiumMessagingRegions>>> 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}/providers/Microsoft.ServiceBus/premiumMessagingRegions").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 HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PremiumMessagingRegions>>();
_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<PremiumMessagingRegions>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the available premium messaging regions for servicebus
/// </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="ErrorResponseException">
/// 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<PremiumMessagingRegions>>> 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 HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PremiumMessagingRegions>>();
_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<PremiumMessagingRegions>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using GeneticSharp.Extensions.Checkers;
using NUnit.Framework;
namespace GeneticSharp.Extensions.UnitTests.Checkers
{
[TestFixture()]
[Category("Extensions")]
public class CheckersBoardTest
{
[Test()]
public void Constructos_InvalidSize_Exception()
{
Assert.Catch<ArgumentException>(() =>
{
new CheckersBoard(7);
}, "The minimum valid size is 8.");
Assert.Catch<ArgumentException>(() =>
{
new CheckersBoard(-8);
}, "The minimum valid size is 8.");
}
[Test()]
public void Contructor_ValidSize_PlayerOnePiecedPlaced()
{
var target = new CheckersBoard(8);
Assert.AreEqual(8, target.Size);
// First row.
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(1, 0).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(3, 0).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(5, 0).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(7, 0).State);
// second row
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(0, 1).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(2, 1).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(4, 1).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(6, 1).State);
// third row
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(1, 2).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(3, 2).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(5, 2).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerOne, target.GetSquare(7, 2).State);
}
[Test()]
public void Contructor_ValidSize_PlayerTwoPiecedPlaced()
{
var target = new CheckersBoard(8);
Assert.AreEqual(8, target.Size);
// first row.
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(0, 7).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(2, 7).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(4, 7).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(6, 7).State);
// second row
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(1, 6).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(3, 6).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(5, 6).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(7, 6).State);
// third row
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(0, 5).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(2, 5).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(4, 5).State);
Assert.AreEqual(CheckersSquareState.OccupiedByPlayerTwo, target.GetSquare(6, 5).State);
}
[Test()]
public void Contructor_ValidSize_FreeAndNotPlayableSquaresOk()
{
var target = new CheckersBoard(8);
Assert.AreEqual(8, target.Size);
for (int c = 0; c < 8; c++)
{
for (int r = 0; r < 8; r++)
{
var notPlayable = CheckersSquare.IsNotPlayableSquare(c, r);
var actual = target.GetSquare(c, r).State;
if (notPlayable)
{
Assert.AreEqual(CheckersSquareState.NotPlayable, actual);
}
else
{
Assert.AreNotEqual(CheckersSquareState.NotPlayable, actual);
}
}
}
}
[Test]
public void IsNotPlayableSquare_DiffSquares_DiffResults()
{
Assert.IsTrue(CheckersSquare.IsNotPlayableSquare(0, 0));
Assert.IsFalse(CheckersSquare.IsNotPlayableSquare(0, 1));
Assert.IsTrue(CheckersSquare.IsNotPlayableSquare(0, 2));
Assert.IsFalse(CheckersSquare.IsNotPlayableSquare(1, 0));
Assert.IsTrue(CheckersSquare.IsNotPlayableSquare(1, 1));
Assert.IsFalse(CheckersSquare.IsNotPlayableSquare(1, 2));
}
[Test()]
public void GetSize_InvalidIndexes_Exception()
{
var target = new CheckersBoard(10);
var actual = Assert.Catch<ArgumentOutOfRangeException>(() =>
{
target.GetSquare(-1, 0);
});
Assert.AreEqual("columnIndex", actual.ParamName);
actual = Assert.Catch<ArgumentOutOfRangeException>(() =>
{
target.GetSquare(10, 0);
});
Assert.AreEqual("columnIndex", actual.ParamName);
actual = Assert.Catch<ArgumentOutOfRangeException>(() =>
{
target.GetSquare(0, -1);
});
Assert.AreEqual("rowIndex", actual.ParamName);
actual = Assert.Catch<ArgumentOutOfRangeException>(() =>
{
target.GetSquare(0, 10);
});
Assert.AreEqual("rowIndex", actual.ParamName);
}
[Test()]
public void MovePiece_NullMove_Exception()
{
var target = new CheckersBoard(10);
var actual = Assert.Catch<ArgumentNullException>(() =>
{
target.MovePiece(null);
});
Assert.AreEqual("move", actual.ParamName);
}
[Test()]
public void MovePiece_InvalidMove_False()
{
var target = new CheckersBoard(8);
// Horizontal move.
var move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(1, 0) }, new CheckersSquare(3, 0));
Assert.IsFalse(target.MovePiece(move));
// Vertical move.
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(1, 0) }, new CheckersSquare(1, 2));
Assert.IsFalse(target.MovePiece(move));
// Back move.
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(2, 3) }, new CheckersSquare(1, 2));
Assert.IsFalse(target.MovePiece(move));
// Move to occupied square to right side.
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(1, 2) }, new CheckersSquare(2, 3));
Assert.IsTrue(target.MovePiece(move));
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(2, 3) }, new CheckersSquare(3, 4));
Assert.IsTrue(target.MovePiece(move));
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(3, 4) }, new CheckersSquare(4, 5)); // Occupied.
Assert.IsFalse(target.MovePiece(move));
// Move to occupied square to left side.
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(7, 2) }, new CheckersSquare(6, 3));
Assert.IsTrue(target.MovePiece(move));
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(6, 3) }, new CheckersSquare(5, 4));
Assert.IsTrue(target.MovePiece(move));
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(5, 4) }, new CheckersSquare(6, 5)); // Occupied.
Assert.IsFalse(target.MovePiece(move));
// Move more than 1 square not capturing.
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(1, 2) }, new CheckersSquare(3, 4));
Assert.IsFalse(target.MovePiece(move));
}
[Test()]
public void MovePiece_ValidMove_True()
{
var target = new CheckersBoard(8);
// Move to occupied square to right side.
var move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(3, 2) }, new CheckersSquare(4, 3));
Assert.IsTrue(target.MovePiece(move));
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerTwo) { CurrentSquare = new CheckersSquare(6, 5) }, new CheckersSquare(5, 4));
Assert.IsTrue(target.MovePiece(move));
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(4, 3) }, new CheckersSquare(6, 5));
Assert.IsTrue(target.MovePiece(move));
move = new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerTwo) { CurrentSquare = new CheckersSquare(5, 6) }, new CheckersSquare(7, 4));
Assert.IsTrue(target.MovePiece(move));
}
[Test()]
public void CountCatchableByPiece_Null_Exception()
{
var target = new CheckersBoard(8);
var actual = Assert.Catch<ArgumentNullException>(() =>
{
target.CountCatchableByPiece(null);
});
Assert.AreEqual("piece", actual.ParamName);
}
[Test()]
public void CountCatchableByPiece_ThereIsNoEnemyPieceAround_Zero()
{
var target = new CheckersBoard(8);
foreach (var p in target.PlayerOnePieces)
{
Assert.AreEqual(0, target.CountCatchableByPiece(p));
}
foreach (var p in target.PlayerTwoPieces)
{
Assert.AreEqual(0, target.CountCatchableByPiece(p));
}
}
[Test()]
public void CountCatchableByPiece_ThereIsEnemyPieceAroundButCannotBeCaptured_Zero()
{
var target = new CheckersBoard(8);
var piece = target.GetSquare(1, 2).CurrentPiece;
Assert.IsTrue(target.MovePiece(new CheckersMove(piece, target.GetSquare(2, 3))));
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
Assert.IsTrue(target.MovePiece(new CheckersMove(piece, target.GetSquare(3, 4))));
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
Assert.IsFalse(target.MovePiece(new CheckersMove(piece, target.GetSquare(4, 5))));
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
}
[Test()]
public void CountCatchableByPiece_ThereIsEnemyPieceAround_CatchableCount()
{
var target = new CheckersBoard(8);
var piece = target.GetSquare(1, 2).CurrentPiece;
Assert.IsTrue(target.MovePiece(new CheckersMove(piece, target.GetSquare(2, 3))));
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
Assert.IsTrue(target.MovePiece(new CheckersMove(piece, target.GetSquare(3, 4))));
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
var enemyPiece = target.GetSquare(4, 5).CurrentPiece;
Assert.AreEqual(1, target.CountCatchableByPiece(enemyPiece));
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
Assert.IsTrue(target.MovePiece(new CheckersMove(enemyPiece, target.GetSquare(2, 3))));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece));
var otherPiece = target.GetSquare(2, 1).CurrentPiece;
Assert.IsTrue(target.MovePiece(new CheckersMove(otherPiece, target.GetSquare(1, 2))));
Assert.AreEqual(1, target.CountCatchableByPiece(otherPiece));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece));
}
[Test()]
public void CountCatchableByPiece_ThereIsTwoEnemyPieceAround_CatchableCountTwo()
{
var target = new CheckersBoard(8);
var piece = target.GetSquare(3, 2).CurrentPiece;
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
var enemyPiece1 = target.GetSquare(6, 5).CurrentPiece;
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece1));
Assert.IsTrue(target.MovePiece(new CheckersMove(enemyPiece1, target.GetSquare(5, 4))));
Assert.AreEqual(0, target.CountCatchableByPiece(piece));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece1));
Assert.IsTrue(target.MovePiece(new CheckersMove(enemyPiece1, target.GetSquare(4, 3))));
Assert.AreEqual(1, target.CountCatchableByPiece(piece));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece1));
var enemyPiece2 = target.GetSquare(4, 5).CurrentPiece;
Assert.AreEqual(1, target.CountCatchableByPiece(piece));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece2));
Assert.IsTrue(target.MovePiece(new CheckersMove(enemyPiece2, target.GetSquare(3, 4))));
Assert.AreEqual(1, target.CountCatchableByPiece(piece));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece2));
Assert.IsTrue(target.MovePiece(new CheckersMove(enemyPiece2, target.GetSquare(2, 3))));
Assert.AreEqual(2, target.CountCatchableByPiece(piece));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece2));
Assert.AreEqual(0, target.CountCatchableByPiece(enemyPiece1));
}
[Test()]
public void CountPieceChancesToBeCaptured_Null_Exception()
{
var target = new CheckersBoard(8);
var actual = Assert.Catch<ArgumentNullException>(() =>
{
target.CountPieceChancesToBeCaptured(null);
});
Assert.AreEqual("piece", actual.ParamName);
}
[Test()]
public void CountPieceChancesToBeCaptured_ThereIsNoEnemyPieceAround_Zero()
{
var target = new CheckersBoard(8);
foreach (var p in target.PlayerOnePieces)
{
Assert.AreEqual(0, target.CountPieceChancesToBeCaptured(p));
}
foreach (var p in target.PlayerTwoPieces)
{
Assert.AreEqual(0, target.CountPieceChancesToBeCaptured(p));
}
}
[Test()]
public void CountPieceChancesToBeCaptured_CanAndCannotCapture_CapturedCount()
{
var target = new CheckersBoard(8);
var piece = target.GetSquare(1, 2).CurrentPiece;
Assert.IsTrue(target.MovePiece(new CheckersMove(piece, target.GetSquare(2, 3))));
Assert.AreEqual(0, target.CountPieceChancesToBeCaptured(piece));
Assert.IsTrue(target.MovePiece(new CheckersMove(piece, target.GetSquare(3, 4))));
Assert.AreEqual(2, target.CountPieceChancesToBeCaptured(piece));
var enemyPiece = target.GetSquare(4, 5).CurrentPiece;
Assert.AreEqual(0, target.CountPieceChancesToBeCaptured(enemyPiece));
Assert.IsFalse(target.MovePiece(new CheckersMove(piece, target.GetSquare(4, 5))));
Assert.AreEqual(2, target.CountPieceChancesToBeCaptured(piece));
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System;
using Microsoft.Boogie;
using System.Diagnostics;
using System.Numerics;
namespace Symbooglix
{
public class ExprUtil
{
public static LiteralExpr AsLiteral(Expr e)
{
return e as LiteralExpr;
}
public static IdentifierExpr AsIdentifer(Expr e)
{
return e as IdentifierExpr;
}
public static SymbolicVariable AsSymbolicVariable(Expr e)
{
var asId = AsIdentifer(e);
if (asId == null)
return null;
if (asId.Decl is SymbolicVariable)
{
return asId.Decl as SymbolicVariable;
}
else
return null;
}
public static bool IsTrue(Expr e)
{
var lit = AsLiteral(e);
if (lit != null)
{
return lit.IsTrue;
}
return false;
}
public static bool IsFalse(Expr e)
{
var lit = AsLiteral(e);
if (lit != null)
{
return lit.IsFalse;
}
return false;
}
public static NAryExpr AsIfThenElse(Expr e)
{
return InternalAsFun<IfThenElse>(e);
}
public static bool StructurallyEqual(Expr a, Expr b)
{
Debug.Assert(a.Immutable);
Debug.Assert(b.Immutable);
if (Object.ReferenceEquals(a, b))
return true;
// Do quick check first
if (a.GetHashCode() != b.GetHashCode())
return false;
// Same hashcodes but the Expr could still be structurally different
// so compute by traversing (much slower)
return a.Equals(b);
}
public static NAryExpr AsNot(Expr e)
{
return GetUnaryOperator(e, UnaryOperator.Opcode.Not);
}
public static NAryExpr AsNotEq(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Neq);
}
public static NAryExpr AsEq(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Eq);
}
public static NAryExpr AsNeg(Expr e)
{
return GetUnaryOperator(e, UnaryOperator.Opcode.Neg);
}
public static NAryExpr AsGt(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Gt);
}
public static NAryExpr AsGe(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Ge);
}
public static NAryExpr AsLt(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Lt);
}
public static NAryExpr AsLe(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Le);
}
private static NAryExpr GetUnaryOperator(Expr e, UnaryOperator.Opcode opcode)
{
var nary = e as NAryExpr;
if (nary == null)
return null;
var fun = nary.Fun;
if (fun is UnaryOperator)
{
var unary = fun as UnaryOperator;
if (unary.Op == opcode)
return nary;
}
return null;
}
private static NAryExpr GetBinaryOperator(Expr e, BinaryOperator.Opcode opcode)
{
var nary = e as NAryExpr;
if (nary == null)
return null;
var fun = nary.Fun;
if (fun is BinaryOperator)
{
var binary = fun as BinaryOperator;
if (binary.Op == opcode)
return nary;
}
return null;
}
public static NAryExpr AsDiv(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Div);
}
public static NAryExpr AsMod(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Mod);
}
public static NAryExpr AsImp(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Imp);
}
public static NAryExpr AsAdd(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Add);
}
public static NAryExpr AsMul(Expr e)
{
return GetBinaryOperator(e, BinaryOperator.Opcode.Mul);
}
private static NAryExpr GetBVOperator(Expr e, string builtin)
{
var nary = e as NAryExpr;
if (nary == null)
return null;
var fc = nary.Fun as FunctionCall;
if (fc == null)
return null;
var usedBuiltin = fc.Func.FindStringAttribute("bvbuiltin");
if (usedBuiltin == null)
return null;
if (usedBuiltin == builtin)
return nary;
else
return null;
}
public static NAryExpr AsBVADD(Expr e)
{
return GetBVOperator(e, "bvadd");
}
public static NAryExpr AsBVSUB(Expr e)
{
return GetBVOperator(e, "bvsub");
}
public static NAryExpr AsBVMUL(Expr e)
{
return GetBVOperator(e, "bvmul");
}
public static NAryExpr AsBVUDIV(Expr e)
{
return GetBVOperator(e, "bvudiv");
}
public static NAryExpr AsBVUREM(Expr e)
{
return GetBVOperator(e, "bvurem");
}
public static NAryExpr AsBVSDIV(Expr e)
{
return GetBVOperator(e, "bvsdiv");
}
public static NAryExpr AsBVSREM(Expr e)
{
return GetBVOperator(e, "bvsrem");
}
public static NAryExpr AsBVSMOD(Expr e)
{
return GetBVOperator(e, "bvsmod");
}
public static NAryExpr AsBVNEG(Expr e)
{
return GetBVOperator(e, "bvneg");
}
public static NAryExpr AsBVNOT(Expr e)
{
return GetBVOperator(e, "bvnot");
}
public static NAryExpr AsBVSEXT(Expr e)
{
var nary = e as NAryExpr;
if (nary == null)
return null;
var fc = nary.Fun as FunctionCall;
if (fc == null)
return null;
var usedBuiltin = fc.Func.FindStringAttribute("bvbuiltin");
if (usedBuiltin == null)
return null;
var regex = new System.Text.RegularExpressions.Regex("^sign_extend \\d+$");
if (regex.IsMatch(usedBuiltin))
{
return nary;
}
return null;
}
public static NAryExpr AsBVZEXT(Expr e)
{
var nary = e as NAryExpr;
if (nary == null)
return null;
var fc = nary.Fun as FunctionCall;
if (fc == null)
return null;
var usedBuiltin = fc.Func.FindStringAttribute("bvbuiltin");
if (usedBuiltin == null)
return null;
var regex = new System.Text.RegularExpressions.Regex("^zero_extend \\d+$");
if (regex.IsMatch(usedBuiltin))
{
return nary;
}
return null;
}
public static BvConcatExpr AsBVCONCAT(Expr e)
{
return e as BvConcatExpr;
}
public static BvExtractExpr AsBVEXTRACT(Expr e)
{
return e as BvExtractExpr;
}
public static NAryExpr AsBVSLT(Expr e)
{
return GetBVOperator(e, "bvslt");
}
public static NAryExpr AsBVSLE(Expr e)
{
return GetBVOperator(e, "bvsle");
}
public static NAryExpr AsBVSGT(Expr e)
{
return GetBVOperator(e, "bvsgt");
}
public static NAryExpr AsBVSGE(Expr e)
{
return GetBVOperator(e, "bvsge");
}
public static NAryExpr AsBVULT(Expr e)
{
return GetBVOperator(e, "bvult");
}
public static NAryExpr AsBVULE(Expr e)
{
return GetBVOperator(e, "bvule");
}
public static NAryExpr AsBVUGT(Expr e)
{
return GetBVOperator(e, "bvugt");
}
public static NAryExpr AsBVUGE(Expr e)
{
return GetBVOperator(e, "bvuge");
}
public static NAryExpr AsBVAND(Expr e)
{
return GetBVOperator(e, "bvand");
}
public static NAryExpr AsBVOR(Expr e)
{
return GetBVOperator(e, "bvor");
}
public static NAryExpr AsBVXOR(Expr e)
{
return GetBVOperator(e, "bvxor");
}
public static NAryExpr AsBVSHL(Expr e)
{
return GetBVOperator(e, "bvshl");
}
public static NAryExpr AsBVLSHR(Expr e)
{
return GetBVOperator(e, "bvlshr");
}
public static NAryExpr AsBVASHR(Expr e)
{
return GetBVOperator(e, "bvashr");
}
private static NAryExpr InternalAsFun<T>(Expr e)
{
var asNary = e as NAryExpr;
if (asNary == null)
return null;
var fun = asNary.Fun;
if (fun is T)
return asNary;
return null;
}
public static NAryExpr AsUninterpretedFunctionCall(Expr e) {
var asFunctionCall = InternalAsFun<FunctionCall>(e);
if (asFunctionCall == null)
return null;
var function = ( asFunctionCall.Fun as FunctionCall ).Func;
var asUF = AsUninterpretedFunction(function);
if (asUF == null)
return null;
return asFunctionCall;
}
public static Function AsUninterpretedFunction(Function f)
{
// FIXME: Should we maintain a list of known built-ins and check against that?
var bvBuiltin = f.FindStringAttribute("bvbuiltin");
if (bvBuiltin != null)
return null;
// Check if its a builtin
var builtin = f.FindStringAttribute("builtin");
if (builtin != null)
return null;
return f;
}
public static NAryExpr AsArithmeticCoercion(Expr e)
{
return InternalAsFun<ArithmeticCoercion>(e);
}
public static NAryExpr AsMapSelect(Expr e)
{
return InternalAsFun<MapSelect>(e);
}
public static NAryExpr AsMapStore(Expr e)
{
return InternalAsFun<MapStore>(e);
}
public static bool IsZero(Expr e)
{
var lit = AsLiteral(e);
if (lit == null)
return false;
if (lit.isBvConst)
{
return lit.asBvConst.Value.IsZero;
}
else if (lit.isBigNum)
{
return lit.asBigNum.IsZero;
}
else if (lit.isBigDec)
{
return lit.asBigDec.IsZero;
}
return false;
}
public static bool IsOne(Expr e)
{
var lit = AsLiteral(e);
if (lit == null)
return false;
if (lit.isBvConst)
{
return lit.asBvConst.Value.ToBigInteger.IsOne;
}
else if (lit.isBigNum)
{
return lit.asBigNum.ToBigInteger.IsOne;
}
else if (lit.isBigDec)
{
return lit.asBigDec.Equals(Microsoft.Basetypes.BigDec.FromInt(1));
}
return false;
}
public static bool IsBVAllOnes(Expr e)
{
var asLit = AsLiteral(e);
if (asLit == null)
return false;
if (!asLit.isBvConst)
return false;
var AllOnesValue = ( System.Numerics.BigInteger.One << asLit.asBvConst.Bits ) - 1;
return asLit.asBvConst.Value.ToBigInteger == AllOnesValue;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
namespace Microsoft.PythonTools.Analysis {
public struct MemberResult {
private readonly string _name;
private string _completion;
private readonly Func<IEnumerable<AnalysisValue>> _vars;
private readonly Func<PythonMemberType> _type;
internal MemberResult(string name, IEnumerable<AnalysisValue> vars) {
_name = _completion = name;
_vars = () => vars ?? Empty;
_type = null;
_type = GetMemberType;
}
public MemberResult(string name, PythonMemberType type) {
_name = _completion = name;
_type = () => type;
_vars = () => Empty;
}
internal MemberResult(string name, string completion, IEnumerable<AnalysisValue> vars, PythonMemberType? type) {
_name = name;
_vars = () => vars ?? Empty;
_completion = completion;
if (type != null) {
_type = () => type.Value;
} else {
_type = null;
_type = GetMemberType;
}
}
internal MemberResult(string name, Func<IEnumerable<AnalysisValue>> vars, Func<PythonMemberType> type) {
_name = _completion = name;
Func<IEnumerable<AnalysisValue>> empty = () => Empty;
_vars = vars ?? empty;
_type = type;
}
public MemberResult FilterCompletion(string completion) {
return new MemberResult(Name, completion, Namespaces, MemberType);
}
private static AnalysisValue[] Empty = new AnalysisValue[0];
public string Name {
get { return _name; }
}
public string Completion {
get { return _completion; }
}
public string Documentation {
get {
var docSeen = new HashSet<string>();
var typeSeen = new HashSet<string>();
var docs = new List<string>();
var types = new List<string>();
var doc = new StringBuilder();
foreach (var ns in _vars()) {
var docString = ns.Documentation ?? string.Empty;
if (docSeen.Add(docString)) {
docs.Add(docString);
}
var typeString = ns.ShortDescription ?? string.Empty;
if (typeSeen.Add(typeString)) {
types.Add(typeString);
}
}
var mt = MemberType;
if (mt == PythonMemberType.Instance || mt == PythonMemberType.Constant) {
switch (mt) {
case PythonMemberType.Instance:
doc.Append("Instance of ");
break;
case PythonMemberType.Constant:
doc.Append("Constant ");
break;
default:
doc.Append("Value of ");
break;
}
if (types.Count == 0) {
doc.AppendLine("unknown type");
} else if (types.Count == 1) {
doc.AppendLine(types[0]);
} else {
var orStr = types.Count == 2 ? " or " : ", or ";
doc.AppendLine(string.Join(", ", types.Take(types.Count - 1)) + orStr + types.Last());
}
doc.AppendLine();
}
foreach (var str in docs.OrderBy(s => s)) {
doc.AppendLine(str);
doc.AppendLine();
}
return Utils.CleanDocumentation(doc.ToString());
}
}
public PythonMemberType MemberType {
get {
return _type();
}
}
private PythonMemberType GetMemberType() {
bool includesNone = false;
PythonMemberType result = PythonMemberType.Unknown;
var allVars = _vars().SelectMany(ns => {
var mmi = ns as MultipleMemberInfo;
if (mmi != null) {
return mmi.Members;
} else {
return Enumerable.Repeat(ns, 1);
}
});
foreach (var ns in allVars) {
if (ns == null) {
Debug.Fail("Unexpected null AnalysisValue");
continue;
}
var nsType = ns.MemberType;
var ci = ns as ConstantInfo;
if (ci != null) {
if (ci.ClassInfo == ci.ProjectState.ClassInfos[BuiltinTypeId.Function]) {
nsType = PythonMemberType.Function;
} else if (ci.ClassInfo == ci.ProjectState.ClassInfos[BuiltinTypeId.Type]) {
nsType = PythonMemberType.Class;
}
}
if (ns.TypeId == BuiltinTypeId.NoneType) {
includesNone = true;
} else if (result == PythonMemberType.Unknown) {
result = nsType;
} else if (result == nsType) {
// No change
} else if (result == PythonMemberType.Constant && nsType == PythonMemberType.Instance) {
// Promote from Constant to Instance
result = PythonMemberType.Instance;
} else {
return PythonMemberType.Multiple;
}
}
if (result == PythonMemberType.Unknown) {
return includesNone ? PythonMemberType.Constant : PythonMemberType.Instance;
}
return result;
}
internal IEnumerable<AnalysisValue> Namespaces {
get {
return _vars();
}
}
/// <summary>
/// Gets the location(s) for the member(s) if they are available.
///
/// New in 1.5.
/// </summary>
public IEnumerable<LocationInfo> Locations {
get {
foreach (var ns in _vars()) {
foreach (var location in ns.Locations) {
yield return location;
}
}
}
}
public override bool Equals(object obj) {
if (!(obj is MemberResult)) {
return false;
}
return Name == ((MemberResult)obj).Name;
}
public static bool operator ==(MemberResult x, MemberResult y) {
return x.Name == y.Name;
}
public static bool operator !=(MemberResult x, MemberResult y) {
return x.Name != y.Name;
}
public override int GetHashCode() {
return Name.GetHashCode();
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.WebsiteBuilder.DataAccess;
using Frapid.WebsiteBuilder.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.WebsiteBuilder.Api.Tests
{
public class CategoryTests
{
public static CategoryController Fixture()
{
CategoryController controller = new CategoryController(new CategoryRepository());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.WebsiteBuilder.Entities.Category category = Fixture().Get(0);
Assert.NotNull(category);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.WebsiteBuilder.Entities.Category category = Fixture().GetFirst();
Assert.NotNull(category);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.WebsiteBuilder.Entities.Category category = Fixture().GetPrevious(0);
Assert.NotNull(category);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.WebsiteBuilder.Entities.Category category = Fixture().GetNext(0);
Assert.NotNull(category);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.WebsiteBuilder.Entities.Category category = Fixture().GetLast();
Assert.NotNull(category);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.WebsiteBuilder.Entities.Category> categories = Fixture().Get(new int[] { });
Assert.NotNull(categories);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
/*
Copyright 2012-2022 Marco De Salvo
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 Microsoft.VisualStudio.TestTools.UnitTesting;
using RDFSharp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace RDFSharp.Test.Model
{
[TestClass]
public class RDFPatternConstraintTest
{
#region Tests
[TestMethod]
public void ShouldCreatePatternConstraint()
{
RDFPatternConstraint patternConstraint = new RDFPatternConstraint(new Regex("^test$", RegexOptions.IgnoreCase));
Assert.IsNotNull(patternConstraint);
Assert.IsNotNull(patternConstraint.RegEx.Equals(new Regex("^test$", RegexOptions.IgnoreCase)));
}
[TestMethod]
public void ShouldThrowExceptionOnCreatingPatternConstraint()
=> Assert.ThrowsException<RDFModelException>(() => new RDFPatternConstraint(null));
[TestMethod]
public void ShouldExportPatternConstraint()
{
RDFPatternConstraint patternConstraint = new RDFPatternConstraint(new Regex("^test$", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace));
RDFGraph graph = patternConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape")));
Assert.IsNotNull(graph);
Assert.IsTrue(graph.TriplesCount == 2);
Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape"))
&& t.Value.Predicate.Equals(RDFVocabulary.SHACL.PATTERN)
&& t.Value.Object.Equals(new RDFTypedLiteral("^test$", RDFModelEnums.RDFDatatypes.XSD_STRING))));
Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape"))
&& t.Value.Predicate.Equals(RDFVocabulary.SHACL.FLAGS)
&& t.Value.Object.Equals(new RDFTypedLiteral("ismx", RDFModelEnums.RDFDatatypes.XSD_STRING))));
}
//NS-CONFORMS: TRUE
[TestMethod]
public void ShouldConformNodeShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:")));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("ce$")));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:")));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:")));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//PS-CONFORMS: TRUE
[TestMethod]
public void ShouldConformPropertyShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:")));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithClassTargetAndLiteralValue()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFPlainLiteral("Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFPlainLiteral("Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^Steve$")));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("(.)*ob$")));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:", RegexOptions.IgnoreCase)));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:", RegexOptions.IgnoreCase)));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//NS-CONFORMS: FALSE
[TestMethod]
public void ShouldNotConformNodeShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:[BS]")));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:[BS]")));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithNodeTargetBecauseBlankValue()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("bnode:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("bnode:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("bnode:Alice")));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("^bnode:A"))); //This constraint does not allow blank nodes as values
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("bnode:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("bnode:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:B")));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:S")));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
//PS-CONFORMS: FALSE
[TestMethod]
public void ShouldNotConformPropertyShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:S")));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must match expression ^ex:S and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithClassTargetBecauseBlankValue()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("bnode:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("bnode:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("bnode:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:")));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must match expression ^ex: and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("bnode:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFPlainLiteral("Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFPlainLiteral("Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^S")));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must match expression ^S and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFPlainLiteral("Bob")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:S")));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must match expression ^ex:S and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFPatternConstraint(new Regex("^ex:B")));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must match expression ^ex:B and can't be a blank node")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Steve")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.PATTERN_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
#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;
/// <summary>
/// ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)
/// </summary>
public class DateTimeCtor6
{
#region Private Fields
private int m_ErrorNo = 0;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: We can call ctor to constructor a new DateTime instance by using valid value");
try
{
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 0, 0, 500);
retVal = retVal && VerifyDateTimeHelper(2006, 8, 28, 12, 56, 56, 900);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: We can call ctor to constructor a new DateTime instance by using MAX/MIN values");
try
{
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(1, 1, 1, 0, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 0, 0, 999);
retVal = retVal && VerifyDateTimeHelper(9999, 12, 31, 0, 59, 59, 0);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 0, 0, 999);
retVal = retVal && VerifyDateTimeHelper(1, 12, 31, 0, 59, 59, 0);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(9999, 1, 1, 0, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(2000, 1, 31, 0, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 0, 0, 999);
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 0, 59, 59, 0);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(2001, 2, 28, 0, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 23, 59, 59, 999);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 0, 0, 999);
retVal = retVal && VerifyDateTimeHelper(2001, 4, 30, 0, 59, 59, 0);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: We can call ctor to constructor a new DateTime instance by using correct day/month pair");
try
{
retVal = retVal && VerifyDateTimeHelper(2000, 2, 29, 16, 7, 43, 500);
retVal = retVal && VerifyDateTimeHelper(2006, 2, 28, 12, 0, 0, 0);
retVal = retVal && VerifyDateTimeHelper(2006, 4, 30, 16, 7, 43, 100);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when year is less than 1 or greater than 9999.");
try
{
m_ErrorNo++;
DateTime value = new DateTime(0, 1, 1, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(10000, 1, 1, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is greater than 9999");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when month is less than 1 or greater than 12");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 0, 1, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 13, 1, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is greater than 12");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException should be thrown when day is less than 1 or greater than the number of days in month");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 0, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is less than 1");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 32, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 2, 29, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 4, 31, 1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException should be thrown when hour is less than 0 or greater than 23");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, -1, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when hour is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 24, 1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when hour is greater than 23");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException should be thrown when minute is less than 0 or greater than 59");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, -1, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown minute year is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 60, 1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when minute is greater than 59");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException should be thrown when second is less than 0 or greater than 59");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, -1, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when second is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 60, 1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when second is greater than 59");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: ArgumentOutOfRangeException should be thrown when millisecond is less than 0 or greater than 999");
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 1, -1);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when millisecond is less than 0");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
try
{
m_ErrorNo++;
DateTime value = new DateTime(2006, 1, 1, 1, 1, 1, 1000);
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when millisecond is greater than 999");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.1", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
#endregion
public static int Main()
{
DateTimeCtor6 test = new DateTimeCtor6();
TestLibrary.TestFramework.BeginTestCase("DateTimeCtor6");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerifyDateTimeHelper(int desiredYear,
int desiredMonth,
int desiredDay,
int desiredHour,
int desiredMinute,
int desiredSecond,
int desiredMillisecond)
{
bool retVal = true;
DateTime value = new DateTime(desiredYear, desiredMonth, desiredDay,
desiredHour, desiredMinute, desiredSecond, desiredMillisecond);
m_ErrorNo++;
if ((desiredYear != value.Year) ||
(desiredMonth != value.Month) ||
(desiredDay != value.Day) ||
(desiredHour != value.Hour) ||
(desiredMinute != value.Minute) ||
(desiredSecond != value.Second) ||
(desiredMillisecond != value.Millisecond) )
{
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Calling ctor constructors a wrong DateTime instance by using valid value");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredYear = " + desiredYear.ToString() +
", desiredMonth = " + desiredMonth.ToString() +
", desiredDay = " + desiredDay.ToString() +
", desiredHour = " + desiredHour.ToString() +
", desiredMinute = " + desiredMinute.ToString() +
", desiredSecond = " + desiredSecond.ToString() +
", desiredMillisecond = " + desiredMillisecond.ToString() +
", actualYear = " + value.Year.ToString() +
", actualMonth = " + value.Month.ToString() +
", actualDay = " + value.Day.ToString() +
", actualHour = " + value.Hour.ToString() +
", actualMinute = " + value.Minute.ToString() +
", actualSecond = " + value.Second.ToString() +
", actualMillisecond = " + value.Millisecond.ToString());
retVal = false;
}
m_ErrorNo++;
if (value.Kind != DateTimeKind.Unspecified)
{
TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Calling ctor constructors a wrong DateTime instance by using valid value");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredKind = DateTimeKind.Unspecified" + ", actualKind = " + value.Kind.ToString());
retVal = false;
}
return retVal;
}
#endregion
}
| |
using SGH_Khronos.Model;
using SGH_Khronos.Model.Enums;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
namespace SGH_Khronos.Data.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<AppContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = false;
}
protected override void Seed(AppContext context)
{
context.Hospitais.AddOrUpdate(h => h.Nome, new Hospital
{
Nome = "Hospital SGH",
Endereco = "Av. Unisinos 900, RS",
Telefone = "(51) 555-9999"
});
var medicos = new List<Medico>
{
new Medico
{
Nome = "Catherine Moore",
Documento = "6998606630",
DataNascimento = new DateTime(1975, 9, 26),
DataRegistro = DateTimeOffset.UtcNow,
Crm = "8213",
CrmUf = Uf.RS,
Especialidade = "Dermatologia"
},
new Medico
{
Nome = "Donald Fisher",
Documento = "8875022736",
DataNascimento = new DateTime(1951, 7, 4),
DataRegistro = DateTimeOffset.UtcNow,
Crm = "7924",
CrmUf = Uf.ES,
Especialidade = "Ortopedia"
},
new Medico
{
Nome = "Phyllis Gardner",
Documento = "6414449392",
DataNascimento = new DateTime(1968, 8, 11),
DataRegistro = DateTimeOffset.UtcNow,
Crm = "9463",
CrmUf = Uf.RJ,
Especialidade = "Pediatria"
},
new Medico
{
Nome = "David Bryant",
Documento = "3318025507",
DataNascimento = new DateTime(1986, 10, 1),
DataRegistro = DateTimeOffset.UtcNow,
Crm = "3892",
CrmUf = Uf.SP,
Especialidade = "Neurologia"
},
new Medico
{
Nome = "Shawn Rodriguez",
Documento = "4374834783",
DataNascimento = new DateTime(1976, 4, 5),
DataRegistro = DateTimeOffset.UtcNow,
Crm = "6292",
CrmUf = Uf.SP,
Especialidade = "Pneumologia"
}
};
foreach (var medico in medicos)
{
if (!context.Medicos.Any(u => u.Nome.Equals(medico.Nome)))
{
context.Medicos.Add(medico);
}
}
var enfermeiros = new List<Enfermeiro>
{
new Enfermeiro
{
Nome = "Amy Diaz",
Documento = "97060038544",
DataNascimento = new DateTime(1990, 4, 13),
DataRegistro = DateTimeOffset.UtcNow,
HorarioEntrada = new TimeSpan(8, 0, 0),
HorarioSaida = new TimeSpan(17, 0, 0),
Supervisor = false
},
new Enfermeiro
{
Nome = "Eric Hamilton",
Documento = "22812392048",
DataNascimento = new DateTime(1984, 12, 19),
DataRegistro = DateTimeOffset.UtcNow,
HorarioEntrada = new TimeSpan(9, 30, 0),
HorarioSaida = new TimeSpan(19, 0, 0),
Supervisor = false
},
new Enfermeiro
{
Nome = "Debra Mendoza",
Documento = "96933681771",
DataNascimento = new DateTime(1987, 3, 11),
DataRegistro = DateTimeOffset.UtcNow,
HorarioEntrada = new TimeSpan(8, 45, 0),
HorarioSaida = new TimeSpan(18, 0, 0),
Supervisor = true
},
};
foreach (var enfermeiro in enfermeiros)
{
if (!context.Enfermeiros.Any(u => u.Nome.Equals(enfermeiro.Nome)))
{
context.Enfermeiros.Add(enfermeiro);
}
}
var recepcionistas = new List<Recepcionista>
{
new Recepcionista
{
Nome = "Shirley Howard",
Documento = "99922917362",
DataNascimento = new DateTime(1992, 1, 14),
DataRegistro = DateTimeOffset.UtcNow,
HorarioEntrada = new TimeSpan(7, 45, 0),
HorarioSaida = new TimeSpan(13, 0, 0)
},
new Recepcionista
{
Nome = "Jessica Larson",
Documento = "27413858566",
DataNascimento = new DateTime(1990, 11, 9),
DataRegistro = DateTimeOffset.UtcNow,
HorarioEntrada = new TimeSpan(13, 15, 0),
HorarioSaida = new TimeSpan(20, 0, 0)
}
};
foreach (var recepcionista in recepcionistas)
{
if (!context.Recepcionistas.Any(u => u.Nome.Equals(recepcionista.Nome)))
{
context.Recepcionistas.Add(recepcionista);
}
}
var pacientes = new List<Paciente>
{
new Paciente
{
Nome = "Sara Hawkins",
Documento = "67612823413",
DataNascimento = new DateTime(1996, 1, 12),
DataRegistro = DateTimeOffset.UtcNow,
NomeMae = "Christine Hawkins",
NomePai = "Wayne Hawkins"
},
new Paciente
{
Nome = "Joyce Nelson",
Documento = "52154383109",
DataNascimento = new DateTime(1985, 7, 22),
DataRegistro = DateTimeOffset.UtcNow,
NomeMae = "Doris Nelson",
NomePai = "Daniel Nelson"
},
new Paciente
{
Nome = "Sandra Armstrong",
Documento = "36404501635",
DataNascimento = new DateTime(1976, 8, 9),
DataRegistro = DateTimeOffset.UtcNow,
NomeMae = "Rebecca Armstrong",
NomePai = "Walter Armstrong"
}
};
foreach (var paciente in pacientes)
{
if (!context.Pacientes.Any(u => u.Nome.Equals(paciente.Nome)))
{
context.Pacientes.Add(paciente);
}
}
context.SaveChanges();
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.CodeGeneration;
using Orleans.GrainReferences;
using Orleans.Internal;
using Orleans.Runtime.Messaging;
using Orleans.Serialization;
using Orleans.Streams;
namespace Orleans.Runtime
{
/// <summary>
/// A client which is hosted within a silo.
/// </summary>
internal sealed class HostedClient : IGrainContext, IGrainExtensionBinder, IDisposable, ILifecycleParticipant<ISiloLifecycle>
{
private readonly object lockObj = new object();
private readonly Channel<Message> incomingMessages;
private readonly IGrainReferenceRuntime grainReferenceRuntime;
private readonly InvokableObjectManager invokableObjects;
private readonly IRuntimeClient runtimeClient;
private readonly ClientObserverRegistrar clientObserverRegistrar;
private readonly ILogger logger;
private readonly IInternalGrainFactory grainFactory;
private readonly MessageCenter siloMessageCenter;
private readonly MessagingTrace messagingTrace;
private readonly ConcurrentDictionary<Type, (object Implementation, IAddressable Reference)> _extensions = new ConcurrentDictionary<Type, (object, IAddressable)>();
private bool disposing;
private Task messagePump;
public HostedClient(
IRuntimeClient runtimeClient,
ClientObserverRegistrar clientObserverRegistrar,
ILocalSiloDetails siloDetails,
ILogger<HostedClient> logger,
IGrainReferenceRuntime grainReferenceRuntime,
IInternalGrainFactory grainFactory,
MessageCenter messageCenter,
MessagingTrace messagingTrace,
SerializationManager serializationManager,
GrainReferenceActivator referenceActivator)
{
this.incomingMessages = Channel.CreateUnbounded<Message>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false,
AllowSynchronousContinuations = false,
});
this.runtimeClient = runtimeClient;
this.clientObserverRegistrar = clientObserverRegistrar;
this.grainReferenceRuntime = grainReferenceRuntime;
this.grainFactory = grainFactory;
this.invokableObjects = new InvokableObjectManager(
this,
runtimeClient,
serializationManager,
messagingTrace,
logger);
this.siloMessageCenter = messageCenter;
this.messagingTrace = messagingTrace;
this.logger = logger;
this.ClientId = ClientGrainId.Create($"hosted-{messageCenter.MyAddress.ToParsableString()}");
this.Address = ActivationAddress.NewActivationAddress(siloDetails.SiloAddress, this.ClientId.GrainId);
this.GrainReference = referenceActivator.CreateReference(this.ClientId.GrainId, default);
}
/// <inheritdoc />
public ClientGrainId ClientId { get; }
/// <inheritdoc />
public StreamDirectory StreamDirectory { get; } = new StreamDirectory();
public GrainReference GrainReference { get; }
public GrainId GrainId => this.ClientId.GrainId;
public IAddressable GrainInstance => null;
public ActivationId ActivationId => this.Address.Activation;
public ActivationAddress Address { get; }
public IServiceProvider ActivationServices => this.runtimeClient.ServiceProvider;
public IGrainLifecycle ObservableLifecycle => throw new NotImplementedException();
/// <inheritdoc />
public override string ToString() => $"{nameof(HostedClient)}_{this.Address}";
/// <inheritdoc />
public IAddressable CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
{
if (obj is GrainReference) throw new ArgumentException("Argument obj is already a grain reference.");
var observerId = ObserverGrainId.Create(this.ClientId);
var grainReference = this.grainFactory.GetGrain(observerId.GrainId);
if (!this.invokableObjects.TryRegister(obj, observerId, invoker))
{
throw new ArgumentException(
string.Format("Failed to add new observer {0} to localObjects collection.", grainReference),
nameof(grainReference));
}
return grainReference;
}
/// <inheritdoc />
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference reference))
{
throw new ArgumentException("Argument reference is not a grain reference.");
}
if (!ObserverGrainId.TryParse(reference.GrainId, out var observerId))
{
throw new ArgumentException($"Reference {reference.GrainId} is not an observer reference");
}
if (!invokableObjects.TryDeregister(observerId))
{
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
}
public TComponent GetComponent<TComponent>()
{
if (this is TComponent component) return component;
return default;
}
public void SetComponent<TComponent>(TComponent instance)
{
throw new NotSupportedException($"Cannot set components on shared client instance. Extension contract: {typeof(TComponent)}. Component: {instance} (Type: {instance?.GetType()})");
}
/// <inheritdoc />
public bool TryDispatchToClient(Message message)
{
if (!ClientGrainId.TryParse(message.TargetGrain, out var targetClient) || !this.ClientId.Equals(targetClient))
{
return false;
}
if (message.IsExpired)
{
this.messagingTrace.OnDropExpiredMessage(message, MessagingStatisticsGroup.Phase.Receive);
return true;
}
if (message.Direction == Message.Directions.Response)
{
// Requests are made through the runtime client, so deliver responses to the rutnime client so that the request callback can be executed.
this.runtimeClient.ReceiveResponse(message);
}
else
{
// Requests against client objects are scheduled for execution on the client.
this.incomingMessages.Writer.TryWrite(message);
}
return true;
}
/// <inheritdoc />
void IDisposable.Dispose()
{
if (this.disposing) return;
this.disposing = true;
Utils.SafeExecute(() => this.clientObserverRegistrar.ClientDropped(this.ClientId));
Utils.SafeExecute(() => this.clientObserverRegistrar.SetHostedClient(null));
Utils.SafeExecute(() => this.siloMessageCenter.SetHostedClient(null));
Utils.SafeExecute(() => this.incomingMessages.Writer.TryComplete());
Utils.SafeExecute(() => this.messagePump?.GetAwaiter().GetResult());
}
private void Start()
{
this.messagePump = Task.Run(this.RunClientMessagePump);
}
private async Task RunClientMessagePump()
{
var reader = this.incomingMessages.Reader;
while (true)
{
try
{
var more = await reader.WaitToReadAsync();
if (!more)
{
this.logger.LogInformation($"{nameof(HostedClient)} completed processing all messages. Shutting down.");
break;
}
while (reader.TryRead(out var message))
{
if (message == null) continue;
switch (message.Direction)
{
case Message.Directions.OneWay:
case Message.Directions.Request:
this.invokableObjects.Dispatch(message);
break;
default:
this.logger.LogError((int)ErrorCode.Runtime_Error_100327, "Message not supported: {Message}", message);
break;
}
}
}
catch (Exception exception)
{
this.logger.LogError((int)ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown an exception: {Exception}. Continuing.", exception);
}
}
}
void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe("HostedClient", ServiceLifecycleStage.RuntimeGrainServices, OnStart, OnStop);
Task OnStart(CancellationToken cancellation)
{
if (cancellation.IsCancellationRequested) return Task.CompletedTask;
// Register with the directory and message center so that we can receive messages.
this.clientObserverRegistrar.SetHostedClient(this);
this.clientObserverRegistrar.ClientAdded(this.ClientId);
this.siloMessageCenter.SetHostedClient(this);
// Start pumping messages.
this.Start();
var clusterClient = this.runtimeClient.ServiceProvider.GetRequiredService<IClusterClient>();
return clusterClient.Connect();
}
async Task OnStop(CancellationToken cancellation)
{
this.incomingMessages.Writer.TryComplete();
if (this.messagePump != null)
{
await Task.WhenAny(cancellation.WhenCancelled(), this.messagePump);
}
if (cancellation.IsCancellationRequested) return;
var clusterClient = this.runtimeClient.ServiceProvider.GetRequiredService<IClusterClient>();
await clusterClient.Close();
}
}
public bool Equals(IGrainContext other) => ReferenceEquals(this, other);
public (TExtension, TExtensionInterface) GetOrSetExtension<TExtension, TExtensionInterface>(Func<TExtension> newExtensionFunc)
where TExtension : TExtensionInterface
where TExtensionInterface : IGrainExtension
{
(TExtension, TExtensionInterface) result;
if (this.TryGetExtension(out result))
{
return result;
}
lock (this.lockObj)
{
if (this.TryGetExtension(out result))
{
return result;
}
var implementation = newExtensionFunc();
var reference = this.grainFactory.CreateObjectReference<TExtensionInterface>(implementation);
_extensions[typeof(TExtensionInterface)] = (implementation, reference);
result = (implementation, reference);
return result;
}
}
private bool TryGetExtension<TExtension, TExtensionInterface>(out (TExtension, TExtensionInterface) result)
where TExtension : TExtensionInterface
where TExtensionInterface : IGrainExtension
{
if (_extensions.TryGetValue(typeof(TExtensionInterface), out var existing))
{
if (existing.Implementation is TExtension typedResult)
{
result = (typedResult, existing.Reference.AsReference<TExtensionInterface>());
return true;
}
throw new InvalidCastException($"Cannot cast existing extension of type {existing.Implementation} to target type {typeof(TExtension)}");
}
result = default;
return false;
}
private bool TryGetExtension<TExtensionInterface>(out TExtensionInterface result)
where TExtensionInterface : IGrainExtension
{
if (_extensions.TryGetValue(typeof(TExtensionInterface), out var existing))
{
result = (TExtensionInterface)existing.Implementation;
return true;
}
result = default;
return false;
}
public TExtensionInterface GetExtension<TExtensionInterface>()
where TExtensionInterface : IGrainExtension
{
if (this.TryGetExtension<TExtensionInterface>(out var result))
{
return result;
}
lock (this.lockObj)
{
if (this.TryGetExtension(out result))
{
return result;
}
var implementation = this.ActivationServices.GetServiceByKey<Type, IGrainExtension>(typeof(TExtensionInterface));
if (implementation is null)
{
throw new GrainExtensionNotInstalledException($"No extension of type {typeof(TExtensionInterface)} is installed on this instance and no implementations are registered for automated install");
}
var reference = this.GrainReference.Cast<TExtensionInterface>();
_extensions[typeof(TExtensionInterface)] = (implementation, reference);
result = (TExtensionInterface)implementation;
return result;
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using System;
using System.Globalization;
using System.Text;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
[TestFixture]
public class TargetConfigurationTests : NLogTestBase
{
[Test]
public void SimpleTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.IsNotNull(t);
Assert.AreEqual(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.AreEqual("${message}", l.Text);
Assert.IsNotNull(t.Layout);
Assert.AreEqual(1, l.Renderers.Count);
Assert.IsInstanceOfType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Test]
public void SimpleElementSyntaxTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='Debug'>
<name>d</name>
<layout>${message}</layout>
</target>
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.IsNotNull(t);
Assert.AreEqual(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.AreEqual("${message}", l.Text);
Assert.IsNotNull(t.Layout);
Assert.AreEqual(1, l.Renderers.Count);
Assert.IsInstanceOfType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Test]
public void ArrayParameterTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter name='p1' layout='${message}' />
<parameter name='p2' layout='${level}' />
<parameter name='p3' layout='${logger}' />
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.IsNotNull(t);
Assert.AreEqual(3, t.Parameters.Count);
Assert.AreEqual("p1", t.Parameters[0].Name);
Assert.AreEqual("'${message}'", t.Parameters[0].Layout.ToString());
Assert.AreEqual("p2", t.Parameters[1].Name);
Assert.AreEqual("'${level}'", t.Parameters[1].Layout.ToString());
Assert.AreEqual("p3", t.Parameters[2].Name);
Assert.AreEqual("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Test]
public void ArrayElementParameterTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter>
<name>p1</name>
<layout>${message}</layout>
</parameter>
<parameter>
<name>p2</name>
<layout type='CsvLayout'>
<column name='x' layout='${message}' />
<column name='y' layout='${level}' />
</layout>
</parameter>
<parameter>
<name>p3</name>
<layout>${logger}</layout>
</parameter>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.IsNotNull(t);
Assert.AreEqual(3, t.Parameters.Count);
Assert.AreEqual("p1", t.Parameters[0].Name);
Assert.AreEqual("'${message}'", t.Parameters[0].Layout.ToString());
Assert.AreEqual("p2", t.Parameters[1].Name);
CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout;
Assert.IsNotNull(csvLayout);
Assert.AreEqual(2, csvLayout.Columns.Count);
Assert.AreEqual("x", csvLayout.Columns[0].Name);
Assert.AreEqual("y", csvLayout.Columns[1].Name);
Assert.AreEqual("p3", t.Parameters[2].Name);
Assert.AreEqual("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Test]
public void SimpleTest2()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message} ${level}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.IsNotNull(t);
Assert.AreEqual(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.AreEqual("${message} ${level}", l.Text);
Assert.IsNotNull(l);
Assert.AreEqual(3, l.Renderers.Count);
Assert.IsInstanceOfType(typeof(MessageLayoutRenderer), l.Renderers[0]);
Assert.IsInstanceOfType(typeof(LiteralLayoutRenderer), l.Renderers[1]);
Assert.IsInstanceOfType(typeof(LevelLayoutRenderer), l.Renderers[2]);
Assert.AreEqual(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text);
}
[Test]
public void WrapperTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper name='a' type='AsyncWrapper'>
<target name='c' type='Debug' layout='${message}' />
</wrapper>
</wrapper-target>
</targets>
</nlog>");
Assert.IsNotNull(c.FindTargetByName("a"));
Assert.IsNotNull(c.FindTargetByName("b"));
Assert.IsNotNull(c.FindTargetByName("c"));
Assert.IsInstanceOfType(typeof(BufferingTargetWrapper), c.FindTargetByName("b"));
Assert.IsInstanceOfType(typeof(AsyncTargetWrapper), c.FindTargetByName("a"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.AreSame(atw, btw.WrappedTarget);
Assert.AreSame(dt, atw.WrappedTarget);
Assert.AreEqual(19, btw.BufferSize);
}
[Test]
public void WrapperRefTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='c' type='Debug' layout='${message}' />
<wrapper name='a' type='AsyncWrapper'>
<target-ref name='c' />
</wrapper>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper-target-ref name='a' />
</wrapper-target>
</targets>
</nlog>");
Assert.IsNotNull(c.FindTargetByName("a"));
Assert.IsNotNull(c.FindTargetByName("b"));
Assert.IsNotNull(c.FindTargetByName("c"));
Assert.IsInstanceOfType(typeof(BufferingTargetWrapper), c.FindTargetByName("b"));
Assert.IsInstanceOfType(typeof(AsyncTargetWrapper), c.FindTargetByName("a"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.AreSame(atw, btw.WrappedTarget);
Assert.AreSame(dt, atw.WrappedTarget);
Assert.AreEqual(19, btw.BufferSize);
}
[Test]
public void CompoundTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<compound-target name='rr' type='RoundRobinGroup'>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
</compound-target>
</targets>
</nlog>");
Assert.IsNotNull(c.FindTargetByName("rr"));
Assert.IsNotNull(c.FindTargetByName("d1"));
Assert.IsNotNull(c.FindTargetByName("d2"));
Assert.IsNotNull(c.FindTargetByName("d3"));
Assert.IsNotNull(c.FindTargetByName("d4"));
Assert.IsInstanceOfType(typeof(RoundRobinGroupTarget), c.FindTargetByName("rr"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d1"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d2"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d3"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.AreEqual(4, rr.Targets.Count);
Assert.AreSame(d1, rr.Targets[0]);
Assert.AreSame(d2, rr.Targets[1]);
Assert.AreSame(d3, rr.Targets[2]);
Assert.AreSame(d4, rr.Targets[3]);
Assert.AreEqual(((SimpleLayout)d1.Layout).Text, "${message}1");
Assert.AreEqual(((SimpleLayout)d2.Layout).Text, "${message}2");
Assert.AreEqual(((SimpleLayout)d3.Layout).Text, "${message}3");
Assert.AreEqual(((SimpleLayout)d4.Layout).Text, "${message}4");
}
[Test]
public void CompoundRefTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
<compound-target name='rr' type='RoundRobinGroup'>
<target-ref name='d1' />
<target-ref name='d2' />
<target-ref name='d3' />
<target-ref name='d4' />
</compound-target>
</targets>
</nlog>");
Assert.IsNotNull(c.FindTargetByName("rr"));
Assert.IsNotNull(c.FindTargetByName("d1"));
Assert.IsNotNull(c.FindTargetByName("d2"));
Assert.IsNotNull(c.FindTargetByName("d3"));
Assert.IsNotNull(c.FindTargetByName("d4"));
Assert.IsInstanceOfType(typeof(RoundRobinGroupTarget), c.FindTargetByName("rr"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d1"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d2"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d3"));
Assert.IsInstanceOfType(typeof(DebugTarget), c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.AreEqual(4, rr.Targets.Count);
Assert.AreSame(d1, rr.Targets[0]);
Assert.AreSame(d2, rr.Targets[1]);
Assert.AreSame(d3, rr.Targets[2]);
Assert.AreSame(d4, rr.Targets[3]);
Assert.AreEqual(((SimpleLayout)d1.Layout).Text, "${message}1");
Assert.AreEqual(((SimpleLayout)d2.Layout).Text, "${message}2");
Assert.AreEqual(((SimpleLayout)d3.Layout).Text, "${message}3");
Assert.AreEqual(((SimpleLayout)d4.Layout).Text, "${message}4");
}
[Test]
public void AsyncWrappersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets async='true'>
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as AsyncTargetWrapper;
Assert.IsNotNull(t);
Assert.AreEqual(t.Name, "d");
var wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.IsNotNull(wrappedTarget);
Assert.AreEqual("d_wrapped", wrappedTarget.Name);
t = c.FindTargetByName("d2") as AsyncTargetWrapper;
Assert.IsNotNull(t);
Assert.AreEqual(t.Name, "d2");
wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.IsNotNull(wrappedTarget);
Assert.AreEqual("d2_wrapped", wrappedTarget.Name);
}
[Test]
public void DefaultTargetParametersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<default-target-parameters type='Debug' layout='x${message}x' />
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as DebugTarget;
Assert.IsNotNull(t);
Assert.AreEqual("'x${message}x'", t.Layout.ToString());
t = c.FindTargetByName("d2") as DebugTarget;
Assert.IsNotNull(t);
Assert.AreEqual("'x${message}x'", t.Layout.ToString());
}
[Test]
public void DefaultWrapperTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<default-wrapper type='BufferingWrapper'>
<wrapper type='RetryingWrapper' />
</default-wrapper>
<target type='Debug' name='d' layout='${level}' />
<target type='Debug' name='d2' layout='${level}' />
</targets>
</nlog>");
var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper;
Assert.IsNotNull(bufferingTargetWrapper);
var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper;
Assert.IsNotNull(retryingTargetWrapper);
Assert.IsNull(retryingTargetWrapper.Name);
var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget;
Assert.IsNotNull(debugTarget);
Assert.AreEqual("d_wrapped", debugTarget.Name);
Assert.AreEqual("'${level}'", debugTarget.Layout.ToString());
}
[Test]
public void DataTypesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyTarget;
Assert.IsNotNull(myTarget);
Assert.AreEqual((byte)42, myTarget.ByteProperty);
Assert.AreEqual((short)42, myTarget.Int16Property);
Assert.AreEqual(42, myTarget.Int32Property);
Assert.AreEqual(42000000000L, myTarget.Int64Property);
Assert.AreEqual("foobar", myTarget.StringProperty);
Assert.AreEqual(true, myTarget.BoolProperty);
Assert.AreEqual(3.14159, myTarget.DoubleProperty);
Assert.AreEqual(3.14159f, myTarget.FloatProperty);
Assert.AreEqual(MyEnum.Value3, myTarget.EnumProperty);
Assert.AreEqual(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.AreEqual(Encoding.UTF8, myTarget.EncodingProperty);
Assert.AreEqual("en-US", myTarget.CultureProperty.Name);
Assert.AreEqual(typeof(int), myTarget.TypeProperty);
Assert.AreEqual("'${level}'", myTarget.LayoutProperty.ToString());
Assert.AreEqual("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
}
[Test]
public void NullableDataTypesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyNullableTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget;
Assert.IsNotNull(myTarget);
Assert.AreEqual((byte)42, myTarget.ByteProperty);
Assert.AreEqual((short)42, myTarget.Int16Property);
Assert.AreEqual(42, myTarget.Int32Property);
Assert.AreEqual(42000000000L, myTarget.Int64Property);
Assert.AreEqual("foobar", myTarget.StringProperty);
Assert.AreEqual(true, myTarget.BoolProperty);
Assert.AreEqual(3.14159, myTarget.DoubleProperty);
Assert.AreEqual(3.14159f, myTarget.FloatProperty);
Assert.AreEqual(MyEnum.Value3, myTarget.EnumProperty);
Assert.AreEqual(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.AreEqual(Encoding.UTF8, myTarget.EncodingProperty);
Assert.AreEqual("en-US", myTarget.CultureProperty.Name);
Assert.AreEqual(typeof(int), myTarget.TypeProperty);
Assert.AreEqual("'${level}'", myTarget.LayoutProperty.ToString());
Assert.AreEqual("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
}
[Target("MyTarget")]
public class MyTarget : Target
{
public byte ByteProperty { get; set; }
public short Int16Property { get; set; }
public int Int32Property { get; set; }
public long Int64Property { get; set; }
public string StringProperty { get; set; }
public bool BoolProperty { get; set; }
public double DoubleProperty { get; set; }
public float FloatProperty { get; set; }
public MyEnum EnumProperty { get; set; }
public MyFlagsEnum FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
}
[Target("MyNullableTarget")]
public class MyNullableTarget : Target
{
public byte? ByteProperty { get; set; }
public short? Int16Property { get; set; }
public int? Int32Property { get; set; }
public long? Int64Property { get; set; }
public string StringProperty { get; set; }
public bool? BoolProperty { get; set; }
public double? DoubleProperty { get; set; }
public float? FloatProperty { get; set; }
public MyEnum? EnumProperty { get; set; }
public MyFlagsEnum? FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
}
public enum MyEnum
{
Value1,
Value2,
Value3,
}
[Flags]
public enum MyFlagsEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
}
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="FormatVersion.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Implementation of the FormatVersion class, which describes the versioning
// of an individual "format feature" within a compound file.
//
// History:
// 06/20/2002: [....]: Created
// 05/30/2003: LGolding: Ported to WCP tree.
//
//-----------------------------------------------------------------------------
// Allow use of presharp warning numbers [6506] and [6518] unknown to the compiler
#pragma warning disable 1634, 1691
using System;
using System.IO;
#if PBTCOMPILER
using MS.Utility; // For SR.cs
#else
using System.Windows;
using MS.Internal.WindowsBase; // FriendAccessAllowed
#endif
namespace MS.Internal.IO.Packaging.CompoundFile
{
///<summary>Class for manipulating version object</summary>
#if !PBTCOMPILER
[FriendAccessAllowed]
#endif
internal class FormatVersion
{
//------------------------------------------------------
//
// Public Constructors
//
//------------------------------------------------------
#region Constructors
#if !PBTCOMPILER
/// <summary>
/// Constructor for FormatVersion
/// </summary>
private FormatVersion()
{
}
#endif
/// <summary>
/// Constructor for FormatVersion with given featureId and version
/// </summary>
/// <param name="featureId">feature identifier</param>
/// <param name="version">version</param>
/// <remarks>reader, updater, and writer versions are set to version</remarks>
public FormatVersion(string featureId, VersionPair version)
: this(featureId, version, version, version)
{
}
/// <summary>
/// Constructor for FormatVersion with given featureId and reader, updater,
/// and writer version
/// </summary>
/// <param name="featureId">feature identifier</param>
/// <param name="writerVersion">Writer Version</param>
/// <param name="readerVersion">Reader Version</param>
/// <param name="updaterVersion">Updater Version</param>
public FormatVersion(String featureId,
VersionPair writerVersion,
VersionPair readerVersion,
VersionPair updaterVersion)
{
if (featureId == null)
throw new ArgumentNullException("featureId");
if (writerVersion == null)
throw new ArgumentNullException("writerVersion");
if (readerVersion == null)
throw new ArgumentNullException("readerVersion");
if (updaterVersion == null)
throw new ArgumentNullException("updaterVersion");
if (featureId.Length == 0)
{
throw new ArgumentException(SR.Get(SRID.ZeroLengthFeatureID));
}
_featureIdentifier = featureId;
_reader = readerVersion;
_updater = updaterVersion;
_writer = writerVersion;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
#if !PBTCOMPILER
/// <summary>
/// reader version
/// </summary>
public VersionPair ReaderVersion
{
get
{
return _reader;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_reader = value;
}
}
/// <summary>
/// writer version
/// </summary>
public VersionPair WriterVersion
{
get
{
return _writer;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_writer = value;
}
}
/// <summary>
/// updater version
/// </summary>
public VersionPair UpdaterVersion
{
get
{
return _updater;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_updater = value;
}
}
/// <summary>
/// feature identifier
/// </summary>
public String FeatureIdentifier
{
get
{
return _featureIdentifier;
}
}
#endif
#endregion Public Properties
#region Operators
#if false
/// <summary>
/// == comparison operator
/// </summary>
/// <param name="v1">version to be compared</param>
/// <param name="v2">version to be compared</param>
public static bool operator ==(FormatVersion v1, FormatVersion v2)
{
// We have to cast v1 and v2 to Object
// to ensure that the == operator on Ojbect class is used not the == operator on FormatVersion
if ((Object) v1 == null || (Object) v2 == null)
{
return ((Object) v1 == null && (Object) v2 == null);
}
// Do comparison only if both v1 and v2 are not null
return v1.Equals(v2);
}
/// <summary>
/// != comparison operator
/// </summary>
/// <param name="v1">version to be compared</param>
/// <param name="v2">version to be compared</param>
public static bool operator !=(FormatVersion v1, FormatVersion v2)
{
return !(v1 == v2);
}
/// <summary>
/// Eaual comparison operator
/// </summary>
/// <param name="obj">Object to compare</param>
/// <returns>ture if the object is equal to this instance</returns>
public override bool Equals(Object obj)
{
if (obj == null)
{
return false;
}
if (obj.GetType() != typeof(FormatVersion))
{
return false;
}
FormatVersion v = (FormatVersion) obj;
//PRESHARP:Parameter to this public method must be validated: A null-dereference can occur here.
// Parameter 'v' to this public method must be validated: A null-dereference can occur here.
//This is a false positive as the checks above can gurantee no null dereference will occur
#pragma warning disable 6506
if (String.CompareOrdinal(_featureIdentifier.ToUpperInvariant(), v.FeatureIdentifier.ToUpperInvariant()) != 0
|| _reader != v.ReaderVersion
|| _writer != v.WriterVersion
|| _updater != v.UpdaterVersion)
{
return false;
}
#pragma warning restore 6506
return true;
}
/// <summary>
/// Hash code
/// </summary>
public override int GetHashCode()
{
int hash = _reader.Major & HashMask;
hash <<= 5;
hash |= (_reader.Minor & HashMask);
hash <<= 5;
hash |= (_updater.Major & HashMask);
hash <<= 5;
hash |= (_updater.Minor & HashMask);
hash <<= 5;
hash |= (_writer.Major & HashMask);
hash <<= 5;
hash |= (_writer.Minor & HashMask);
return hash;
}
#endif
#endregion Operators
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
#if !PBTCOMPILER
/// <summary>
/// Constructor for FormatVersion with information read from the given stream
/// </summary>
/// <param name="stream">Stream where version information is read from</param>
/// <remarks>Before this function call the current position of stream should be
/// pointing to the begining of the version structure. After this call the current
/// poisition will be pointing immediately after the version structure</remarks>
public static FormatVersion LoadFromStream(Stream stream)
{
int bytesRead;
return LoadFromStream(stream, out bytesRead);
}
#endif
/// <summary>
/// Persist format version to the given stream
/// </summary>
/// <param name="stream">the stream to be written</param>
/// <remarks>
/// This operation will change the stream pointer
/// stream can be null and will still return the number of bytes to be written
/// </remarks>
public int SaveToStream(Stream stream)
{
checked
{
// Suppress 56518 Local IDisposable object not disposed:
// Reason: The stream is not owned by the BlockManager, therefore we can
// close the BinaryWriter as it will Close the stream underneath.
#pragma warning disable 6518
int len = 0;
BinaryWriter binarywriter = null;
#pragma warning restore 6518
if (stream != null)
{
binarywriter = new BinaryWriter(stream, System.Text.Encoding.Unicode);
}
// ************
// feature ID
// ************
len += ContainerUtilities.WriteByteLengthPrefixedDWordPaddedUnicodeString(binarywriter, _featureIdentifier);
// ****************
// Reader Version
// ****************
if (stream != null)
{
binarywriter.Write(_reader.Major); // Major number
binarywriter.Write(_reader.Minor); // Minor number
}
len += ContainerUtilities.Int16Size;
len += ContainerUtilities.Int16Size;
// *****************
// Updater Version
// *****************
if (stream != null)
{
binarywriter.Write(_updater.Major); // Major number
binarywriter.Write(_updater.Minor); // Minor number
}
len += ContainerUtilities.Int16Size;
len += ContainerUtilities.Int16Size;
// ****************
// Writer Version
// ****************
if (stream != null)
{
binarywriter.Write(_writer.Major); // Major number
binarywriter.Write(_writer.Minor); // Minor number
}
len += ContainerUtilities.Int16Size;
len += ContainerUtilities.Int16Size;
return len;
}
}
#if !PBTCOMPILER
/// <summary>
/// Check if a component with the given version can read this format version safely
/// </summary>
/// <param name="version">version of a component</param>
/// <returns>true if this format version can be read safely by the component
/// with the given version, otherwise false</returns>
/// <remarks>
/// The given version is checked against ReaderVersion
/// </remarks>
public bool IsReadableBy(VersionPair version)
{
if (version == null)
{
throw new ArgumentNullException("version");
}
return (_reader <= version);
}
/// <summary>
/// Check if a component with the given version can update this format version safely
/// </summary>
/// <param name="version">version of a component</param>
/// <returns>true if this format version can be updated safely by the component
/// with the given version, otherwise false</returns>
/// <remarks>
/// The given version is checked against UpdaterVersion
/// </remarks>
public bool IsUpdatableBy(VersionPair version)
{
if (version == null)
{
throw new ArgumentNullException("version");
}
return (_updater <= version);
}
#endif
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Internal Constructors
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#if !PBTCOMPILER
/// <summary>
/// Constructor for FormatVersion with information read from the given BinaryReader
/// </summary>
/// <param name="reader">BinaryReader where version information is read from</param>
/// <param name="bytesRead">number of bytes read including padding</param>
/// <returns>FormatVersion object</returns>
/// <remarks>
/// This operation will change the stream pointer. This function is preferred over the
/// LoadFromStream as it doesn't leave around Undisposed BinaryReader, which
/// LoadFromStream will
/// </remarks>
private static FormatVersion LoadFromBinaryReader(BinaryReader reader, out Int32 bytesRead)
{
checked
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
FormatVersion ver = new FormatVersion();
bytesRead = 0; // Initialize the number of bytes read
// **************
// feature ID
// **************
Int32 strBytes;
ver._featureIdentifier = ContainerUtilities.ReadByteLengthPrefixedDWordPaddedUnicodeString(reader, out strBytes);
bytesRead += strBytes;
Int16 major;
Int16 minor;
// ****************
// Reader Version
// ****************
major = reader.ReadInt16(); // Major number
bytesRead += ContainerUtilities.Int16Size;
minor = reader.ReadInt16(); // Minor number
bytesRead += ContainerUtilities.Int16Size;
ver.ReaderVersion = new VersionPair(major, minor);
// *****************
// Updater Version
// *****************
major = reader.ReadInt16(); // Major number
bytesRead += ContainerUtilities.Int16Size;
minor = reader.ReadInt16(); // Minor number
bytesRead += ContainerUtilities.Int16Size;
ver.UpdaterVersion = new VersionPair(major, minor);
// ****************
// Writer Version
// ****************
major = reader.ReadInt16(); // Major number
bytesRead += ContainerUtilities.Int16Size;
minor = reader.ReadInt16(); // Minor number
bytesRead += ContainerUtilities.Int16Size;
ver.WriterVersion = new VersionPair(major, minor);
return ver;
}
}
/// <summary>
/// Create FormatVersion object and read version information from the given stream
/// </summary>
/// <param name="stream">the stream to read version information from</param>
/// <param name="bytesRead">number of bytes read including padding</param>
/// <returns>FormatVersion object</returns>
/// <remarks>
/// This operation will change the stream pointer. This function shouldn't be
/// used in the scenarios when LoadFromBinaryReader can do the job.
/// LoadFromBinaryReader will not leave around any undisposed objects,
/// and LoadFromStream will.
/// </remarks>
internal static FormatVersion LoadFromStream(Stream stream, out Int32 bytesRead)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
// Suppress 56518 Local IDisposable object not disposed:
// Reason: The stream is not owned by the BlockManager, therefore we can
// close the BinaryWriter as it will Close the stream underneath.
#pragma warning disable 6518
BinaryReader streamReader = new BinaryReader(stream, System.Text.Encoding.Unicode);
#pragma warning restore 6518
return LoadFromBinaryReader(streamReader, out bytesRead);
}
#endif
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Member Variables
private VersionPair _reader;
private VersionPair _updater;
private VersionPair _writer;
private String _featureIdentifier;
#if false
static private readonly int HashMask = 0x1f;
#endif
#endregion Member Variables
}
}
| |
/*
* Vericred API
*
* Vericred's API allows you to search for Health Plans that a specific doctor
accepts.
## Getting Started
Visit our [Developer Portal](https://developers.vericred.com) to
create an account.
Once you have created an account, you can create one Application for
Production and another for our Sandbox (select the appropriate Plan when
you create the Application).
## SDKs
Our API follows standard REST conventions, so you can use any HTTP client
to integrate with us. You will likely find it easier to use one of our
[autogenerated SDKs](https://github.com/vericred/?query=vericred-),
which we make available for several common programming languages.
## Authentication
To authenticate, pass the API Key you created in the Developer Portal as
a `Vericred-Api-Key` header.
`curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Versioning
Vericred's API default to the latest version. However, if you need a specific
version, you can request it with an `Accept-Version` header.
The current version is `v3`. Previous versions are `v1` and `v2`.
`curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Pagination
Endpoints that accept `page` and `per_page` parameters are paginated. They expose
four additional fields that contain data about your position in the response,
namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988).
For example, to display 5 results per page and view the second page of a
`GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`.
## Sideloading
When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s
we sideload the associated data. In this example, we would provide an Array of
`State`s and a `state_id` for each provider. This is done primarily to reduce the
payload size since many of the `Provider`s will share a `State`
```
{
providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }],
states: [{ id: 1, code: 'NY' }]
}
```
If you need the second level of the object graph, you can just match the
corresponding id.
## Selecting specific data
All endpoints allow you to specify which fields you would like to return.
This allows you to limit the response to contain only the data you need.
For example, let's take a request that returns the following JSON by default
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890',
field_we_dont_care_about: 'value_we_dont_care_about'
},
states: [{
id: 1,
name: 'New York',
code: 'NY',
field_we_dont_care_about: 'value_we_dont_care_about'
}]
}
```
To limit our results to only return the fields we care about, we specify the
`select` query string parameter for the corresponding fields in the JSON
document.
In this case, we want to select `name` and `phone` from the `provider` key,
so we would add the parameters `select=provider.name,provider.phone`.
We also want the `name` and `code` from the `states` key, so we would
add the parameters `select=states.name,staes.code`. The id field of
each document is always returned whether or not it is requested.
Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code`
The response would be
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890'
},
states: [{
id: 1,
name: 'New York',
code: 'NY'
}]
}
```
## Benefits summary format
Benefit cost-share strings are formatted to capture:
* Network tiers
* Compound or conditional cost-share
* Limits on the cost-share
* Benefit-specific maximum out-of-pocket costs
**Example #1**
As an example, we would represent [this Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as:
* **Hospital stay facility fees**:
- Network Provider: `$400 copay/admit plus 20% coinsurance`
- Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance`
- Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible`
* **Rehabilitation services:**
- Network Provider: `20% coinsurance`
- Out-of-Network Provider: `50% coinsurance`
- Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.`
- Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period`
**Example #2**
In [this other Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies.
* **Specialty drugs:**
- Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply`
- Out-of-Network Provider `Not covered`
- Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%`
**BNF**
Here's a description of the benefits summary string, represented as a context-free grammar:
```
<cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit>
<tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:"
<opt-num-prefix> ::= "first" <num> <unit> | ""
<unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)"
<value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable"
<compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible>
<copay> ::= "$" <num>
<coinsurace> ::= <num> "%"
<ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited"
<opt-per-unit> ::= "per day" | "per visit" | "per stay" | ""
<deductible> ::= "before deductible" | "after deductible" | ""
<tier-limit> ::= ", " <limit> | ""
<benefit-limit> ::= <limit> | ""
```
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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 System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.Vericred.Model
{
/// <summary>
/// DrugSearchResponse
/// </summary>
[DataContract]
public partial class DrugSearchResponse : IEquatable<DrugSearchResponse>
{
/// <summary>
/// Initializes a new instance of the <see cref="DrugSearchResponse" /> class.
/// </summary>
/// <param name="Meta">Meta-data.</param>
/// <param name="Drugs">Drugs found in query.</param>
/// <param name="DrugPackages">DrugPackages.</param>
public DrugSearchResponse(Meta Meta = null, List<Drug> Drugs = null, List<DrugPackage> DrugPackages = null)
{
this.Meta = Meta;
this.Drugs = Drugs;
this.DrugPackages = DrugPackages;
}
/// <summary>
/// Meta-data
/// </summary>
/// <value>Meta-data</value>
[DataMember(Name="meta", EmitDefaultValue=false)]
public Meta Meta { get; set; }
/// <summary>
/// Drugs found in query
/// </summary>
/// <value>Drugs found in query</value>
[DataMember(Name="drugs", EmitDefaultValue=false)]
public List<Drug> Drugs { get; set; }
/// <summary>
/// DrugPackages
/// </summary>
/// <value>DrugPackages</value>
[DataMember(Name="drug_packages", EmitDefaultValue=false)]
public List<DrugPackage> DrugPackages { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DrugSearchResponse {\n");
sb.Append(" Meta: ").Append(Meta).Append("\n");
sb.Append(" Drugs: ").Append(Drugs).Append("\n");
sb.Append(" DrugPackages: ").Append(DrugPackages).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as DrugSearchResponse);
}
/// <summary>
/// Returns true if DrugSearchResponse instances are equal
/// </summary>
/// <param name="other">Instance of DrugSearchResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DrugSearchResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Meta == other.Meta ||
this.Meta != null &&
this.Meta.Equals(other.Meta)
) &&
(
this.Drugs == other.Drugs ||
this.Drugs != null &&
this.Drugs.SequenceEqual(other.Drugs)
) &&
(
this.DrugPackages == other.DrugPackages ||
this.DrugPackages != null &&
this.DrugPackages.SequenceEqual(other.DrugPackages)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Meta != null)
hash = hash * 59 + this.Meta.GetHashCode();
if (this.Drugs != null)
hash = hash * 59 + this.Drugs.GetHashCode();
if (this.DrugPackages != null)
hash = hash * 59 + this.DrugPackages.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using umbraco.interfaces;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Sync
{
/// <summary>
/// An <see cref="IServerMessenger"/> that works by storing messages in the database.
/// </summary>
//
// this messenger writes ALL instructions to the database,
// but only processes instructions coming from remote servers,
// thus ensuring that instructions run only once
//
public class DatabaseServerMessenger : ServerMessengerBase
{
private readonly ApplicationContext _appContext;
private readonly DatabaseServerMessengerOptions _options;
private readonly ManualResetEvent _syncIdle;
private readonly object _locko = new object();
private readonly ILogger _logger;
private int _lastId = -1;
private DateTime _lastSync;
private DateTime _lastPruned;
private bool _initialized;
private bool _syncing;
private bool _released;
private readonly ProfilingLogger _profilingLogger;
protected ApplicationContext ApplicationContext { get { return _appContext; } }
public DatabaseServerMessenger(ApplicationContext appContext, bool distributedEnabled, DatabaseServerMessengerOptions options)
: base(distributedEnabled)
{
if (appContext == null) throw new ArgumentNullException("appContext");
if (options == null) throw new ArgumentNullException("options");
_appContext = appContext;
_options = options;
_lastPruned = _lastSync = DateTime.UtcNow;
_syncIdle = new ManualResetEvent(true);
_profilingLogger = appContext.ProfilingLogger;
_logger = appContext.ProfilingLogger.Logger;
}
#region Messenger
protected override bool RequiresDistributed(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, MessageType dispatchType)
{
// we don't care if there's servers listed or not,
// if distributed call is enabled we will make the call
return _initialized && DistributedEnabled;
}
protected override void DeliverRemote(
IEnumerable<IServerAddress> servers,
ICacheRefresher refresher,
MessageType messageType,
IEnumerable<object> ids = null,
string json = null)
{
var idsA = ids == null ? null : ids.ToArray();
Type idType;
if (GetArrayType(idsA, out idType) == false)
throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids");
var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json);
var dto = new CacheInstructionDto
{
UtcStamp = DateTime.UtcNow,
Instructions = JsonConvert.SerializeObject(instructions, Formatting.None),
OriginIdentity = LocalIdentity
};
ApplicationContext.DatabaseContext.Database.Insert(dto);
}
#endregion
#region Sync
/// <summary>
/// Boots the messenger.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
protected void Boot()
{
// weight:10, must release *before* the facade service, because once released
// the service will *not* be able to properly handle our notifications anymore
const int weight = 10;
var registered = ApplicationContext.MainDom.Register(
() =>
{
lock (_locko)
{
_released = true; // no more syncs
}
_syncIdle.WaitOne(); // wait for pending sync
},
weight);
if (registered == false)
return;
ReadLastSynced(); // get _lastId
EnsureInstructions(); // reset _lastId if instrs are missing
Initialize(); // boot
}
/// <summary>
/// Initializes a server that has never synchronized before.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
private void Initialize()
{
lock (_locko)
{
if (_released) return;
var coldboot = false;
if (_lastId < 0) // never synced before
{
// we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new
// server and it will need to rebuild it's own caches, eg Lucene or the xml cache file.
_logger.Warn<DatabaseServerMessenger>("No last synced Id found, this generally means this is a new server/install."
+ " The server will build its caches and indexes, and then adjust its last synced Id to the latest found in"
+ " the database and maintain cache updates based on that Id.");
coldboot = true;
}
else
{
//check for how many instructions there are to process
var count = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoCacheInstruction WHERE id > @lastId", new {lastId = _lastId});
if (count > _options.MaxProcessingInstructionCount)
{
//too many instructions, proceed to cold boot
_logger.Warn<DatabaseServerMessenger>("The instruction count ({0}) exceeds the specified MaxProcessingInstructionCount ({1})."
+ " The server will skip existing instructions, rebuild its caches and indexes entirely, adjust its last synced Id"
+ " to the latest found in the database and maintain cache updates based on that Id.",
() => count, () => _options.MaxProcessingInstructionCount);
coldboot = true;
}
}
if (coldboot)
{
// go get the last id in the db and store it
// note: do it BEFORE initializing otherwise some instructions might get lost
// when doing it before, some instructions might run twice - not an issue
var maxId = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction");
//if there is a max currently, or if we've never synced
if (maxId > 0 || _lastId < 0)
SaveLastSynced(maxId);
// execute initializing callbacks
if (_options.InitializingCallbacks != null)
foreach (var callback in _options.InitializingCallbacks)
callback();
}
_initialized = true;
}
}
/// <summary>
/// Synchronize the server (throttled).
/// </summary>
protected void Sync()
{
lock (_locko)
{
if (_syncing)
return;
if (_released)
return;
if ((DateTime.UtcNow - _lastSync).TotalSeconds <= _options.ThrottleSeconds)
return;
_syncing = true;
_syncIdle.Reset();
_lastSync = DateTime.UtcNow;
}
try
{
using (_profilingLogger.DebugDuration<DatabaseServerMessenger>("Syncing from database..."))
{
ProcessDatabaseInstructions();
if ((DateTime.UtcNow - _lastPruned).TotalSeconds <= _options.PruneThrottleSeconds)
return;
_lastPruned = _lastSync;
switch (_appContext.GetCurrentServerRole())
{
case ServerRole.Single:
case ServerRole.Master:
PruneOldInstructions();
break;
}
}
}
finally
{
_syncing = false;
_syncIdle.Set();
}
}
/// <summary>
/// Process instructions from the database.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
/// <returns>
/// Returns the number of processed instructions
/// </returns>
private void ProcessDatabaseInstructions()
{
// NOTE
// we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that
// would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests
// (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are
// pending requests after being processed, they'll just be processed on the next poll.
//
// FIXME not true if we're running on a background thread, assuming we can?
var sql = new Sql().Select("*")
.From<CacheInstructionDto>(_appContext.DatabaseContext.SqlSyntax)
.Where<CacheInstructionDto>(dto => dto.Id > _lastId)
.OrderBy<CacheInstructionDto>(dto => dto.Id, _appContext.DatabaseContext.SqlSyntax);
var dtos = _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(sql);
if (dtos.Count <= 0) return;
// only process instructions coming from a remote server, and ignore instructions coming from
// the local server as they've already been processed. We should NOT assume that the sequence of
// instructions in the database makes any sense whatsoever, because it's all async.
var localIdentity = LocalIdentity;
var lastId = 0;
foreach (var dto in dtos)
{
if (dto.OriginIdentity == localIdentity)
{
// just skip that local one but update lastId nevertheless
lastId = dto.Id;
continue;
}
// deserialize remote instructions & skip if it fails
JArray jsonA;
try
{
jsonA = JsonConvert.DeserializeObject<JArray>(dto.Instructions);
}
catch (JsonException ex)
{
_logger.Error<DatabaseServerMessenger>(string.Format("Failed to deserialize instructions ({0}: \"{1}\").", dto.Id, dto.Instructions), ex);
lastId = dto.Id; // skip
continue;
}
// execute remote instructions & update lastId
try
{
NotifyRefreshers(jsonA);
lastId = dto.Id;
}
catch (Exception ex)
{
_logger.Error<DatabaseServerMessenger>(
string.Format("DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({0}: \"{1}\"). Instruction is being skipped/ignored", dto.Id, dto.Instructions), ex);
//we cannot throw here because this invalid instruction will just keep getting processed over and over and errors
// will be thrown over and over. The only thing we can do is ignore and move on.
lastId = dto.Id;
}
}
if (lastId > 0)
SaveLastSynced(lastId);
}
/// <summary>
/// Remove old instructions from the database
/// </summary>
/// <remarks>
/// Always leave the last (most recent) record in the db table, this is so that not all instructions are removed which would cause
/// the site to cold boot if there's been no instruction activity for more than DaysToRetainInstructions.
/// See: http://issues.umbraco.org/issue/U4-7643#comment=67-25085
/// </remarks>
private void PruneOldInstructions()
{
var pruneDate = DateTime.UtcNow.AddDays(-_options.DaysToRetainInstructions);
// using 2 queries is faster than convoluted joins
var maxId = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction;");
var delete = new Sql().Append(@"DELETE FROM umbracoCacheInstruction WHERE utcStamp < @pruneDate AND id < @maxId",
new { pruneDate, maxId });
_appContext.DatabaseContext.Database.Execute(delete);
}
/// <summary>
/// Ensure that the last instruction that was processed is still in the database.
/// </summary>
/// <remarks>
/// If the last instruction is not in the database anymore, then the messenger
/// should not try to process any instructions, because some instructions might be lost,
/// and it should instead cold-boot.
/// However, if the last synced instruction id is '0' and there are '0' records, then this indicates
/// that it's a fresh site and no user actions have taken place, in this circumstance we do not want to cold
/// boot. See: http://issues.umbraco.org/issue/U4-8627
/// </remarks>
private void EnsureInstructions()
{
if (_lastId == 0)
{
var sql = new Sql().Select("COUNT(*)")
.From<CacheInstructionDto>(_appContext.DatabaseContext.SqlSyntax);
var count = _appContext.DatabaseContext.Database.ExecuteScalar<int>(sql);
//if there are instructions but we haven't synced, then a cold boot is necessary
if (count > 0)
_lastId = -1;
}
else
{
var sql = new Sql().Select("*")
.From<CacheInstructionDto>(_appContext.DatabaseContext.SqlSyntax)
.Where<CacheInstructionDto>(dto => dto.Id == _lastId);
var dtos = _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(sql);
//if the last synced instruction is not found in the db, then a cold boot is necessary
if (dtos.Count == 0)
_lastId = -1;
}
}
/// <summary>
/// Reads the last-synced id from file into memory.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void ReadLastSynced()
{
var path = SyncFilePath;
if (File.Exists(path) == false) return;
var content = File.ReadAllText(path);
int last;
if (int.TryParse(content, out last))
_lastId = last;
}
/// <summary>
/// Updates the in-memory last-synced id and persists it to file.
/// </summary>
/// <param name="id">The id.</param>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void SaveLastSynced(int id)
{
File.WriteAllText(SyncFilePath, id.ToString(CultureInfo.InvariantCulture));
_lastId = id;
}
/// <summary>
/// Gets the unique local identity of the executing AppDomain.
/// </summary>
/// <remarks>
/// <para>It is not only about the "server" (machine name and appDomainappId), but also about
/// an AppDomain, within a Process, on that server - because two AppDomains running at the same
/// time on the same server (eg during a restart) are, practically, a LB setup.</para>
/// <para>Practically, all we really need is the guid, the other infos are here for information
/// and debugging purposes.</para>
/// </remarks>
protected static readonly string LocalIdentity = NetworkHelper.MachineName // eg DOMAIN\SERVER
+ "/" + HttpRuntime.AppDomainAppId // eg /LM/S3SVC/11/ROOT
+ " [P" + Process.GetCurrentProcess().Id // eg 1234
+ "/D" + AppDomain.CurrentDomain.Id // eg 22
+ "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique
/// <summary>
/// Gets the sync file path for the local server.
/// </summary>
/// <returns>The sync file path for the local server.</returns>
private static string SyncFilePath
{
get
{
var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/DistCache/" + NetworkHelper.FileSafeMachineName);
if (Directory.Exists(tempFolder) == false)
Directory.CreateDirectory(tempFolder);
return Path.Combine(tempFolder, HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt");
}
}
#endregion
#region Notify refreshers
private static ICacheRefresher GetRefresher(Guid id)
{
var refresher = CacheRefreshersResolver.Current.GetById(id);
if (refresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist.");
return refresher;
}
private static IJsonCacheRefresher GetJsonRefresher(Guid id)
{
return GetJsonRefresher(GetRefresher(id));
}
private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher)
{
var jsonRefresher = refresher as IJsonCacheRefresher;
if (jsonRefresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + refresher.UniqueIdentifier + "\" does not implement " + typeof(IJsonCacheRefresher) + ".");
return jsonRefresher;
}
private static void NotifyRefreshers(IEnumerable<JToken> jsonArray)
{
foreach (var jsonItem in jsonArray)
{
// could be a JObject in which case we can convert to a RefreshInstruction,
// otherwise it could be another JArray - in which case we'll iterate that.
var jsonObj = jsonItem as JObject;
if (jsonObj != null)
{
var instruction = jsonObj.ToObject<RefreshInstruction>();
switch (instruction.RefreshType)
{
case RefreshMethodType.RefreshAll:
RefreshAll(instruction.RefresherId);
break;
case RefreshMethodType.RefreshByGuid:
RefreshByGuid(instruction.RefresherId, instruction.GuidId);
break;
case RefreshMethodType.RefreshById:
RefreshById(instruction.RefresherId, instruction.IntId);
break;
case RefreshMethodType.RefreshByIds:
RefreshByIds(instruction.RefresherId, instruction.JsonIds);
break;
case RefreshMethodType.RefreshByJson:
RefreshByJson(instruction.RefresherId, instruction.JsonPayload);
break;
case RefreshMethodType.RemoveById:
RemoveById(instruction.RefresherId, instruction.IntId);
break;
}
}
else
{
var jsonInnerArray = (JArray) jsonItem;
NotifyRefreshers(jsonInnerArray); // recurse
}
}
}
private static void RefreshAll(Guid uniqueIdentifier)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.RefreshAll();
}
private static void RefreshByGuid(Guid uniqueIdentifier, Guid id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshByIds(Guid uniqueIdentifier, string jsonIds)
{
var refresher = GetRefresher(uniqueIdentifier);
foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds))
refresher.Refresh(id);
}
private static void RefreshByJson(Guid uniqueIdentifier, string jsonPayload)
{
var refresher = GetJsonRefresher(uniqueIdentifier);
refresher.Refresh(jsonPayload);
}
private static void RemoveById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Remove(id);
}
#endregion
}
}
| |
// Copyright 2020 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
//
// 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.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace YetiCommon
{
// Indicates errors running a process
public class ProcessException : Exception
{
public ProcessException(string message) : base(message)
{
}
public ProcessException(string message, Exception e) : base(message, e)
{
}
}
// A wrapper for System.Diagnostics.Process.
public interface IProcess : IDisposable
{
/// <summary>
/// The ID of the process, as reported by the OS after the process has been started.
/// </summary>
int Id { get; }
/// <summary>
/// The name of the process, as reported by the OS after the process has been started.
/// </summary>
string ProcessName { get; }
/// <summary>
/// The exit code of the process, which is reported after the process exited.
/// </summary>
int ExitCode { get; }
/// <summary>
/// The starting information which was specified when creating this process.
/// </summary>
ProcessStartInfo StartInfo { get; }
/// <summary>
/// Event triggered when the process produces output (stdout).
/// </summary>
event TextReceivedEventHandler OutputDataReceived;
/// <summary>
/// Event triggered when the process produces error output (stderr).
/// </summary>
event TextReceivedEventHandler ErrorDataReceived;
/// <summary>
/// Standard output stream of the process. This should only be used if the
/// process was started with the standardOutputReadLine parameter set
/// to false.
/// </summary>
StreamReader StandardOutput { get; }
/// <summary>
/// Event triggered when the process exits.
/// </summary>
/// <remarks>
/// The exit event may be triggered asynchronously w.r.t. data received events.
/// Do not assume that all data has been received when this event is triggered.
/// </remarks>
event EventHandler OnExit;
/// <summary>
/// Starts the process and returns immediately.
/// </summary>
/// <param name="standardOutputReadLine">
/// Determines if the the process should automatically read standard output by lines and
/// call the OutputDataReceived for each line. If the parameter is false, the caller
/// is responsible for consuming the StandardOutput stream of the process.
/// </param>
/// <exception cref="ProcessException">
/// Thrown if there is an error launching the process.
/// </exception>
/// <seealso cref="RunToExitAsync"/>
void Start(bool standardOutputReadLine = true);
/// <summary>
/// Attempts to kill the process immediately. OnExit will not be called.
/// </summary>
/// <remarks>
/// If the process has already exited or cannot be killed, then this call is a no-op.
/// </remarks>
void Kill();
/// <summary>
/// Launches the process and returns a task that waits for the process to exit and yields
/// the exit code of the process as the result.
/// </summary>
/// <exception cref="ProcessException">Thrown if launching the process fails.</exception>
/// <remarks>
/// Output and error data handlers are guaranteed to be called before this task completes.
/// </remarks>
Task<int> RunToExitAsync();
/// <summary>
/// Returns a task that waits for the started process to exit and yields
/// the exit code of the process as the result.
/// Throws ProcessException if the wait times out or if an error occurs.
/// </summary>
/// <remarks>
/// Output and error data handlers are guaranteed to be called before this task completes.
/// </remarks>
/// <returns>The process exit code.</returns>
Task<int> WaitForExitAsync();
/// <summary>
/// Waits for the started process to exit. Returns false on error. Does not throw.
/// </summary>
/// <param name="timeout">Timeout to wait</param>
/// <returns>True if the process exited.</returns>
bool WaitForExit(TimeSpan timeout);
}
public delegate void TextReceivedEventHandler(object sender, TextReceivedEventArgs args);
public class TextReceivedEventArgs : EventArgs
{
public string Text { get; }
public TextReceivedEventArgs(string text)
{
Text = text;
}
}
// A wrapper for Process that ties the process execution to a local job object.
public class ManagedProcess : IProcess
{
public class Factory
{
public virtual IProcess Create(ProcessStartInfo startInfo, int timeoutMs = 30 * 1000) =>
new ManagedProcess(startInfo, timeoutMs);
public virtual IProcess CreateVisible(ProcessStartInfo startInfo,
int timeoutMs = 30 * 1000) =>
new ManagedProcess(startInfo, timeoutMs, true);
}
readonly int _timeoutMs;
// System structures and functions needed to make a Windows API call that will tie a
// spawned process's lifetime to a local object.
public enum JobObjectInfoType
{
AssociateCompletionPortInformation = 7,
BasicLimitInformation = 2,
BasicUiRestrictions = 4,
EndOfJobTimeInformation = 6,
ExtendedLimitInformation = 9,
SecurityLimitInformation = 5,
GroupInformation = 11
}
// Windows data types reference:
// https://docs.microsoft.com/en-us/windows/win32/winprog/windows-data-types
[StructLayout(LayoutKind.Sequential)]
struct JobObjectBasicLimitInformation
{
public Int64 PerProcessUserTimeLimit;
public Int64 PerJobUserTimeLimit;
public UInt32 LimitFlags;
public UIntPtr MinimumWorkingSetSize;
public UIntPtr MaximumWorkingSetSize;
public UInt32 ActiveProcessLimit;
public UIntPtr Affinity;
public UInt32 PriorityClass;
public UInt32 SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
struct IoCounters
{
public UInt64 ReadOperationCount;
public UInt64 WriteOperationCount;
public UInt64 OtherOperationCount;
public UInt64 ReadTransferCount;
public UInt64 WriteTransferCount;
public UInt64 OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
struct JobobjectExtendedLimitInformation
{
public JobObjectBasicLimitInformation BasicLimitInformation;
public IoCounters IoInfo;
public UIntPtr ProcessMemoryLimit;
public UIntPtr JobMemoryLimit;
public UIntPtr PeakProcessMemoryUsed;
public UIntPtr PeakJobMemoryUsed;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr CreateJobObject(IntPtr a, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType,
IntPtr lpJobObjectInfo,
UInt32 cbJobObjectInfoLength);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
[DllImport("Kernel32")]
static extern bool CloseHandle(IntPtr handle);
readonly Process _process;
readonly IntPtr _handle;
public ProcessStartInfo StartInfo => _process.StartInfo;
public int ExitCode => _process.ExitCode;
// Local copies of process info to print during Dispose/Finalize.
public string ProcessName { get; private set; }
public int Id { get; private set; }
public event TextReceivedEventHandler OutputDataReceived;
public event TextReceivedEventHandler ErrorDataReceived;
public event EventHandler OnExit;
bool _disposed;
ManagedProcess(ProcessStartInfo startInfo, int timeoutMs, bool showWindow = false)
{
_process = new Process { StartInfo = startInfo };
_timeoutMs = timeoutMs;
if (showWindow)
{
// When launching the process, show the window. Don't redirect standard output so
// it can appear in the console window if applicable, but still redirect standard
// error so errors are logged.
_process.StartInfo.RedirectStandardInput = false;
_process.StartInfo.RedirectStandardOutput = false;
_process.StartInfo.RedirectStandardError = true;
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.CreateNoWindow = false;
}
else
{
_process.StartInfo.RedirectStandardInput = true;
_process.StartInfo.RedirectStandardOutput = true;
_process.StartInfo.RedirectStandardError = true;
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.CreateNoWindow = true;
}
_process.OutputDataReceived += OutputHandler;
_process.ErrorDataReceived += ErrorHandler;
_process.EnableRaisingEvents = true;
_process.Exited += ExitHandler;
_handle = CreateJobObject(IntPtr.Zero, null);
var info = new JobObjectBasicLimitInformation
{
LimitFlags = 0x2000
};
var extendedInfo = new JobobjectExtendedLimitInformation
{
BasicLimitInformation = info
};
int length = Marshal.SizeOf(typeof(JobobjectExtendedLimitInformation));
IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);
if (!SetInformationJobObject(_handle, JobObjectInfoType.ExtendedLimitInformation,
extendedInfoPtr, (uint) length))
{
throw new Exception(
ErrorStrings.FailedToSetJobLimitInfo(Marshal.GetLastWin32Error()));
}
}
~ManagedProcess()
{
Dispose(false);
}
// Attempts to start the process and returns as soon as it has started.
// Throws ProcessException if the process cannot be started.
public void Start(bool standardOutputReadLine = true)
{
try
{
_process.Start();
Id = _process.Id;
ProcessName = Path.GetFileName(_process.StartInfo.FileName);
AssignProcessToJobObject(_handle, _process.Handle);
Trace.WriteLine($"Started {_process.StartInfo.FileName} " +
$"{_process.StartInfo.Arguments} with id {Id}");
if (_process.StartInfo.RedirectStandardError)
{
_process.BeginErrorReadLine();
}
if (_process.StartInfo.RedirectStandardOutput && standardOutputReadLine)
{
_process.BeginOutputReadLine();
}
}
catch (Exception e) when (e is InvalidOperationException || e is Win32Exception)
{
string name = Path.GetFileName(_process.StartInfo.FileName);
Trace.WriteLine($"Error launching {name}: {e}");
throw new ProcessException(
ErrorStrings.FailedToLaunchProcess(_process.StartInfo.FileName, e.Message), e);
}
}
// Attempts to start the process and returns a task that is completed when the process
// exits. The result of the task is the exit code of the process.
// Throws ProcessException if the process cannot be started.
//
// The resulting task may fail with a ProcessException if the process does not exit within
// the timeout specified at construction time.
public async Task<int> RunToExitAsync()
{
Start();
return await WaitForExitAsync();
}
public async Task<int> WaitForExitAsync()
{
try
{
await Task.Run(() =>
{
if (!_process.WaitForExit(_timeoutMs))
{
Trace.WriteLine($"Timeout waiting for {ProcessName} [{Id}]");
throw new ProcessException(
ErrorStrings.TimeoutWaitingForProcess(ProcessName));
}
// WaitForExit(int) does not guarantee that data received handlers
// completed. Instead, the documentation tells us to call WaitForExit().
_process.WaitForExit();
});
return _process.ExitCode;
}
catch (Exception e) when (e is InvalidOperationException || e is Win32Exception)
{
Trace.WriteLine($"Error waiting for {ProcessName} [{Id}]: {e}");
throw new ProcessException(
ErrorStrings.ErrorWaitingForProcess(ProcessName, e.Message), e);
}
}
public bool WaitForExit(TimeSpan timeout)
{
try
{
return _process.WaitForExit((int) timeout.TotalMilliseconds);
}
catch (Exception e) when (e is SystemException || e is Win32Exception)
{
Trace.WriteLine($"Error waiting for {ProcessName} [{Id}]: {e}");
return false;
}
}
public void Kill()
{
_process.Exited -= ExitHandler;
try
{
Trace.WriteLine($"Killing process {ProcessName} [{Id}]");
_process.Kill();
}
catch (Exception e) when (e is InvalidOperationException || e is Win32Exception)
{
Trace.WriteLine($"Couldn't kill process {ProcessName} [{Id}]," +
" probably already stopping or stopped");
}
}
void OutputHandler(object sender, DataReceivedEventArgs args)
{
if (_disposed)
{
return;
}
if (OutputDataReceived != null)
{
OutputDataReceived(this, new TextReceivedEventArgs(args.Data));
}
else
{
Trace.WriteLine($"{ProcessName} [{Id}] stdout> {args.Data}");
}
}
void ErrorHandler(object sender, DataReceivedEventArgs args)
{
if (_disposed)
{
return;
}
if (ErrorDataReceived != null)
{
ErrorDataReceived(this, new TextReceivedEventArgs(args.Data));
}
else
{
Trace.WriteLine($"{ProcessName} [{Id}] stderr> {args.Data}");
}
}
void ExitHandler(object sender, EventArgs args)
{
if (_disposed)
{
return;
}
OnExit?.Invoke(this, args);
try
{
Trace.WriteLine($"Process {ProcessName} [{Id}] exited with code {ExitCode}");
}
// This should never happen, but for some reason it does, see (internal).
catch (InvalidOperationException exception)
{
Trace.WriteLine($"Failed to read an exit code of the process {ProcessName} " +
$"[{Id}] due to `{exception.Message}`, the process is already disposed.");
}
}
public StreamReader StandardOutput => _process.StandardOutput;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
Trace.WriteLine($"Dispose ({disposing}) job for process {ProcessName} [{Id}]");
if (disposing)
{
_process.Dispose();
}
CloseHandle(_handle);
}
}
}
| |
using UnityEngine;
namespace Zenject
{
// Zero parameters
// NOTE: For this to work, the given component must be at the root game object of the thing
// you want to use in a pool
public class MonoMemoryPool<TValue> : MemoryPool<TValue>
where TValue : Component
{
Transform _originalParent;
[Inject]
public MonoMemoryPool()
{
}
protected override void OnCreated(TValue item)
{
item.gameObject.SetActive(false);
// Record the original parent which will be set to whatever is used in the UnderTransform method
_originalParent = item.transform.parent;
}
protected override void OnDestroyed(TValue item)
{
GameObject.Destroy(item.gameObject);
}
protected override void OnSpawned(TValue item)
{
item.gameObject.SetActive(true);
}
protected override void OnDespawned(TValue item)
{
item.gameObject.SetActive(false);
if (item.transform.parent != _originalParent)
{
item.transform.SetParent(_originalParent, false);
}
}
}
// One parameter
// NOTE: For this to work, the given component must be at the root game object of the thing
// you want to use in a pool
public class MonoMemoryPool<TParam1, TValue> : MemoryPool<TParam1, TValue>
where TValue : Component
{
Transform _originalParent;
[Inject]
public MonoMemoryPool()
{
}
protected override void OnCreated(TValue item)
{
item.gameObject.SetActive(false);
// Record the original parent which will be set to whatever is used in the UnderTransform method
_originalParent = item.transform.parent;
}
protected override void OnDestroyed(TValue item)
{
GameObject.Destroy(item.gameObject);
}
protected override void OnSpawned(TValue item)
{
item.gameObject.SetActive(true);
}
protected override void OnDespawned(TValue item)
{
item.gameObject.SetActive(false);
if (item.transform.parent != _originalParent)
{
item.transform.SetParent(_originalParent, false);
}
}
}
// Two parameters
// NOTE: For this to work, the given component must be at the root game object of the thing
// you want to use in a pool
public class MonoMemoryPool<TParam1, TParam2, TValue>
: MemoryPool<TParam1, TParam2, TValue>
where TValue : Component
{
Transform _originalParent;
[Inject]
public MonoMemoryPool()
{
}
protected override void OnCreated(TValue item)
{
item.gameObject.SetActive(false);
// Record the original parent which will be set to whatever is used in the UnderTransform method
_originalParent = item.transform.parent;
}
protected override void OnDestroyed(TValue item)
{
GameObject.Destroy(item.gameObject);
}
protected override void OnSpawned(TValue item)
{
item.gameObject.SetActive(true);
}
protected override void OnDespawned(TValue item)
{
item.gameObject.SetActive(false);
if (item.transform.parent != _originalParent)
{
item.transform.SetParent(_originalParent, false);
}
}
}
// Three parameters
// NOTE: For this to work, the given component must be at the root game object of the thing
// you want to use in a pool
public class MonoMemoryPool<TParam1, TParam2, TParam3, TValue>
: MemoryPool<TParam1, TParam2, TParam3, TValue>
where TValue : Component
{
Transform _originalParent;
[Inject]
public MonoMemoryPool()
{
}
protected override void OnCreated(TValue item)
{
item.gameObject.SetActive(false);
// Record the original parent which will be set to whatever is used in the UnderTransform method
_originalParent = item.transform.parent;
}
protected override void OnDestroyed(TValue item)
{
GameObject.Destroy(item.gameObject);
}
protected override void OnSpawned(TValue item)
{
item.gameObject.SetActive(true);
}
protected override void OnDespawned(TValue item)
{
item.gameObject.SetActive(false);
if (item.transform.parent != _originalParent)
{
item.transform.SetParent(_originalParent, false);
}
}
}
// Four parameters
// NOTE: For this to work, the given component must be at the root game object of the thing
// you want to use in a pool
public class MonoMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue>
: MemoryPool<TParam1, TParam2, TParam3, TParam4, TValue>
where TValue : Component
{
Transform _originalParent;
[Inject]
public MonoMemoryPool()
{
}
protected override void OnCreated(TValue item)
{
item.gameObject.SetActive(false);
// Record the original parent which will be set to whatever is used in the UnderTransform method
_originalParent = item.transform.parent;
}
protected override void OnDestroyed(TValue item)
{
GameObject.Destroy(item.gameObject);
}
protected override void OnSpawned(TValue item)
{
item.gameObject.SetActive(true);
}
protected override void OnDespawned(TValue item)
{
item.gameObject.SetActive(false);
if (item.transform.parent != _originalParent)
{
item.transform.SetParent(_originalParent, false);
}
}
}
// Five parameters
// NOTE: For this to work, the given component must be at the root game object of the thing
// you want to use in a pool
public class MonoMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>
: MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>
where TValue : Component
{
Transform _originalParent;
[Inject]
public MonoMemoryPool()
{
}
protected override void OnCreated(TValue item)
{
item.gameObject.SetActive(false);
// Record the original parent which will be set to whatever is used in the UnderTransform method
_originalParent = item.transform.parent;
}
protected override void OnDestroyed(TValue item)
{
GameObject.Destroy(item.gameObject);
}
protected override void OnSpawned(TValue item)
{
item.gameObject.SetActive(true);
}
protected override void OnDespawned(TValue item)
{
item.gameObject.SetActive(false);
if (item.transform.parent != _originalParent)
{
item.transform.SetParent(_originalParent, false);
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TooltipDrawer.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.Unity.Editor.Common.Inspectors.Utils
{
using System;
using System.Reflection;
using Slash.Unity.Common.Utils;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
/// <summary>
/// Shows a tooltip next to a property in the Unity inspector.
/// </summary>
/// <seealso href="http://forum.unity3d.com/threads/182621-Inspector-Tooltips" />
[CustomPropertyDrawer(typeof(InspectorTooltipAttribute))]
public class TooltipDrawer : PropertyDrawer
{
#region Static Fields
private static Type editorType;
private static MethodInfo layerMaskFieldMethod;
#endregion
#region Fields
private Type fieldType;
private GUIContent label;
private GUIContent oldlabel;
#endregion
#region Properties
private static Type EditorType
{
get
{
if (editorType == null)
{
Assembly assembly = Assembly.GetAssembly(typeof(EditorGUI));
editorType = assembly.GetType("UnityEditor.EditorGUI");
if (editorType == null)
{
Debug.LogWarning("TooltipDrawer: Failed to open source file of EditorGUI");
}
}
return editorType;
}
}
private static MethodInfo LayerMaskFieldMethod
{
get
{
if (layerMaskFieldMethod == null)
{
Type[] typeDecleration = new[] { typeof(Rect), typeof(SerializedProperty), typeof(GUIContent) };
layerMaskFieldMethod = EditorType.GetMethod(
"LayerMaskField",
BindingFlags.NonPublic | BindingFlags.Static,
Type.DefaultBinder,
typeDecleration,
null);
if (layerMaskFieldMethod == null)
{
Debug.LogError("TooltipDrawer: Failed to locate the internal LayerMaskField method.");
}
}
return layerMaskFieldMethod;
}
}
private GUIContent Label
{
get
{
if (this.label == null)
{
InspectorTooltipAttribute labelAttribute = (InspectorTooltipAttribute)this.attribute;
this.label = new GUIContent(this.oldlabel.text, labelAttribute.Text);
}
return this.label;
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Shows a tooltip next to a property in the Unity inspector.
/// </summary>
/// <param name="position">Position to draw the property editor at.</param>
/// <param name="property">Property to draw the editor for.</param>
/// <param name="oldLabel">Tooltip text.</param>
public override void OnGUI(Rect position, SerializedProperty property, GUIContent oldLabel)
{
this.oldlabel = oldLabel;
EditorGUI.BeginProperty(position, this.Label, property);
EditorGUI.BeginChangeCheck();
switch (property.propertyType)
{
case SerializedPropertyType.AnimationCurve:
AnimationCurve newAnimationCurveValue = EditorGUI.CurveField(
position, this.Label, property.animationCurveValue);
if (EditorGUI.EndChangeCheck())
{
property.animationCurveValue = newAnimationCurveValue;
}
break;
case SerializedPropertyType.Boolean:
bool newBoolValue = EditorGUI.Toggle(position, this.Label, property.boolValue);
if (EditorGUI.EndChangeCheck())
{
property.boolValue = newBoolValue;
}
break;
case SerializedPropertyType.Bounds:
Bounds newBoundsValue = EditorGUI.BoundsField(position, this.Label, property.boundsValue);
if (EditorGUI.EndChangeCheck())
{
property.boundsValue = newBoundsValue;
}
break;
case SerializedPropertyType.Color:
Color newColorValue = EditorGUI.ColorField(position, this.Label, property.colorValue);
if (EditorGUI.EndChangeCheck())
{
property.colorValue = newColorValue;
}
break;
case SerializedPropertyType.Enum:
int newEnumValueIndex =
(int)
(object)
EditorGUI.EnumPopup(
position,
this.Label,
Enum.Parse(this.GetFieldType(property), property.enumNames[property.enumValueIndex]) as Enum);
if (EditorGUI.EndChangeCheck())
{
property.enumValueIndex = newEnumValueIndex;
}
break;
case SerializedPropertyType.Float:
float newFloatValue = EditorGUI.FloatField(position, this.Label, property.floatValue);
if (EditorGUI.EndChangeCheck())
{
property.floatValue = newFloatValue;
}
break;
case SerializedPropertyType.Integer:
int newIntValue = EditorGUI.IntField(position, this.Label, property.intValue);
if (EditorGUI.EndChangeCheck())
{
property.intValue = newIntValue;
}
break;
case SerializedPropertyType.LayerMask:
LayerMaskFieldMethod.Invoke(property.intValue, new object[] { position, property, this.Label });
break;
case SerializedPropertyType.ObjectReference:
Object newObjectReferenceValue = EditorGUI.ObjectField(
position, this.Label, property.objectReferenceValue, this.GetFieldType(property), true);
if (EditorGUI.EndChangeCheck())
{
property.objectReferenceValue = newObjectReferenceValue;
}
break;
case SerializedPropertyType.Rect:
Rect newRectValue = EditorGUI.RectField(position, this.Label, property.rectValue);
if (EditorGUI.EndChangeCheck())
{
property.rectValue = newRectValue;
}
break;
case SerializedPropertyType.String:
string newStringValue = EditorGUI.TextField(position, this.Label, property.stringValue);
if (EditorGUI.EndChangeCheck())
{
property.stringValue = newStringValue;
}
break;
default:
Debug.LogWarning("TooltipDrawer: found an un-handled type: " + property.propertyType);
break;
}
EditorGUI.EndProperty();
}
#endregion
#region Methods
private Type GetFieldType(SerializedProperty property)
{
if (this.fieldType == null)
{
Type parentClassType = property.serializedObject.targetObject.GetType();
FieldInfo propertyFieldInfo = parentClassType.GetField(
property.name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
if (propertyFieldInfo == null)
{
Debug.LogError("TooltipDrawer: Could not locate the object in the parent class");
return null;
}
this.fieldType = propertyFieldInfo.FieldType;
}
return this.fieldType;
}
#endregion
}
}
| |
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 Contoso.Branding.CustomCSSWeb
{
/// <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
}
| |
namespace ZetaHtmlEditControl.Code.PInvoke
{
using System;
using System.Drawing;
using System.Runtime.InteropServices;
public sealed class NativeMethods
{
public enum ContextMenuKind
{
#region Enum members.
CONTEXT_MENU_DEFAULT = 0,
CONTEXT_MENU_IMAGE = 1,
CONTEXT_MENU_CONTROL = 2,
CONTEXT_MENU_TABLE = 3,
CONTEXT_MENU_TEXTSELECT = 4,
CONTEXT_MENU_ANCHOR = 5,
CONTEXT_MENU_UNKNOWN = 6
#endregion
}
[Flags]
public enum DOCHOSTUIFLAG
{
#region Enum members.
DOCHOSTUIFLAG_DIALOG = 0x00000001,
DOCHOSTUIFLAG_DISABLE_HELP_MENU = 0x00000002,
DOCHOSTUIFLAG_NO3DBORDER = 0x00000004,
DOCHOSTUIFLAG_SCROLL_NO = 0x00000008,
DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE = 0x00000010,
DOCHOSTUIFLAG_OPENNEWWIN = 0x00000020,
DOCHOSTUIFLAG_DISABLE_OFFSCREEN = 0x00000040,
DOCHOSTUIFLAG_FLAT_SCROLLBAR = 0x00000080,
DOCHOSTUIFLAG_DIV_BLOCKDEFAULT = 0x00000100,
DOCHOSTUIFLAG_ACTIVATE_CLIENTHIT_ONLY = 0x00000200,
DOCHOSTUIFLAG_OVERRIDEBEHAVIORFACTORY = 0x00000400,
DOCHOSTUIFLAG_CODEPAGELINKEDFONTS = 0x00000800,
DOCHOSTUIFLAG_URL_ENCODING_DISABLE_UTF8 = 0x00001000,
DOCHOSTUIFLAG_URL_ENCODING_ENABLE_UTF8 = 0x00002000,
DOCHOSTUIFLAG_ENABLE_FORMS_AUTOCOMPLETE = 0x00004000,
DOCHOSTUIFLAG_ENABLE_INPLACE_NAVIGATION = 0x00010000,
DOCHOSTUIFLAG_IME_ENABLE_RECONVERSION = 0x00020000,
DOCHOSTUIFLAG_THEME = 0x00040000,
DOCHOSTUIFLAG_NOTHEME = 0x00080000,
DOCHOSTUIFLAG_NOPICS = 0x00100000,
DOCHOSTUIFLAG_NO3DOUTERBORDER = 0x00200000,
DOCHOSTUIFLAG_DISABLE_EDIT_NS_FIXUP = 0x00400000,
DOCHOSTUIFLAG_LOCAL_MACHINE_ACCESS_CHECK = 0x00800000,
DOCHOSTUIFLAG_DISABLE_UNTRUSTEDPROTOCOL = 0x01000000
#endregion
}
public const int WmKeydown = 0x100;
public const int WmSyskeydown = 0x104;
public const int IdmPrint = 27;
public const int IdmPrintpreview = 2003;
public static readonly int BOOL_FALSE = 0;
public static readonly int BOOL_TRUE = 1;
[StructLayout( LayoutKind.Sequential )]
public class COMRECT
{
public int left;
public int top;
public int right;
public int bottom;
//public COMRECT();
//public COMRECT(Rectangle r);
//public COMRECT(int left, int top, int right, int bottom);
//public static NativeMethods.COMRECT FromXYWH(int x, int y, int width, int height);
//public override string ToString();
public COMRECT()
{
}
public COMRECT( Rectangle r )
{
left = r.X;
top = r.Y;
right = r.Right;
bottom = r.Bottom;
}
public COMRECT( int left, int top, int right, int bottom )
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public static COMRECT FromXYWH( int x, int y, int width, int height )
{
return new COMRECT( x, y, x + width, y + height );
}
public override string ToString()
{
return String.Concat( new object[]
{ "Left = ", left, " Top ", top, " Right = ", right, " Bottom = ", bottom } );
}
}
[StructLayout( LayoutKind.Sequential ), ComVisible( true )]
public class DOCHOSTUIINFO
{
[MarshalAs( UnmanagedType.U4 )]
public int cbSize;
[MarshalAs( UnmanagedType.I4 )]
public int dwFlags;
[MarshalAs( UnmanagedType.I4 )]
public int dwDoubleClick;
[MarshalAs( UnmanagedType.I4 )]
public int dwReserved1;
[MarshalAs( UnmanagedType.I4 )]
public int dwReserved2;
//public DOCHOSTUIINFO();
public DOCHOSTUIINFO()
{
cbSize = Marshal.SizeOf( typeof( DOCHOSTUIINFO ) );
}
}
[Guid("00020400-0000-0000-C000-000000000046")]
[TypeLibType(512)]
[ComImport]
public interface IDispatch
{
}
[ComImport, InterfaceType( ComInterfaceType.InterfaceIsIUnknown ), Guid( @"B722BCCB-4E68-101B-A2BC-00AA00404770" ), ComVisible( true )]
public interface IOleCommandTarget
{
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int QueryStatus( ref Guid pguidCmdGroup, int cCmds, [In, Out] OLECMD prgCmds, [In, Out] IntPtr pCmdText );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int Exec( ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt,
[In, MarshalAs(UnmanagedType.LPArray)] object[] pvaIn,
[Out, MarshalAs(UnmanagedType.LPArray)] object[] pvaOut);
}
[Guid(@"00000000-0000-0000-C000-000000000046")]
[InterfaceType(1)]
[TypeLibType(16)]
[ComImport]
public interface IUnknown
{
}
[Serializable, StructLayout( LayoutKind.Sequential )]
public struct MSG
{
public IntPtr hwnd;
public int message;
public IntPtr wParam;
public IntPtr lParam;
public int time;
public int pt_x;
public int pt_y;
}
[StructLayout( LayoutKind.Sequential )]
public class OLECMD
{
[MarshalAs( UnmanagedType.U4 )]
public int cmdID;
[MarshalAs( UnmanagedType.U4 )]
public int cmdf;
//public OLECMD();
}
[StructLayout( LayoutKind.Sequential )]
public class POINT
{
public int x;
public int y;
public POINT()
{
}
public POINT( int x, int y )
{
this.x = x;
this.y = y;
}
}
public static class SRESULTS
{
#region Public properties.
public static readonly int S_OK = 0;
public static readonly int S_FALSE = 1;
#endregion
}
[StructLayout( LayoutKind.Sequential )]
public sealed class tagOleMenuGroupWidths
{
[MarshalAs( UnmanagedType.ByValArray, SizeConst = 6 )]
public int[] widths;
//public tagOleMenuGroupWidths();
public tagOleMenuGroupWidths()
{
widths = new int[6];
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SpscTargetCore.cs
//
//
// A fast single-producer-single-consumer core for a target block.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security;
#pragma warning disable 0420 // turn off warning for passing volatiles to interlocked operations
namespace System.Threading.Tasks.Dataflow.Internal
{
// SpscTargetCore provides a fast target core for use in blocks that will only have single-producer-single-consumer
// semantics. Blocks configured with the default DOP==1 will be single consumer, so whether this core may be
// used is largely up to whether the block is also single-producer. The ExecutionDataflowBlockOptions.SingleProducerConstrained
// option can be used by a developer to inform a block that it will only be accessed by one producer at a time,
// and a block like ActionBlock can utilize that knowledge to choose this target instead of the default TargetCore.
// However, there are further constraints that might prevent this core from being used.
// - If the user specifies a CancellationToken, this core can't be used, as the cancellation request
// could come in concurrently with the single producer accessing the block, thus resulting in multiple producers.
// - If the user specifies a bounding capacity, this core can't be used, as the consumer processing items
// needs to synchronize with producers around the change in bounding count, and the consumer is again
// in effect another producer.
// - If the block has a source half (e.g. TransformBlock) and that source could potentially call back
// to the target half to, for example, notify it of exceptions occurring, again there would potentially
// be multiple producers.
// Thus, when and how this SpscTargetCore may be applied is significantly constrained.
/// <summary>
/// Provides a core implementation of <see cref="ITargetBlock{TInput}"/> for use when there's only a single producer posting data.
/// </summary>
/// <typeparam name="TInput">Specifies the type of data accepted by the <see cref="TargetCore{TInput}"/>.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
internal sealed class SpscTargetCore<TInput>
{
/// <summary>The target block using this helper.</summary>
private readonly ITargetBlock<TInput> _owningTarget;
/// <summary>The messages in this target.</summary>
private readonly SingleProducerSingleConsumerQueue<TInput> _messages = new SingleProducerSingleConsumerQueue<TInput>();
/// <summary>The options to use to configure this block. The target core assumes these options are immutable.</summary>
private readonly ExecutionDataflowBlockOptions _dataflowBlockOptions;
/// <summary>An action to invoke for every accepted message.</summary>
private readonly Action<TInput> _action;
/// <summary>Exceptions that may have occurred and gone unhandled during processing. This field is lazily initialized.</summary>
private volatile List<Exception> _exceptions;
/// <summary>Whether to stop accepting new messages.</summary>
private volatile bool _decliningPermanently;
/// <summary>A task has reserved the right to run the completion routine.</summary>
private volatile bool _completionReserved;
/// <summary>
/// The Task currently active to process the block. This field is used to synchronize between producer and consumer,
/// and it should not be set to null once the block completes, as doing so would allow for races where the producer
/// gets another consumer task queued even though the block has completed.
/// </summary>
private volatile Task _activeConsumer;
/// <summary>A task representing the completion of the block. This field is lazily initialized.</summary>
private TaskCompletionSource<VoidResult> _completionTask;
/// <summary>Initialize the SPSC target core.</summary>
/// <param name="owningTarget">The owning target block.</param>
/// <param name="action">The action to be invoked for every message.</param>
/// <param name="dataflowBlockOptions">The options to use to configure this block. The target core assumes these options are immutable.</param>
internal SpscTargetCore(
ITargetBlock<TInput> owningTarget, Action<TInput> action, ExecutionDataflowBlockOptions dataflowBlockOptions)
{
Contract.Requires(owningTarget != null, "Expected non-null owningTarget");
Contract.Requires(action != null, "Expected non-null action");
Contract.Requires(dataflowBlockOptions != null, "Expected non-null dataflowBlockOptions");
_owningTarget = owningTarget;
_action = action;
_dataflowBlockOptions = dataflowBlockOptions;
}
internal bool Post(TInput messageValue)
{
if (_decliningPermanently)
return false;
// Store the offered message into the queue.
_messages.Enqueue(messageValue);
Interlocked.MemoryBarrier(); // ensure the read of _activeConsumer doesn't move up before the writes in Enqueue
// Make sure there's an active task available to handle processing this message. If we find the task
// is null, we'll try to schedule one using an interlocked operation. If we find the task is non-null,
// then there must be a task actively running. If there's a race where the task is about to complete
// and nulls out its reference (using a barrier), it'll subsequently check whether there are any messages in the queue,
// and since we put the messages into the queue before now, it'll find them and use an interlocked
// to re-launch itself.
if (_activeConsumer == null)
{
ScheduleConsumerIfNecessary(false);
}
return true;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
internal DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept)
{
// If we're not required to go back to the source to consume the offered message, try fast path.
return !consumeToAccept && Post(messageValue) ?
DataflowMessageStatus.Accepted :
OfferMessage_Slow(messageHeader, messageValue, source, consumeToAccept);
}
/// <summary>Implements the slow path for OfferMessage.</summary>
/// <param name="messageHeader">The message header for the offered value.</param>
/// <param name="messageValue">The offered value.</param>
/// <param name="source">The source offering the message. This may be null.</param>
/// <param name="consumeToAccept">true if we need to call back to the source to consume the message; otherwise, false if we can simply accept it directly.</param>
/// <returns>The status of the message.</returns>
private DataflowMessageStatus OfferMessage_Slow(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept)
{
// If we're declining permanently, let the caller know.
if (_decliningPermanently)
{
return DataflowMessageStatus.DecliningPermanently;
}
// If the message header is invalid, throw.
if (!messageHeader.IsValid)
{
throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader");
}
// If the caller has requested we consume the message using ConsumeMessage, do so.
if (consumeToAccept)
{
if (source == null) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, "consumeToAccept");
bool consumed;
messageValue = source.ConsumeMessage(messageHeader, _owningTarget, out consumed);
if (!consumed) return DataflowMessageStatus.NotAvailable;
}
// See the "fast path" comments in Post
_messages.Enqueue(messageValue);
Interlocked.MemoryBarrier(); // ensure the read of _activeConsumer doesn't move up before the writes in Enqueue
if (_activeConsumer == null)
{
ScheduleConsumerIfNecessary(isReplica: false);
}
return DataflowMessageStatus.Accepted;
}
/// <summary>Schedules a consumer task if there's none currently running.</summary>
/// <param name="isReplica">Whether the new consumer is being scheduled to replace a currently running consumer.</param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private void ScheduleConsumerIfNecessary(bool isReplica)
{
// If there's currently no active task...
if (_activeConsumer == null)
{
// Create a new consumption task and try to set it as current as long as there's still no other task
var newConsumer = new Task(
state => ((SpscTargetCore<TInput>)state).ProcessMessagesLoopCore(),
this, CancellationToken.None, Common.GetCreationOptionsForTask(isReplica));
if (Interlocked.CompareExchange(ref _activeConsumer, newConsumer, null) == null)
{
// We won the race. This task is now the consumer.
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TaskLaunchedForMessageHandling(
_owningTarget, newConsumer, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages, _messages.Count);
}
#endif
// Start the task. In the erroneous case where the scheduler throws an exception,
// just allow it to propagate. Our other option would be to fault the block with
// that exception, but in order for the block to complete we need to schedule a consumer
// task to do so, and it's very likely that if the scheduler is throwing an exception
// now, it would do so again.
newConsumer.Start(_dataflowBlockOptions.TaskScheduler);
}
}
}
/// <summary>Task body used to process messages.</summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ProcessMessagesLoopCore()
{
Debug.Assert(
_activeConsumer != null && _activeConsumer.Id == Task.CurrentId,
"This method should only be called when it's the active consumer.");
int messagesProcessed = 0;
int maxMessagesToProcess = _dataflowBlockOptions.ActualMaxMessagesPerTask;
// Continue processing as long as there's more processing to be done
bool continueProcessing = true;
while (continueProcessing)
{
continueProcessing = false;
TInput nextMessage = default(TInput);
try
{
// While there are more messages to be processed, process each one.
// NOTE: This loop is critical for performance. It must be super lean.
while (
_exceptions == null &&
messagesProcessed < maxMessagesToProcess &&
_messages.TryDequeue(out nextMessage))
{
messagesProcessed++; // done before _action invoked in case it throws exception
_action(nextMessage);
}
}
catch (Exception exc)
{
// If the exception is for cancellation, just ignore it.
// Otherwise, store it, and the finally block will handle completion.
if (!Common.IsCooperativeCancellation(exc))
{
_decliningPermanently = true; // stop accepting from producers
Common.StoreDataflowMessageValueIntoExceptionData<TInput>(exc, nextMessage, false);
StoreException(exc);
}
}
finally
{
// If more messages just arrived and we should still process them,
// loop back around and keep going.
if (!_messages.IsEmpty && _exceptions == null && (messagesProcessed < maxMessagesToProcess))
{
continueProcessing = true;
}
else
{
// If messages are being declined and we're empty, or if there's an exception,
// then there's no more work to be done and we should complete the block.
bool wasDecliningPermanently = _decliningPermanently;
if ((wasDecliningPermanently && _messages.IsEmpty) || _exceptions != null)
{
// Complete the block, as long as we're not already completing or completed.
if (!_completionReserved) // no synchronization necessary; this can't happen concurrently
{
_completionReserved = true;
CompleteBlockOncePossible();
}
}
else
{
// Mark that we're exiting.
Task previousConsumer = Interlocked.Exchange(ref _activeConsumer, null);
Debug.Assert(previousConsumer != null && previousConsumer.Id == Task.CurrentId,
"The running task should have been denoted as the active task.");
// Now that we're no longer the active task, double
// check to make sure there's really nothing to do,
// which could include processing more messages or completing.
// If there is more to do, schedule a task to try to do it.
// This is to handle a race with Post/Complete/Fault and this
// task completing.
if (!_messages.IsEmpty || // messages to be processed
(!wasDecliningPermanently && _decliningPermanently) || // potentially completion to be processed
_exceptions != null) // exceptions/completion to be processed
{
ScheduleConsumerIfNecessary(isReplica: true);
}
}
}
}
}
}
/// <summary>Gets the number of messages waiting to be processed.</summary>
internal int InputCount { get { return _messages.Count; } }
/// <summary>
/// Completes the target core. If an exception is provided, the block will end up in a faulted state.
/// If Complete is invoked more than once, or if it's invoked after the block is already
/// completing, all invocations after the first are ignored.
/// </summary>
/// <param name="exception">The exception to be stored.</param>
internal void Complete(Exception exception)
{
// If we're not yet declining permanently...
if (!_decliningPermanently)
{
// Mark us as declining permanently, and then kick off a processing task
// if we need one. It's this processing task's job to complete the block
// once all data has been consumed and/or we're in a valid state for completion.
if (exception != null) StoreException(exception);
_decliningPermanently = true;
ScheduleConsumerIfNecessary(isReplica: false);
}
}
/// <summary>
/// Ensures the exceptions list is initialized and stores the exception into the list using a lock.
/// </summary>
/// <param name="exception">The exception to store.</param>
private void StoreException(Exception exception)
{
// Ensure that the _exceptions field has been initialized.
// We need to synchronize the initialization and storing of
// the exception because this method could be accessed concurrently
// by the producer and consumer, a producer calling Fault and the
// processing task processing the user delegate which might throw.
lock (LazyInitializer.EnsureInitialized(ref _exceptions, () => new List<Exception>()))
{
_exceptions.Add(exception);
}
}
/// <summary>
/// Completes the block. This must only be called once, and only once all of the completion conditions are met.
/// </summary>
private void CompleteBlockOncePossible()
{
Debug.Assert(_completionReserved, "Should only invoke once completion has been reserved.");
// Dump any messages that might remain in the queue, which could happen if we completed due to exceptions.
TInput dumpedMessage;
while (_messages.TryDequeue(out dumpedMessage)) ;
// Complete the completion task
bool result;
if (_exceptions != null)
{
Exception[] exceptions;
lock (_exceptions) exceptions = _exceptions.ToArray();
result = CompletionSource.TrySetException(exceptions);
}
else
{
result = CompletionSource.TrySetResult(default(VoidResult));
}
Debug.Assert(result, "Expected completion task to not yet be completed");
// We explicitly do not set the _activeTask to null here, as that would
// allow for races where a producer calling OfferMessage could end up
// seeing _activeTask as null and queueing a new consumer task even
// though the block has completed.
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.DataflowBlockCompleted(_owningTarget);
}
#endif
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
internal Task Completion { get { return CompletionSource.Task; } }
/// <summary>Gets the lazily-initialized completion source.</summary>
private TaskCompletionSource<VoidResult> CompletionSource
{
get { return LazyInitializer.EnsureInitialized(ref _completionTask, () => new TaskCompletionSource<VoidResult>()); }
}
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _dataflowBlockOptions; } }
/// <summary>Gets information about this helper to be used for display in a debugger.</summary>
/// <returns>Debugging information about this target.</returns>
internal DebuggingInformation GetDebuggingInformation() { return new DebuggingInformation(this); }
/// <summary>Gets the object to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
var displayTarget = _owningTarget as IDebuggerDisplay;
return string.Format("Block=\"{0}\"",
displayTarget != null ? displayTarget.Content : _owningTarget);
}
}
/// <summary>Provides a wrapper for commonly needed debugging information.</summary>
internal sealed class DebuggingInformation
{
/// <summary>The target being viewed.</summary>
private readonly SpscTargetCore<TInput> _target;
/// <summary>Initializes the debugging helper.</summary>
/// <param name="target">The target being viewed.</param>
internal DebuggingInformation(SpscTargetCore<TInput> target) { _target = target; }
/// <summary>Gets the number of messages waiting to be processed.</summary>
internal int InputCount { get { return _target.InputCount; } }
/// <summary>Gets the messages waiting to be processed.</summary>
internal IEnumerable<TInput> InputQueue { get { return _target._messages.ToList(); } }
/// <summary>Gets the current number of outstanding input processing operations.</summary>
internal Int32 CurrentDegreeOfParallelism { get { return _target._activeConsumer != null && !_target.Completion.IsCompleted ? 1 : 0; } }
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _target._dataflowBlockOptions; } }
/// <summary>Gets whether the block is declining further messages.</summary>
internal bool IsDecliningPermanently { get { return _target._decliningPermanently; } }
/// <summary>Gets whether the block is completed.</summary>
internal bool IsCompleted { get { return _target.Completion.IsCompleted; } }
}
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UMA.CharacterSystem;
namespace UMA.Editors
{
[CustomEditor(typeof(UMAWardrobeCollection), true)]
public partial class UMAWardrobeCollectionEditor : RecipeEditor
{
static bool coverImagesIsExpanded = false;
protected override bool PreInspectorGUI()
{
hideToolBar = true;
hideRaceField = true;
return TextRecipeGUI();
}
/// <summary>
/// Impliment this method to output any extra GUI for any extra fields you have added to UMAWardrobeCollection before the main RecipeGUI
/// </summary>
partial void PreRecipeGUI(ref bool changed);
/// <summary>
/// Impliment this method to output any extra GUI for any extra fields you have added to UMAWardrobeCollection after the main RecipeGUI
/// </summary>
partial void PostRecipeGUI(ref bool changed);
protected override bool PostInspectorGUI()
{
bool changed = false;
PostRecipeGUI(ref changed);
return changed;
}
//draws the coverImages foldout
protected virtual bool DrawCoverImagesUI(Type TargetType)
{
bool doUpdate = false;
//FieldInfos
var CoverImagesField = TargetType.GetField("coverImages", BindingFlags.Public | BindingFlags.Instance);
//field values
List<Sprite> coverImages = (List<Sprite>)CoverImagesField.GetValue(target);
//drawUI
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
coverImagesIsExpanded = EditorGUILayout.Foldout(coverImagesIsExpanded, new GUIContent("Cover Images"));
GUILayout.EndHorizontal();
if (coverImagesIsExpanded)
{
List<Sprite> prevCoverImages = coverImages;
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.BeginHorizontal();
for (int i = 0; i < coverImages.Count; i++)
{
EditorGUI.BeginChangeCheck();
var thisImg = EditorGUILayout.ObjectField(coverImages[i], typeof(Sprite), false, GUILayout.Width(75), GUILayout.Height(75));
if (EditorGUI.EndChangeCheck())
{
if (thisImg != coverImages[i])
{
if (thisImg == null)
{
coverImages.RemoveAt(i);
}
else
{
coverImages[i] = (Sprite)thisImg;
}
doUpdate = true;
}
}
}
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("Add"))
{
coverImages.Add(null);
}
if (!AreListsEqual<Sprite>(prevCoverImages, coverImages))
{
CoverImagesField.SetValue(target, coverImages);
}
GUIHelper.EndVerticalPadded(10);
}
GUILayout.Space(-5f);
return doUpdate;
}
/// <summary>
/// An editor for a WardrobeCollection. Wardrobe collections can have Shared Colors and multiple WardrobeSets, but dont need a standard Slot or DNA Editor
/// </summary>
public class WardrobeCollectionMasterEditor : SlotMasterEditor
{
private List<string> _compatibleRaces = new List<string>();
private WardrobeCollectionList _wardrobeCollection;
private List<string> _arbitraryRecipes = new List<string>();
private bool forceGUIUpdate = false;
private static string recipesAddErrMsg = "";
//int recipePickerID = -1; This is needed if we can make the recipe drop area work with 'Click To Pick'
public WardrobeCollectionMasterEditor(UMAData.UMARecipe recipe, List<string> compatibleRaces, WardrobeCollectionList wardrobeCollection, List<string> arbitraryRecipes) : base(recipe)
{
_compatibleRaces = compatibleRaces;
_wardrobeCollection = wardrobeCollection;
_arbitraryRecipes = arbitraryRecipes;
UpdateFoldouts();
recipesAddErrMsg = "";
}
public void UpdateVals(List<string> compatibleRaces, WardrobeCollectionList wardrobeCollection, List<string> arbitraryRecipes)
{
forceGUIUpdate = false;
_wardrobeCollection = wardrobeCollection;
_compatibleRaces = compatibleRaces;
forceGUIUpdate = UpdateCollectionRaces();
UpdateFoldouts();
}
private void UpdateFoldouts()
{
if (!OpenSlots.ContainsKey("wardrobeSets"))
OpenSlots.Add("wardrobeSets", true);
if (!OpenSlots.ContainsKey("arbitraryRecipes"))
OpenSlots.Add("arbitraryRecipes", true);
for (int i = 0; i < _compatibleRaces.Count; i++)
{
bool open = i == 0 ? true : false;
if (!OpenSlots.ContainsKey(_compatibleRaces[i]))
{
OpenSlots.Add(_compatibleRaces[i], open);
}
}
}
private bool UpdateCollectionRaces()
{
bool changed = false;
if (_compatibleRaces.Count == 0 && _wardrobeCollection.sets.Count > 0)
{
_wardrobeCollection.Clear();
changed = true;
}
else
{
for(int i = 0; i < _compatibleRaces.Count; i++)
{
if (!_wardrobeCollection.Contains(_compatibleRaces[i]))
{
_wardrobeCollection.Add(_compatibleRaces[i]);
changed = true;
}
}
var collectionNames = _wardrobeCollection.GetAllRacesInCollection();
for(int i = 0; i < collectionNames.Count; i++)
{
if (!_compatibleRaces.Contains(collectionNames[i]))
{
_wardrobeCollection.Remove(collectionNames[i]);
changed = true;
}
}
}
return changed;
}
public override bool OnGUI(string targetName, ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty)
{
var context = UMAContext.FindInstance();
if (context == null)
{
var _errorMessage = "Editing a recipe requires a loaded scene with a valid UMAContext.";
Debug.LogWarning(_errorMessage);
return false;
}
bool changed = forceGUIUpdate;
//Make a foldout for WardrobeSets - the UI for an individual WardrobeSet is added for each compatible race in the collection
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
bool wsfoldoutOpen = OpenSlots["wardrobeSets"];
wsfoldoutOpen = EditorGUILayout.Foldout(OpenSlots["wardrobeSets"], "Wardrobe Sets");
OpenSlots["wardrobeSets"] = wsfoldoutOpen;
GUILayout.EndHorizontal();
if (wsfoldoutOpen)
{
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.HelpBox("Wardrobe Sets are added for each 'Compatible Race' assigned above. 'SharedColors' in this section are derived from all the recipes assigned in the set and are will be applied to the Avatar when the wardrobe sets recipes are added.", MessageType.Info);
if (_compatibleRaces.Count > 0)
{
//dont show shared colors unless there are 'FullOutfits' to apply them to
if (_sharedColorsEditor.OnGUI(_recipe))
{
changed = true;
_textureDirty = true;
}
for (int i = 0; i < _compatibleRaces.Count; i++)
{
var thisRace = context.raceLibrary.GetRace(_compatibleRaces[i]);
if (thisRace != null)
{
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
bool foldoutOpen = OpenSlots[_compatibleRaces[i]];
foldoutOpen = EditorGUILayout.Foldout(OpenSlots[_compatibleRaces[i]], " Wardrobe Set: " + _compatibleRaces[i]);
OpenSlots[_compatibleRaces[i]] = foldoutOpen;
GUILayout.EndHorizontal();
if (foldoutOpen)
{
var thisSetEditor = new WardrobeSetEditor(thisRace, _wardrobeCollection[thisRace.raceName], _recipe, false);
if (thisSetEditor.OnGUI())
{
_wardrobeCollection[thisRace.raceName] = thisSetEditor.WardrobeSet;
changed = true;
}
}
}
else
{
//Do the foldout thing but show as 'missing'
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
bool foldoutOpen = OpenSlots[_compatibleRaces[i]];
foldoutOpen = EditorGUILayout.Foldout(OpenSlots[_compatibleRaces[i]], _compatibleRaces[i] + " Wardrobe Set (Missing)");
OpenSlots[_compatibleRaces[i]] = foldoutOpen;
GUILayout.EndHorizontal();
if (foldoutOpen)
{
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.HelpBox("_compatibleRaces[i] could not be located by the Dynamic Race Library", MessageType.Warning);
GUIHelper.EndVerticalPadded(10);
}
}
}
}
else
{
EditorGUILayout.HelpBox("Drag in compatible races at the top of this recipe and WardrobeSets for those races will show here", MessageType.Info);
}
GUIHelper.EndVerticalPadded(10);
}
GUILayout.Space(10);
//the Arbitrary Recipes section
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
bool arbiOpen = OpenSlots["arbitraryRecipes"];
arbiOpen = EditorGUILayout.Foldout(OpenSlots["arbitraryRecipes"], "Arbitrary Recipes");
OpenSlots["arbitraryRecipes"] = arbiOpen;
Rect dropArea = new Rect();
GUILayout.EndHorizontal();
if (arbiOpen)
{
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.HelpBox("Drop recipes in to this area to create a collection that is not a full outfit or connected to any given race, for example a 'Hair Styles' pack or 'Tattoos' pack.", MessageType.Info);
dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea, "Drag WardrobeRecipes here. " + recipesAddErrMsg);
if (_arbitraryRecipes.Count > 0)
{
for (int i = 0; i < _arbitraryRecipes.Count; i++)
{
GUILayout.Space(2f);
GUI.enabled = false; //we readonly to prevent typos
Rect crfRect = GUILayoutUtility.GetRect(0.0f, EditorGUIUtility.singleLineHeight, GUILayout.ExpandWidth(true));
Rect crfDelRect = crfRect;
crfRect.width = crfRect.width - 20f - 5f;
crfDelRect.width = 20f + 2f;
crfDelRect.x = crfRect.width + 20f + 10f;
EditorGUI.TextField(crfRect, _arbitraryRecipes[i]);
GUI.enabled = true;
if (GUI.Button(crfDelRect, "X"))
{
_arbitraryRecipes.RemoveAt(i);
changed = true;
}
}
}
GUIHelper.EndVerticalPadded(10);
if (AddRecipesDropAreaGUI(ref recipesAddErrMsg, dropArea, _arbitraryRecipes))
changed = true;
}
return changed;
}
// Drop area for Arbitrary Wardrobe recipes
private bool AddRecipesDropAreaGUI(ref string errorMsg, Rect dropArea, List<string> recipes)
{
Event evt = Event.current;
bool changed = false;
//make the box clickable so that the user can select raceData assets from the asset selection window
//TODO: cant make this work without layout errors. Anyone know how to fix?
/*if (evt.type == EventType.MouseUp)
{
if (dropArea.Contains(evt.mousePosition))
{
recipePickerID = EditorGUIUtility.GetControlID(new GUIContent("recipeObjectPicker"), FocusType.Passive);
EditorGUIUtility.ShowObjectPicker<UMARecipeBase>(null, false, "", recipePickerID);
}
}
if (evt.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == recipePickerID)
{
UMARecipeBase tempRecipeAsset = EditorGUIUtility.GetObjectPickerObject() as UMARecipeBase;
if (tempRecipeAsset)
{
if (AddIfWardrobeRecipe(tempRecipeAsset, recipes))
{
changed = true;
errorMsg = "";
}
else
errorMsg = "That recipe was not a Wardrobe recipe";
}
}*/
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
bool allAdded = true;
for (int i = 0; i < draggedObjects.Length; i++)
{
if (draggedObjects[i])
{
UMARecipeBase tempRecipeAsset = draggedObjects[i] as UMARecipeBase;
if (tempRecipeAsset)
{
if (AddIfWardrobeRecipe(tempRecipeAsset, recipes))
changed = true;
else
{
allAdded = false;
}
continue;
}
var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForAssets(path, recipes);
}
}
}
if (!allAdded)
errorMsg = "Some of the recipes you tried to add were not Wardrobe recipes";
else
errorMsg = "";
}
}
return changed;
}
private bool AddIfWardrobeRecipe(UnityEngine.Object tempRecipeAsset, List<string> recipes)
{
bool added = false;
if (!recipes.Contains(tempRecipeAsset.name))
{
Type TargetType = tempRecipeAsset.GetType();
if (TargetType.ToString() == "UMATextRecipe" || TargetType.ToString() == "UMAWardrobeRecipe")
{
FieldInfo RecipeTypeField = TargetType.GetField("recipeType", BindingFlags.Public | BindingFlags.Instance);
string recipeType = (string)RecipeTypeField.GetValue(tempRecipeAsset);
if (recipeType == "Wardrobe")
{
recipes.Add(tempRecipeAsset.name);
added = true;
}
}
}
return added;
}
private void RecursiveScanFoldersForAssets(string path, List<string> recipes)
{
var assetFiles = System.IO.Directory.GetFiles(path, "*.asset");
foreach (var assetFile in assetFiles)
{
var tempRecipeAsset = AssetDatabase.LoadAssetAtPath(assetFile, typeof(UMARecipeBase)) as UMARecipeBase;
if (tempRecipeAsset)
{
AddIfWardrobeRecipe(tempRecipeAsset, recipes);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'), recipes);
}
}
}
protected virtual bool TextRecipeGUI()
{
Type TargetType = target.GetType();
bool doUpdate = false;
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.Popup("Recipe Type", 0, new string[] { "WardrobeCollection"});
EditorGUI.EndDisabledGroup();
PreRecipeGUI(ref doUpdate);
FieldInfo CompatibleRacesField = TargetType.GetField("compatibleRaces", BindingFlags.Public | BindingFlags.Instance);
//WardrobeCollections use the WardrobeSlot field to allow the user to define a Collection Group
FieldInfo WardrobeSlotField = TargetType.GetField("wardrobeSlot", BindingFlags.Public | BindingFlags.Instance);
string wardrobeSlot = (string)WardrobeSlotField.GetValue(target);
List<string> compatibleRaces = (List<string>)CompatibleRacesField.GetValue(target);
//FieldInfos
FieldInfo WardrobeCollectionList = TargetType.GetField("wardrobeCollection", BindingFlags.Public | BindingFlags.Instance);
FieldInfo ArbitraryRecipesList = TargetType.GetField("arbitraryRecipes", BindingFlags.Public | BindingFlags.Instance);
//field values
WardrobeCollectionList wardrobeCollection = (WardrobeCollectionList)WardrobeCollectionList.GetValue(target);
List<string> arbitraryRecipes = (List<string>)ArbitraryRecipesList.GetValue(target);
if (slotEditor == null || slotEditor.GetType() != typeof(WardrobeCollectionMasterEditor))
{
slotEditor = new WardrobeCollectionMasterEditor(_recipe, compatibleRaces, wardrobeCollection, arbitraryRecipes);
}
else
{
(slotEditor as WardrobeCollectionMasterEditor).UpdateVals(compatibleRaces, wardrobeCollection, arbitraryRecipes);
}
//wardrobe collection also has a 'cover image' field
if (DrawCoverImagesUI(TargetType))
doUpdate = true;
//CompatibleRaces drop area
if (DrawCompatibleRacesUI(TargetType))
doUpdate = true;
EditorGUILayout.Space();
//Draw the Wardrobe slot field as a WardrobeCollection Group text field.
EditorGUILayout.HelpBox("When a collection is placed on an avatar it replaces any other collections belonging to this group and unloads that collections recipes", MessageType.Info);
var newWardrobeSlot = EditorGUILayout.DelayedTextField("Collection Group", wardrobeSlot);
if(newWardrobeSlot != wardrobeSlot)
{
WardrobeSlotField.SetValue(target, newWardrobeSlot);
doUpdate = true;
}
EditorGUILayout.Space();
return doUpdate;
}
}
}
#endif
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Development;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osu.Framework.Threading;
using osuTK;
namespace osu.Framework.Tests.Visual.Drawables
{
public class TestSceneSynchronizationContext : FrameworkTestScene
{
[Resolved]
private GameHost host { get; set; }
private AsyncPerformingBox box;
[Test]
public void TestAsyncLoadComplete()
{
AddStep("add box", () => Child = box = new AsyncPerformingBox(true));
AddAssert("not spun", () => box.Rotation == 0);
AddStep("trigger", () => box.ReleaseAsyncLoadCompleteLock());
AddUntilStep("has spun", () => box.Rotation == 180);
}
private GameThreadSynchronizationContext syncContext => SynchronizationContext.Current as GameThreadSynchronizationContext;
[Test]
public void TestNoAsyncDoesntUseScheduler()
{
int initialTasksRun = 0;
AddStep("get initial run count", () => initialTasksRun = syncContext.TotalTasksRun);
AddStep("add box", () => Child = box = new AsyncPerformingBox(false));
AddAssert("no tasks run", () => syncContext.TotalTasksRun == initialTasksRun);
AddStep("trigger", () => box.ReleaseAsyncLoadCompleteLock());
AddAssert("no tasks run", () => syncContext.TotalTasksRun == initialTasksRun);
}
[Test]
public void TestAsyncUsesScheduler()
{
int initialTasksRun = 0;
AddStep("get initial run count", () => initialTasksRun = syncContext.TotalTasksRun);
AddStep("add box", () => Child = box = new AsyncPerformingBox(true));
AddAssert("no tasks run", () => syncContext.TotalTasksRun == initialTasksRun);
AddStep("trigger", () => box.ReleaseAsyncLoadCompleteLock());
AddUntilStep("one new task run", () => syncContext.TotalTasksRun == initialTasksRun + 1);
}
[Test]
public void TestOrderOfExecutionFlushing()
{
List<int> ran = new List<int>();
AddStep("queue items", () =>
{
SynchronizationContext.Current?.Post(_ => ran.Add(1), null);
SynchronizationContext.Current?.Post(_ => ran.Add(2), null);
SynchronizationContext.Current?.Post(_ => ran.Add(3), null);
Assert.That(ran, Is.Empty);
SynchronizationContext.Current?.Send(_ => ran.Add(4), null);
Assert.That(ran, Is.EqualTo(new[] { 1, 2, 3, 4 }));
});
}
[Test]
public void TestOrderOfExecutionFlushingAsyncThread()
{
ManualResetEventSlim finished = new ManualResetEventSlim();
List<int> ran = new List<int>();
AddStep("queue items", () =>
{
var updateContext = SynchronizationContext.Current;
Debug.Assert(updateContext != null);
updateContext.Post(_ => ran.Add(1), null);
updateContext.Post(_ => ran.Add(2), null);
updateContext.Post(_ => ran.Add(3), null);
Assert.That(ran, Is.Empty);
Task.Factory.StartNew(() =>
{
updateContext.Send(_ => ran.Add(4), null);
Assert.That(ran, Is.EqualTo(new[] { 1, 2, 3, 4 }));
finished.Set();
}, TaskCreationOptions.LongRunning);
});
AddUntilStep("wait for completion", () => finished.IsSet);
}
[Test]
public void TestAsyncThrows()
{
Exception thrown = null;
AddStep("watch for exceptions", () => host.ExceptionThrown += onException);
AddStep("throw on update thread", () =>
{
// ReSharper disable once AsyncVoidLambda
host.UpdateThread.Scheduler.Add(async () =>
{
Assert.That(ThreadSafety.IsUpdateThread);
await Task.Delay(100).ConfigureAwait(true);
Assert.That(ThreadSafety.IsUpdateThread);
throw new InvalidOperationException();
});
});
AddUntilStep("wait for exception to arrive", () => thrown is InvalidOperationException);
AddStep("stop watching for exceptions", () => host.ExceptionThrown -= onException);
bool onException(Exception arg)
{
thrown = arg;
return true;
}
}
[Test]
public void TestAsyncInsideUpdate()
{
int updateCount = 0;
AddStep("add box", () =>
{
updateCount = 0;
Child = box = new AsyncPerformingBox(false);
});
AddUntilStep("has spun", () => box.Rotation == 180);
AddStep("update with async", () =>
{
#pragma warning disable 4014
box.OnUpdate += _ => asyncAction();
#pragma warning restore 4014
async Task asyncAction()
{
updateCount++;
await box.PerformAsyncWait().ConfigureAwait(true);
box.RotateTo(0, 500);
}
});
AddUntilStep("is running updates", () => updateCount > 5);
AddStep("trigger", () => box.ReleaseAsyncLoadCompleteLock());
AddUntilStep("has spun", () => box.Rotation == 0);
}
[Test]
public void TestAsyncInsideSchedule()
{
AddStep("add box", () => Child = box = new AsyncPerformingBox(false));
AddUntilStep("has spun", () => box.Rotation == 180);
AddStep("schedule with async", () =>
{
#pragma warning disable 4014
// We may want to give `Schedule` a `Task` accepting overload in the future.
box.Schedule(() => asyncScheduledAction());
#pragma warning restore 4014
async Task asyncScheduledAction()
{
await box.PerformAsyncWait().ConfigureAwait(true);
box.RotateTo(0, 500);
}
});
AddStep("trigger", () => box.ReleaseAsyncLoadCompleteLock());
AddUntilStep("has spun", () => box.Rotation == 0);
}
public class AsyncPerformingBox : Box
{
private readonly bool performAsyncLoadComplete;
private readonly SemaphoreSlim waiter = new SemaphoreSlim(0);
public AsyncPerformingBox(bool performAsyncLoadComplete)
{
this.performAsyncLoadComplete = performAsyncLoadComplete;
Size = new Vector2(100);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
protected override async void LoadComplete()
{
base.LoadComplete();
if (performAsyncLoadComplete)
await PerformAsyncWait().ConfigureAwait(true);
this.RotateTo(180, 500);
}
public async Task PerformAsyncWait() => await waiter.WaitAsync().ConfigureAwait(false);
public void ReleaseAsyncLoadCompleteLock() => waiter.Release();
}
}
}
| |
#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UMA;
namespace UMAEditor
{
//[CustomEditor(typeof(SlotDataAsset))]
public class SlotInspector : Editor
{
[MenuItem("Assets/Create/UMA Slot Asset")]
public static void CreateSlotMenuItem()
{
CustomAssetUtility.CreateAsset<SlotDataAsset>();
}
static private void RecurseTransformsInPrefab(Transform root, List<Transform> transforms)
{
for (int i = 0; i < root.childCount; i++)
{
Transform child = root.GetChild(i);
transforms.Add(child);
RecurseTransformsInPrefab(child, transforms);
}
}
static protected Transform[] GetTransformsInPrefab(Transform prefab)
{
List<Transform> transforms = new List<Transform>();
RecurseTransformsInPrefab(prefab, transforms);
return transforms.ToArray();
}
protected SlotDataAsset slot;
protected bool showBones;
protected Vector2 boneScroll = new Vector2();
protected Transform[] umaBoneData;
public void OnEnable()
{
slot = target as SlotDataAsset;
#pragma warning disable 618
if (slot.meshData != null)
{
//if (slot.meshData.rootBoneHash != null)
//{
// umaBoneData = GetTransformsInPrefab(slot.meshData.rootBone);
//}
//else
//{
umaBoneData = new Transform[0];
//}
}
#if !UMA2_LEAN_AND_CLEAN
else if (slot.meshRenderer != null)
{
umaBoneData = GetTransformsInPrefab(slot.meshRenderer.rootBone);
}
#endif
else
{
umaBoneData = new Transform[0];
}
#pragma warning restore 618
}
public override void OnInspectorGUI()
{
slot.slotName = EditorGUILayout.TextField("Slot Name", slot.slotName);
slot.slotDNA = EditorGUILayout.ObjectField("DNA Converter", slot.slotDNA, typeof(DnaConverterBehaviour), false) as DnaConverterBehaviour;
EditorGUILayout.Space();
slot.subMeshIndex = EditorGUILayout.IntField("Sub Mesh Index", slot.subMeshIndex);
if (GUI.changed)
{
EditorUtility.SetDirty(slot);
}
EditorGUILayout.Space();
if (umaBoneData == null)
{
showBones = false;
GUI.enabled = false;
}
showBones = EditorGUILayout.Foldout(showBones, "Bones");
if (showBones)
{
EditorGUI.indentLevel++;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Name");
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField("Animated");
GUILayout.Space(40f);
EditorGUILayout.EndHorizontal();
boneScroll = EditorGUILayout.BeginScrollView(boneScroll);
EditorGUILayout.BeginVertical();
foreach (Transform bone in umaBoneData)
{
bool wasAnimated = ArrayUtility.Contains<Transform>(slot.animatedBones, bone);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(bone.name);
bool animated = EditorGUILayout.Toggle(wasAnimated, GUILayout.Width(40f));
if (animated != wasAnimated)
{
if (animated)
{
ArrayUtility.Add<Transform>(ref slot.animatedBones, bone);
EditorUtility.SetDirty(slot);
}
else
{
ArrayUtility.Remove<Transform>(ref slot.animatedBones, bone);
EditorUtility.SetDirty(slot);
}
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndScrollView();
EditorGUI.indentLevel--;
if (GUILayout.Button("Clear Animated Bones"))
{
slot.animatedBones = new Transform[0];
EditorUtility.SetDirty(slot);
}
}
GUI.enabled = true;
EditorGUILayout.Space();
slot.slotGroup = EditorGUILayout.TextField("Slot Group", slot.slotGroup);
var textureNameList = serializedObject.FindProperty("textureNameList");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(textureNameList, true);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
SerializedProperty tags = serializedObject.FindProperty("tags");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(tags, true);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
SerializedProperty begunCallback = serializedObject.FindProperty("CharacterBegun");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(begunCallback, true);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
SerializedProperty atlasCallback = serializedObject.FindProperty("SlotAtlassed");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(atlasCallback, true);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
SerializedProperty dnaAppliedCallback = serializedObject.FindProperty("DNAApplied");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(dnaAppliedCallback, true);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
SerializedProperty characterCompletedCallback = serializedObject.FindProperty("CharacterCompleted");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(characterCompletedCallback, true);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
foreach (var field in slot.GetType().GetFields())
{
foreach (var attribute in System.Attribute.GetCustomAttributes(field))
{
if (attribute is UMAAssetFieldVisible)
{
SerializedProperty serializedProp = serializedObject.FindProperty(field.Name);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serializedProp);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
break;
}
}
}
if (GUI.changed)
{
EditorUtility.SetDirty(slot);
AssetDatabase.SaveAssets();
}
}
}
}
#endif
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
// Vector Light State
new GFXStateBlockData( AL_VectorLightState )
{
blendDefined = true;
blendEnable = true;
blendSrc = GFXBlendOne;
blendDest = GFXBlendOne;
blendOp = GFXBlendOpAdd;
zDefined = true;
zEnable = false;
zWriteEnable = false;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint; // G-buffer
mSamplerNames[0] = "deferredBuffer";
samplerStates[1] = SamplerClampPoint; // Shadow Map (Do not change this to linear, as all cards can not filter equally.)
mSamplerNames[1] = "shadowMap";
samplerStates[2] = SamplerClampPoint; // Shadow Map (Do not change this to linear, as all cards can not filter equally.)
mSamplerNames[2] = "dynamicShadowMap";
samplerStates[3] = SamplerClampLinear; // SSAO Mask
mSamplerNames[3] = "ssaoMask";
samplerStates[4] = SamplerWrapPoint; // Random Direction Map
cullDefined = true;
cullMode = GFXCullNone;
stencilDefined = true;
stencilEnable = true;
stencilFailOp = GFXStencilOpKeep;
stencilZFailOp = GFXStencilOpKeep;
stencilPassOp = GFXStencilOpKeep;
stencilFunc = GFXCmpLess;
stencilRef = 0;
};
// Vector Light Material
new ShaderData( AL_VectorLightShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/farFrustumQuadV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/vectorLightP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/gl/farFrustumQuadV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/gl/vectorLightP.glsl";
samplerNames[0] = "$deferredBuffer";
samplerNames[1] = "$shadowMap";
samplerNames[2] = "$dynamicShadowMap";
samplerNames[3] = "$ssaoMask";
samplerNames[4] = "$gTapRotationTex";
samplerNames[5] = "$lightBuffer";
samplerNames[6] = "$colorBuffer";
samplerNames[7] = "$matInfoBuffer";
pixVersion = 3.0;
};
new CustomMaterial( AL_VectorLightMaterial )
{
shader = AL_VectorLightShader;
stateBlock = AL_VectorLightState;
sampler["deferredBuffer"] = "#deferred";
sampler["shadowMap"] = "$dynamiclight";
sampler["dynamicShadowMap"] = "$dynamicShadowMap";
sampler["ssaoMask"] = "#ssaoMask";
sampler["lightBuffer"] = "#lightinfo";
sampler["colorBuffer"] = "#color";
sampler["matInfoBuffer"] = "#matinfo";
target = "lightinfo";
pixVersion = 3.0;
};
//------------------------------------------------------------------------------
// Convex-geometry light states
new GFXStateBlockData( AL_ConvexLightState )
{
blendDefined = true;
blendEnable = true;
blendSrc = GFXBlendOne;
blendDest = GFXBlendOne;
blendOp = GFXBlendOpAdd;
zDefined = true;
zEnable = true;
zWriteEnable = false;
zFunc = GFXCmpGreaterEqual;
samplersDefined = true;
samplerStates[0] = SamplerClampPoint; // G-buffer
mSamplerNames[0] = "deferredBuffer";
samplerStates[1] = SamplerClampPoint; // Shadow Map (Do not use linear, these are perspective projections)
mSamplerNames[1] = "shadowMap";
samplerStates[2] = SamplerClampPoint; // Shadow Map (Do not use linear, these are perspective projections)
mSamplerNames[2] = "dynamicShadowMap";
samplerStates[3] = SamplerClampLinear; // Cookie Map
samplerStates[4] = SamplerWrapPoint; // Random Direction Map
cullDefined = true;
cullMode = GFXCullCW;
stencilDefined = true;
stencilEnable = true;
stencilFailOp = GFXStencilOpKeep;
stencilZFailOp = GFXStencilOpKeep;
stencilPassOp = GFXStencilOpKeep;
stencilFunc = GFXCmpLess;
stencilRef = 0;
};
// Point Light Material
new ShaderData( AL_PointLightShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/convexGeometryV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/pointLightP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/gl/convexGeometryV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/gl/pointLightP.glsl";
samplerNames[0] = "$deferredBuffer";
samplerNames[1] = "$shadowMap";
samplerNames[2] = "$dynamicShadowMap";
samplerNames[3] = "$cookieMap";
samplerNames[4] = "$gTapRotationTex";
samplerNames[5] = "$lightBuffer";
samplerNames[6] = "$colorBuffer";
samplerNames[7] = "$matInfoBuffer";
pixVersion = 3.0;
};
new CustomMaterial( AL_PointLightMaterial )
{
shader = AL_PointLightShader;
stateBlock = AL_ConvexLightState;
sampler["deferredBuffer"] = "#deferred";
sampler["shadowMap"] = "$dynamiclight";
sampler["dynamicShadowMap"] = "$dynamicShadowMap";
sampler["cookieMap"] = "$dynamiclightmask";
sampler["lightBuffer"] = "#lightinfo";
sampler["colorBuffer"] = "#color";
sampler["matInfoBuffer"] = "#matinfo";
target = "lightinfo";
pixVersion = 3.0;
};
// Spot Light Material
new ShaderData( AL_SpotLightShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/convexGeometryV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/spotLightP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/gl/convexGeometryV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/gl/spotLightP.glsl";
samplerNames[0] = "$deferredBuffer";
samplerNames[1] = "$shadowMap";
samplerNames[2] = "$dynamicShadowMap";
samplerNames[3] = "$cookieMap";
samplerNames[4] = "$gTapRotationTex";
samplerNames[5] = "$lightBuffer";
samplerNames[6] = "$colorBuffer";
samplerNames[7] = "$matInfoBuffer";
pixVersion = 3.0;
};
new CustomMaterial( AL_SpotLightMaterial )
{
shader = AL_SpotLightShader;
stateBlock = AL_ConvexLightState;
sampler["deferredBuffer"] = "#deferred";
sampler["shadowMap"] = "$dynamiclight";
sampler["dynamicShadowMap"] = "$dynamicShadowMap";
sampler["cookieMap"] = "$dynamiclightmask";
sampler["lightBuffer"] = "#lightinfo";
sampler["colorBuffer"] = "#color";
sampler["matInfoBuffer"] = "#matinfo";
target = "lightinfo";
pixVersion = 3.0;
};
/// This material is used for generating deferred
/// materials for objects that do not have materials.
new Material( AL_DefaultDeferredMaterial )
{
// We need something in the first pass else it
// won't create a proper material instance.
//
// We use color here because some objects may not
// have texture coords in their vertex format...
// for example like terrain.
//
diffuseColor[0] = "1 1 1 1";
};
/// This material is used for generating shadow
/// materials for objects that do not have materials.
new Material( AL_DefaultShadowMaterial )
{
// We need something in the first pass else it
// won't create a proper material instance.
//
// We use color here because some objects may not
// have texture coords in their vertex format...
// for example like terrain.
//
diffuseColor[0] = "1 1 1 1";
// This is here mostly for terrain which uses
// this material to create its shadow material.
//
// At sunset/sunrise the sun is looking thru
// backsides of the terrain which often are not
// closed. By changing the material to be double
// sided we avoid holes in the shadowed geometry.
//
doubleSided = true;
};
// Particle System Point Light Material
new ShaderData( AL_ParticlePointLightShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/particlePointLightV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/particlePointLightP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/gl/convexGeometryV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/lighting/advanced/gl/pointLightP.glsl";
samplerNames[0] = "$deferredBuffer";
pixVersion = 3.0;
};
new CustomMaterial( AL_ParticlePointLightMaterial )
{
shader = AL_ParticlePointLightShader;
stateBlock = AL_ConvexLightState;
sampler["deferredBuffer"] = "#deferred";
target = "lightinfo";
pixVersion = 3.0;
};
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class TableLayout : android.widget.LinearLayout
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static TableLayout()
{
InitJNI();
}
protected TableLayout(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public new partial class LayoutParams : android.widget.LinearLayout.LayoutParams
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static LayoutParams()
{
InitJNI();
}
protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _setBaseAttributes12062;
protected override void setBaseAttributes(android.content.res.TypedArray arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout.LayoutParams._setBaseAttributes12062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.LayoutParams.staticClass, global::android.widget.TableLayout.LayoutParams._setBaseAttributes12062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _LayoutParams12063;
public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TableLayout.LayoutParams.staticClass, global::android.widget.TableLayout.LayoutParams._LayoutParams12063, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _LayoutParams12064;
public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TableLayout.LayoutParams.staticClass, global::android.widget.TableLayout.LayoutParams._LayoutParams12064, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _LayoutParams12065;
public LayoutParams(int arg0, int arg1, float arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TableLayout.LayoutParams.staticClass, global::android.widget.TableLayout.LayoutParams._LayoutParams12065, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _LayoutParams12066;
public LayoutParams() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TableLayout.LayoutParams.staticClass, global::android.widget.TableLayout.LayoutParams._LayoutParams12066);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _LayoutParams12067;
public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TableLayout.LayoutParams.staticClass, global::android.widget.TableLayout.LayoutParams._LayoutParams12067, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _LayoutParams12068;
public LayoutParams(android.view.ViewGroup.MarginLayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TableLayout.LayoutParams.staticClass, global::android.widget.TableLayout.LayoutParams._LayoutParams12068, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.TableLayout.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/TableLayout$LayoutParams"));
global::android.widget.TableLayout.LayoutParams._setBaseAttributes12062 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.LayoutParams.staticClass, "setBaseAttributes", "(Landroid/content/res/TypedArray;II)V");
global::android.widget.TableLayout.LayoutParams._LayoutParams12063 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.widget.TableLayout.LayoutParams._LayoutParams12064 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.LayoutParams.staticClass, "<init>", "(II)V");
global::android.widget.TableLayout.LayoutParams._LayoutParams12065 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.LayoutParams.staticClass, "<init>", "(IIF)V");
global::android.widget.TableLayout.LayoutParams._LayoutParams12066 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.LayoutParams.staticClass, "<init>", "()V");
global::android.widget.TableLayout.LayoutParams._LayoutParams12067 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V");
global::android.widget.TableLayout.LayoutParams._LayoutParams12068 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$MarginLayoutParams;)V");
}
}
internal static global::MonoJavaBridge.MethodId _addView12069;
public override void addView(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._addView12069, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._addView12069, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addView12070;
public override void addView(android.view.View arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._addView12070, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._addView12070, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addView12071;
public override void addView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._addView12071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._addView12071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addView12072;
public override void addView(android.view.View arg0, int arg1, android.view.ViewGroup.LayoutParams arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._addView12072, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._addView12072, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _onLayout12073;
protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._onLayout12073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._onLayout12073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _requestLayout12074;
public override void requestLayout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._requestLayout12074);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._requestLayout12074);
}
internal static global::MonoJavaBridge.MethodId _onMeasure12075;
protected override void onMeasure(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._onMeasure12075, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._onMeasure12075, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _checkLayoutParams12076;
protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.TableLayout._checkLayoutParams12076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._checkLayoutParams12076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnHierarchyChangeListener12077;
public override void setOnHierarchyChangeListener(android.view.ViewGroup.OnHierarchyChangeListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._setOnHierarchyChangeListener12077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._setOnHierarchyChangeListener12077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _generateLayoutParams12078;
public virtual new global::android.widget.TableLayout.LayoutParams generateLayoutParams(android.util.AttributeSet arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.TableLayout._generateLayoutParams12078, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.TableLayout.LayoutParams;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._generateLayoutParams12078, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.TableLayout.LayoutParams;
}
internal static global::MonoJavaBridge.MethodId _generateLayoutParams12079;
protected override global::android.widget.LinearLayout.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.TableLayout._generateLayoutParams12079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.LinearLayout.LayoutParams;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._generateLayoutParams12079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.LinearLayout.LayoutParams;
}
internal static global::MonoJavaBridge.MethodId _generateDefaultLayoutParams12080;
protected override global::android.widget.LinearLayout.LayoutParams generateDefaultLayoutParams()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.TableLayout._generateDefaultLayoutParams12080)) as android.widget.LinearLayout.LayoutParams;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._generateDefaultLayoutParams12080)) as android.widget.LinearLayout.LayoutParams;
}
internal static global::MonoJavaBridge.MethodId _isShrinkAllColumns12081;
public virtual bool isShrinkAllColumns()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.TableLayout._isShrinkAllColumns12081);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._isShrinkAllColumns12081);
}
internal static global::MonoJavaBridge.MethodId _setShrinkAllColumns12082;
public virtual void setShrinkAllColumns(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._setShrinkAllColumns12082, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._setShrinkAllColumns12082, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isStretchAllColumns12083;
public virtual bool isStretchAllColumns()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.TableLayout._isStretchAllColumns12083);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._isStretchAllColumns12083);
}
internal static global::MonoJavaBridge.MethodId _setStretchAllColumns12084;
public virtual void setStretchAllColumns(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._setStretchAllColumns12084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._setStretchAllColumns12084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setColumnCollapsed12085;
public virtual void setColumnCollapsed(int arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._setColumnCollapsed12085, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._setColumnCollapsed12085, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _isColumnCollapsed12086;
public virtual bool isColumnCollapsed(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.TableLayout._isColumnCollapsed12086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._isColumnCollapsed12086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setColumnStretchable12087;
public virtual void setColumnStretchable(int arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._setColumnStretchable12087, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._setColumnStretchable12087, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _isColumnStretchable12088;
public virtual bool isColumnStretchable(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.TableLayout._isColumnStretchable12088, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._isColumnStretchable12088, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setColumnShrinkable12089;
public virtual void setColumnShrinkable(int arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.TableLayout._setColumnShrinkable12089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._setColumnShrinkable12089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _isColumnShrinkable12090;
public virtual bool isColumnShrinkable(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.TableLayout._isColumnShrinkable12090, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.TableLayout.staticClass, global::android.widget.TableLayout._isColumnShrinkable12090, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _TableLayout12091;
public TableLayout(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TableLayout.staticClass, global::android.widget.TableLayout._TableLayout12091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _TableLayout12092;
public TableLayout(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.TableLayout.staticClass, global::android.widget.TableLayout._TableLayout12092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.TableLayout.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/TableLayout"));
global::android.widget.TableLayout._addView12069 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "addView", "(Landroid/view/View;)V");
global::android.widget.TableLayout._addView12070 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "addView", "(Landroid/view/View;I)V");
global::android.widget.TableLayout._addView12071 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V");
global::android.widget.TableLayout._addView12072 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "addView", "(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V");
global::android.widget.TableLayout._onLayout12073 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "onLayout", "(ZIIII)V");
global::android.widget.TableLayout._requestLayout12074 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "requestLayout", "()V");
global::android.widget.TableLayout._onMeasure12075 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "onMeasure", "(II)V");
global::android.widget.TableLayout._checkLayoutParams12076 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z");
global::android.widget.TableLayout._setOnHierarchyChangeListener12077 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "setOnHierarchyChangeListener", "(Landroid/view/ViewGroup$OnHierarchyChangeListener;)V");
global::android.widget.TableLayout._generateLayoutParams12078 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/widget/TableLayout$LayoutParams;");
global::android.widget.TableLayout._generateLayoutParams12079 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "generateLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Landroid/widget/LinearLayout$LayoutParams;");
global::android.widget.TableLayout._generateDefaultLayoutParams12080 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "generateDefaultLayoutParams", "()Landroid/widget/LinearLayout$LayoutParams;");
global::android.widget.TableLayout._isShrinkAllColumns12081 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "isShrinkAllColumns", "()Z");
global::android.widget.TableLayout._setShrinkAllColumns12082 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "setShrinkAllColumns", "(Z)V");
global::android.widget.TableLayout._isStretchAllColumns12083 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "isStretchAllColumns", "()Z");
global::android.widget.TableLayout._setStretchAllColumns12084 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "setStretchAllColumns", "(Z)V");
global::android.widget.TableLayout._setColumnCollapsed12085 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "setColumnCollapsed", "(IZ)V");
global::android.widget.TableLayout._isColumnCollapsed12086 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "isColumnCollapsed", "(I)Z");
global::android.widget.TableLayout._setColumnStretchable12087 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "setColumnStretchable", "(IZ)V");
global::android.widget.TableLayout._isColumnStretchable12088 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "isColumnStretchable", "(I)Z");
global::android.widget.TableLayout._setColumnShrinkable12089 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "setColumnShrinkable", "(IZ)V");
global::android.widget.TableLayout._isColumnShrinkable12090 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "isColumnShrinkable", "(I)Z");
global::android.widget.TableLayout._TableLayout12091 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "<init>", "(Landroid/content/Context;)V");
global::android.widget.TableLayout._TableLayout12092 = @__env.GetMethodIDNoThrow(global::android.widget.TableLayout.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
}
}
}
| |
//
// cpConstraint.cs
//
// Author:
// Jose Medrano <josmed@microsoft.com>
//
// Copyright (c) 2015
//
// 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;
namespace ChipmunkSharp
{
public class cpConstraint
{
internal cpSpace space;
/// The first body connected to this constraint.
public cpBody a, b;
internal cpConstraint next_a, next_b;
/// The maximum force that this constraint is allowed to use.
/// Defaults to infinity.
internal float maxForce;
/// The rate at which joint error is corrected.
/// Defaults to pow(1.0 - 0.1, 60.0) meaning that it will
/// correct 10% of the error every 1/60th of a second.
internal float errorBias;
/// The maximum rate at which joint error is corrected.
/// Defaults to infinity.
internal float maxBias;
internal bool collideBodies;
/// Function called before the solver runs.
/// Animate your joint anchors, update your motor torque, etc.
internal Action<cpSpace> preSolve;
//TODO: cpConstraintPreSolveFunc
/// Function called after the solver runs.
/// Use the applied impulse to perform effects like breakable joints.
//public cpConstraintPostSolveFunc postSolve;
internal Action<cpSpace> postSolve;
//TODO: cpConstraintPostSolveFunc
/// User definable data pointer.
/// Generally this points to your the game object class so you can access it
/// when given a cpConstraint reference in a callback.
internal object userData;
public cpConstraint(cpBody a, cpBody b)
{
/// The first body connected to this constraint.
this.a = a;
/// The second body connected to this constraint.
this.b = b;
this.space = null;
this.next_a = null;
this.next_b = null;
/// The maximum force that this constraint is allowed to use.
this.maxForce = cp.Infinity;
/// The rate at which joint error is corrected.
/// Defaults to pow(1 - 0.1, 60) meaning that it will
/// correct 10% of the error every 1/60th of a second.
this.errorBias = cp.cpfpow(1f - 0.1f, 60f);
/// The maximum rate at which joint error is corrected.
this.maxBias = cp.Infinity;
this.collideBodies = true;
//Not clear
preSolve = DefaultPreSolve;
postSolve = DefaultPostSolve;
}
public cpSpace GetSpace()
{
return this.space;
}
public cpBody GetBodyA()
{
return this.a;
}
public cpBody GetBodyB()
{
return this.b;
}
public float GetMaxForce()
{
return maxForce;
}
public void SetMaxForce(float maxForce)
{
cp.AssertHard(maxForce >= 0.0f, "maxForce must be positive.");
ActivateBodies();// cpConstraintActivateBodies(constraint);
this.maxForce = maxForce;
}
public float GetErrorBias()
{
return this.errorBias;
}
public void SetErrorBias(float errorBias)
{
cp.AssertHard(errorBias >= 0.0f, "errorBias must be positive.");
ActivateBodies();
this.errorBias = errorBias;
}
public float GetMaxBias()
{
return this.maxBias;
}
public void SetMaxBias(float maxBias)
{
cp.AssertHard(maxBias >= 0.0f, "errorBias must be positive.");
ActivateBodies();
this.maxBias = maxBias;
}
public bool GetCollideBodies()
{
return collideBodies;
}
public void SetCollideBodies(bool value)
{
ActivateBodies();
this.collideBodies = value;
}
public Action<cpSpace> GetPreSolveFunc()
{
return preSolve;
}
public void SetPreSolveFunc(Action<cpSpace> preSolveFunc)
{
this.preSolve = preSolveFunc;
}
public Action<cpSpace> GetPostSolveFunc()
{
return postSolve;
}
public void SetPostSolveFunc(Action<cpSpace> postSolve)
{
this.postSolve = postSolve;
}
public object GetUserData()
{
return userData;
}
public void SetUserData(object userData)
{
this.userData = userData;
}
public virtual float GetImpulse()
{
return 0;
}
public void ActivateBodies()
{
if (this.a != null)
this.a.Activate();
if (this.b != null)
this.b.Activate();
}
/// These methods are overridden by the constraint itself.
#region overriden methods
public virtual void PreStep(float dt) { }
public virtual void ApplyCachedImpulse(float dt_coef) { }
public virtual void ApplyImpulse(float dt)
{
}
//Function called before the solver runs. This can be overridden by the user
//to customize the constraint.
//Animate your joint anchors, update your motor torque, etc.
public virtual void DefaultPreSolve(cpSpace space)
{
}
//Function called after the solver runs. This can be overridden by the user
//to customize the constraint.
//Use the applied impulse to perform effects like breakable joints.
public virtual void DefaultPostSolve(cpSpace space)
{
}
#endregion
public virtual cpConstraint Next(cpBody body)
{
return (this.a == body ? this.next_a : this.next_b);
}
#region OverRideMethods
public virtual cpVect GetAnchorA()
{
throw new NotImplementedException();
}
public virtual cpVect GetAnchorB()
{
throw new NotImplementedException();
}
public virtual float GetMin()
{
throw new NotImplementedException();
}
public virtual float GetMax()
{
throw new NotImplementedException();
}
public virtual void SetMax(float max)
{
throw new NotImplementedException();
}
public virtual void SetAnchorB(cpVect anchr2)
{
throw new NotImplementedException();
}
public virtual void SetAnchorA(cpVect anchr1)
{
throw new NotImplementedException();
}
public virtual void SetMin(float min)
{
throw new NotImplementedException();
}
public virtual float GetDist()
{
throw new NotImplementedException();
}
public virtual void SetDist(float distance)
{
throw new NotImplementedException();
}
public virtual float GetRestLength()
{
throw new NotImplementedException();
}
public virtual void SetRestLength(float restLength)
{
throw new NotImplementedException();
}
public virtual float GetStiffness()
{
throw new NotImplementedException();
}
public virtual float GetDamping()
{
throw new NotImplementedException();
}
public virtual void SetStiffness(float stiffness)
{
throw new NotImplementedException();
}
public virtual void SetDamping(float damping)
{
throw new NotImplementedException();
}
public virtual cpVect GetGrooveA()
{
throw new NotImplementedException();
}
public virtual void SetGrooveA(cpVect grooveA)
{
throw new NotImplementedException();
}
public virtual cpVect GetGrooveB()
{
throw new NotImplementedException();
}
public virtual void SetGrooveB(cpVect grooveB)
{
throw new NotImplementedException();
}
public virtual float GetRestAngle()
{
throw new NotImplementedException();
}
public virtual void SetRestAngle(float restAngle)
{
throw new NotImplementedException();
}
public virtual float GetRatchet()
{
throw new NotImplementedException();
}
public virtual void SetRatchet(float ratchet)
{
throw new NotImplementedException();
}
public virtual float GetPhase()
{
throw new NotImplementedException();
}
public virtual float GetAngle()
{
throw new NotImplementedException();
}
public virtual void SetAngle(float angle)
{
throw new NotImplementedException();
}
public virtual void SetPhase(float phase)
{
throw new NotImplementedException();
}
public virtual float GetRatio()
{
throw new NotImplementedException();
}
public virtual void SetRatio(float ratchet)
{
throw new NotImplementedException();
}
public virtual float GetRate()
{
throw new NotImplementedException();
}
public virtual void SetRate(float rate)
{
throw new NotImplementedException();
}
#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.Text;
using System.Diagnostics;
namespace System.Globalization
{
internal static class TimeSpanFormat
{
private static unsafe void AppendNonNegativeInt32(StringBuilder sb, int n, int digits)
{
Debug.Assert(n >= 0);
uint value = (uint)n;
const int MaxUInt32Digits = 10;
char* buffer = stackalloc char[MaxUInt32Digits];
int index = 0;
do
{
uint div = value / 10;
buffer[index++] = (char)(value - (div * 10) + '0');
value = div;
}
while (value != 0);
Debug.Assert(index <= MaxUInt32Digits);
for (int i = digits - index; i > 0; --i) sb.Append('0');
for (int i = index - 1; i >= 0; --i) sb.Append(buffer[i]);
}
internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: false);
internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: true);
internal enum Pattern
{
None = 0,
Minimum = 1,
Full = 2,
}
/// <summary>Main method called from TimeSpan.ToString.</summary>
internal static string Format(TimeSpan value, string format, IFormatProvider formatProvider) =>
StringBuilderCache.GetStringAndRelease(FormatToBuilder(value, format, formatProvider));
/// <summary>Main method called from TimeSpan.TryFormat.</summary>
internal static bool TryFormat(TimeSpan value, Span<char> destination, out int charsWritten, string format, IFormatProvider formatProvider)
{
StringBuilder sb = FormatToBuilder(value, format, formatProvider);
if (sb.Length <= destination.Length)
{
charsWritten = sb.Length;
sb.CopyTo(0, destination, sb.Length);
StringBuilderCache.Release(sb);
return true;
}
else
{
StringBuilderCache.Release(sb);
charsWritten = 0;
return false;
}
}
private static StringBuilder FormatToBuilder(TimeSpan value, string format, IFormatProvider formatProvider)
{
if (format == null || format.Length == 0)
{
format = "c";
}
// Standard formats
if (format.Length == 1)
{
char f = format[0];
switch (f)
{
case 'c':
case 't':
case 'T':
return FormatStandard(
value,
isInvariant: true,
format: format,
pattern: Pattern.Minimum);
case 'g':
case 'G':
DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider);
return FormatStandard(
value,
isInvariant: false,
format: value.Ticks < 0 ? dtfi.FullTimeSpanNegativePattern : dtfi.FullTimeSpanPositivePattern,
pattern: f == 'g' ? Pattern.Minimum : Pattern.Full);
default:
throw new FormatException(SR.Format_InvalidString);
}
}
// Custom formats
return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider));
}
/// <summary>Format the TimeSpan instance using the specified format.</summary>
private static StringBuilder FormatStandard(TimeSpan value, bool isInvariant, string format, Pattern pattern)
{
StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
int day = (int)(value.Ticks / TimeSpan.TicksPerDay);
long time = value.Ticks % TimeSpan.TicksPerDay;
if (value.Ticks < 0)
{
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
FormatLiterals literal;
if (isInvariant)
{
literal = value.Ticks < 0 ?
NegativeInvariantFormatLiterals :
PositiveInvariantFormatLiterals;
}
else
{
literal = new FormatLiterals();
literal.Init(format, pattern == Pattern.Full);
}
if (fraction != 0)
{
// truncate the partial second to the specified length
fraction = (int)(fraction / TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
}
// Pattern.Full: [-]dd.hh:mm:ss.fffffff
// Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff]
sb.Append(literal.Start); // [-]
if (pattern == Pattern.Full || day != 0)
{
sb.Append(day); // [dd]
sb.Append(literal.DayHourSep); // [.]
} //
AppendNonNegativeInt32(sb, hours, literal.hh); // hh
sb.Append(literal.HourMinuteSep); // :
AppendNonNegativeInt32(sb, minutes, literal.mm); // mm
sb.Append(literal.MinuteSecondSep); // :
AppendNonNegativeInt32(sb, seconds, literal.ss); // ss
if (!isInvariant && pattern == Pattern.Minimum)
{
int effectiveDigits = literal.ff;
while (effectiveDigits > 0)
{
if (fraction % 10 == 0)
{
fraction = fraction / 10;
effectiveDigits--;
}
else
{
break;
}
}
if (effectiveDigits > 0)
{
sb.Append(literal.SecondFractionSep); // [.FFFFFFF]
sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
}
else if (pattern == Pattern.Full || fraction != 0)
{
sb.Append(literal.SecondFractionSep); // [.]
AppendNonNegativeInt32(sb, fraction, literal.ff); // [fffffff]
}
sb.Append(literal.End);
return sb;
}
/// <summary>Format the TimeSpan instance using the specified format.</summary>
private static StringBuilder FormatCustomized(TimeSpan value, string format, DateTimeFormatInfo dtfi)
{
Debug.Assert(dtfi != null);
int day = (int)(value.Ticks / TimeSpan.TicksPerDay);
long time = value.Ticks % TimeSpan.TicksPerDay;
if (value.Ticks < 0)
{
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
long tmp = 0;
int i = 0;
int tokenLen;
StringBuilder result = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
while (i < format.Length)
{
char ch = format[i];
int nextChar;
switch (ch)
{
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
throw new FormatException(SR.Format_InvalidString);
}
DateTimeFormat.FormatDigits(result, hours, tokenLen);
break;
case 'm':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
throw new FormatException(SR.Format_InvalidString);
}
DateTimeFormat.FormatDigits(result, minutes, tokenLen);
break;
case 's':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
{
throw new FormatException(SR.Format_InvalidString);
}
DateTimeFormat.FormatDigits(result, seconds, tokenLen);
break;
case 'f':
//
// The fraction of a second in single-digit precision. The remaining digits are truncated.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
{
throw new FormatException(SR.Format_InvalidString);
}
tmp = fraction;
tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
break;
case 'F':
//
// Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
{
throw new FormatException(SR.Format_InvalidString);
}
tmp = fraction;
tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
int effectiveDigits = tokenLen;
while (effectiveDigits > 0)
{
if (tmp % 10 == 0)
{
tmp = tmp / 10;
effectiveDigits--;
}
else
{
break;
}
}
if (effectiveDigits > 0)
{
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
break;
case 'd':
//
// tokenLen == 1 : Day as digits with no leading zero.
// tokenLen == 2+: Day as digits with leading zero for single-digit days.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 8)
{
throw new FormatException(SR.Format_InvalidString);
}
DateTimeFormat.FormatDigits(result, day, tokenLen, true);
break;
case '\'':
case '\"':
tokenLen = DateTimeFormat.ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day
// Most of the cases, "%" can be ignored.
nextChar = DateTimeFormat.ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != (int)'%')
{
result.Append(TimeSpanFormat.FormatCustomized(value, ((char)nextChar).ToString(), dtfi));
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
throw new FormatException(SR.Format_InvalidString);
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For example, "\d" will insert the character 'd' into the string.
//
nextChar = DateTimeFormat.ParseNextChar(format, i);
if (nextChar >= 0)
{
result.Append(((char)nextChar));
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new FormatException(SR.Format_InvalidString);
}
break;
default:
throw new FormatException(SR.Format_InvalidString);
}
i += tokenLen;
}
return result;
}
internal struct FormatLiterals
{
internal string AppCompatLiteral;
internal int dd;
internal int hh;
internal int mm;
internal int ss;
internal int ff;
private string[] _literals;
internal string Start => _literals[0];
internal string DayHourSep => _literals[1];
internal string HourMinuteSep => _literals[2];
internal string MinuteSecondSep => _literals[3];
internal string SecondFractionSep => _literals[4];
internal string End => _literals[5];
/* factory method for static invariant FormatLiterals */
internal static FormatLiterals InitInvariant(bool isNegative)
{
FormatLiterals x = new FormatLiterals();
x._literals = new string[6];
x._literals[0] = isNegative ? "-" : string.Empty;
x._literals[1] = ".";
x._literals[2] = ":";
x._literals[3] = ":";
x._literals[4] = ".";
x._literals[5] = string.Empty;
x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep;
x.dd = 2;
x.hh = 2;
x.mm = 2;
x.ss = 2;
x.ff = DateTimeFormat.MaxSecondsFractionDigits;
return x;
}
// For the "v1" TimeSpan localized patterns, the data is simply literal field separators with
// the constants guaranteed to include DHMSF ordered greatest to least significant.
// Once the data becomes more complex than this we will need to write a proper tokenizer for
// parsing and formatting
internal void Init(string format, bool useInvariantFieldLengths)
{
dd = hh = mm = ss = ff = 0;
_literals = new string[6];
for (int i = 0; i < _literals.Length; i++)
{
_literals[i] = string.Empty;
}
StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
bool inQuote = false;
char quote = '\'';
int field = 0;
for (int i = 0; i < format.Length; i++)
{
switch (format[i])
{
case '\'':
case '\"':
if (inQuote && (quote == format[i]))
{
/* we were in a quote and found a matching exit quote, so we are outside a quote now */
if (field >= 0 && field <= 5)
{
_literals[field] = sb.ToString();
sb.Length = 0;
inQuote = false;
}
else
{
Debug.Fail($"Unexpected field value: {field}");
return; // how did we get here?
}
}
else if (!inQuote)
{
/* we are at the start of a new quote block */
quote = format[i];
inQuote = true;
}
else
{
/* we were in a quote and saw the other type of quote character, so we are still in a quote */
}
break;
case '%':
Debug.Fail("Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
if (!inQuote)
{
i++; /* skip next character that is escaped by this backslash or percent sign */
break;
}
goto default;
case 'd':
if (!inQuote)
{
Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
dd++;
}
break;
case 'h':
if (!inQuote)
{
Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
hh++;
}
break;
case 'm':
if (!inQuote)
{
Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
mm++;
}
break;
case 's':
if (!inQuote)
{
Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
ss++;
}
break;
case 'f':
case 'F':
if (!inQuote)
{
Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
ff++;
}
break;
default:
sb.Append(format[i]);
break;
}
}
Debug.Assert(field == 5);
AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
if (useInvariantFieldLengths)
{
dd = 2;
hh = 2;
mm = 2;
ss = 2;
ff = DateTimeFormat.MaxSecondsFractionDigits;
}
else
{
if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation.
if (hh < 1 || hh > 2) hh = 2;
if (mm < 1 || mm > 2) mm = 2;
if (ss < 1 || ss > 2) ss = 2;
if (ff < 1 || ff > 7) ff = 7;
}
StringBuilderCache.Release(sb);
}
}
}
}
| |
/* transpiled with BefunCompile v1.3.0 (c) 2017 */
public static class Program
{
private static readonly string _g = "AR+LCAAAAAAABADdVMGO4yAM/RW3yV5AbDGQNkEIjfYDttfOKEr3xpUTp+6/r03SadrRaKRqTmspNQXbvPfspLy+vgJb82DwpJ1+nU7fWe/t7e1b8f1+NvETOx6P1X8X"+
"vqv9R/UKDN5nJ4cxdZKXyEtDSwjP1Ityn8ZBdtmjGjdFw6rMM/VmjIu1Z+8HiXyBzn76Iq0mnkujxPbvts9oPaWibR8AzbfzZty+wNYLL4TBbC1mjTb3Pcjoe6nHvuKI"+
"iOnnS2XazyQvtFbGpJ0x2XZiWl+/WNbGUzVN14c2nKdm4xXmeyDTorsPDUzCJ8Ngs0FFK5HAmFCoRNKWKSWNnj2EtQqh0F4trUcte2rmqClCdDZjpX6+3QaQorcko9GQ"+
"xp00Ow9Wp1W5eKNO7WTn2NWIWCP+LNGxbaEt5j3x6lsq6B1mLywmxTq1uHcCM/86YmMykmikk+Yj6QfVq5pKomo7rWSj9tXu3bG93tOAbaBrQNReNnQwkcZepV6+iwqh"+
"LSyEsbtkjKzyuvtJuPajha+NOE7R8zhqHkdM1iQh0SbpCzW+s6vmXjajQp+cuY5e5LwD5w1JLTH8cFgmuOOPhAayxR37QCMaZ0waHY0YiMj3jlAuGzUkZ6nhB3Kcld2c"+
"5GUKpH8nKkZX38kbxrIiGUU0wGVFBWZckg3slXV5kCbRX3YlYjnEz2pBeKA4MzlcNXh8UxvWWqU5ar/wXej6EJeYyrFcgDjCTHK4J0kceScUFOEyBkcjhAuRtU0ris0Q"+
"gTgCkVwo7meK+0QjKgTSwRTpGKT97PtS92m+KvoAU/fhk/Ixo0b8A6X0qdzQBwAA";
private static readonly long[] g = System.Array.ConvertAll(zd(System.Convert.FromBase64String(_g)),b=>(long)b);
private static byte[]zd(byte[]o){byte[]d=System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Skip(o, 1));for(int i=0;i<o[0];i++)d=zs(d);return d;}
private static byte[]zs(byte[]o){using(var c=new System.IO.MemoryStream(o))
using(var z=new System.IO.Compression.GZipStream(c,System.IO.Compression.CompressionMode.Decompress))
using(var r=new System.IO.MemoryStream()){z.CopyTo(r);return r.ToArray();}}
private static long gr(long x,long y){return(x>=0&&y>=0&&x<80&&y<25)?g[y*80+x]:0;}
private static void gw(long x,long y,long v){if(x>=0&&y>=0&&x<80&&y<25)g[y*80+x]=v;}
private static long td(long a,long b){ return (b==0)?0:(a/b); }
private static long tm(long a,long b){ return (b==0)?0:(a%b); }
private static System.Collections.Generic.Stack<long> s=new System.Collections.Generic.Stack<long>();
private static long sp(){ return (s.Count==0)?0:s.Pop(); }
private static void sa(long v){ s.Push(v); }
private static long sr(){ return (s.Count==0)?0:s.Peek(); }
static void Main(string[]args)
{
long t0,t1;
gw(2,1,67108864);
gw(3,1,3);
gw(1,3,0);
gw(24,8,0);
sa(15);
sa(15);
_1:
if(sp()!=0)goto _55;else goto _2;
_2:
sp();
_3:
t0=gr(3,1);
sa(gr(3,1));
sa(gr(3,1));
gw(1,0,0);
gw(2,0,t0);
_4:
gw(3,0,sp());
t0=gr(2,0);
sa(sr());
sa(t0);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
{long v0=sp();sa(td(sp(),v0));}
t1=sp();
sa(sp()+t1);
sa(sp()/2L);
if((sr()-gr(3,0))!=0)goto _53;else goto _5;
_5:
t0=gr(3,0)*gr(3,0);
gw(4,1,gr(3,0));
t0-=gr(3,1);
sp();
if((t0)!=0)goto _6;else goto _52;
_6:
gw(24,5,0);
gw(24,4,0);
gw(24,1,0);
gw(24,0,0);
sa(15);
sa(15);
_7:
if(sp()!=0)goto _51;else goto _8;
_8:
gw(24,1,1);
gw(24,4,1);
gw(1,2,0);
gw(2,2,1);
sp();
_9:
gw(3,2,td(gr(4,1)+gr(1,2),gr(2,2)));
sa(15);
sa(15);
sa(gr(24,0)+(gr(24,1)*gr(3,2))+gr(1,3));
gw(1,3,td(gr(24,0)+(gr(24,1)*gr(3,2))+gr(1,3),gr(2,1)));
_10:
sa(tm(sp(),gr(2,1)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()+9L);
sa(2);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()-1);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
if(sp()!=0)goto _50;else goto _11;
_11:
sp();
sa(15);
sa(15);
sa(gr(24,4)+(gr(24,5)*gr(3,2))+gr(1,3));
gw(1,3,td(gr(24,4)+(gr(24,5)*gr(3,2))+gr(1,3),gr(2,1)));
_12:
sa(tm(sp(),gr(2,1)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()+9L);
sa(6);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()-1);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
if(sp()!=0)goto _13;else goto _14;
_13:
sa(sr());
sa(sr());
t0=gr(sr()+9,4);
sa(sp()+9L);
sa(5);
{long v0=sp();t1=gr(sp(),v0);}
t1*=gr(3,2);
sa(t0+t1+gr(1,3));
gw(1,3,td(sr(),gr(2,1)));
goto _12;
_14:
gw(1,4,1);
gw(24,9,0);
sp();
sa(14);
sa(15);
_15:
if(sp()!=0)goto _49;else goto _16;
_16:
gw(2,4,15);
sp();
_17:
gw(3,4,gr(2,4)+9);
sa(15);
sa((gr(24,6)*gr(gr(2,4)+9,6)*gr(3,1))+gr(1,4)+gr(gr(3,4),9));
gw(1,4,td((gr(24,6)*gr(gr(2,4)+9,6)*gr(3,1))+gr(1,4)+gr(gr(3,4),9),gr(2,1)));
_18:
sa(tm(sp(),gr(2,1)));
gw(gr(3,4),9,sp());
sa(sp()-1L);
if(gr(3,4)!=9)goto _48;else goto _19;
_19:
t0=gr(2,4)-1;
sp();
if((gr(2,4))!=0)goto _47;else goto _20;
_20:
gw(1,4,0);
gw(24,7,0);
sa(14);
sa(15);
_21:
if(sp()!=0)goto _46;else goto _22;
_22:
gw(2,4,15);
sp();
_23:
gw(3,4,gr(2,4)+9);
sa(15);
sa((gr(24,2)*gr(gr(2,4)+9,2))+gr(1,4)+gr(gr(3,4),7));
gw(1,4,td((gr(24,2)*gr(gr(2,4)+9,2))+gr(1,4)+gr(gr(3,4),7),gr(2,1)));
_24:
sa(tm(sp(),gr(2,1)));
gw(gr(3,4),7,sp());
sa(sp()-1L);
if(gr(3,4)!=9)goto _45;else goto _25;
_25:
t0=gr(2,4)-1;
sp();
if((gr(2,4))!=0)goto _44;else goto _26;
_26:
sa(15);
sa(gr(24,7)-gr(24,9));
_27:
if(sp()!=0)goto _40;else goto _28;
_28:
sa(sr()-1);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
if(sp()!=0)goto _29;else goto _30;
_29:
sa(sr());
t0=gr(sr()+9,7);
sa(sp()+9L);
sa(9);
{long v0=sp();t1=gr(sp(),v0);}
sa(t0-t1);
goto _27;
_30:
t0=1;
t1=1;
sp();
sa(0);
sa(gr(9,2)-gr(9,8));
sa(gr(9,2)-gr(9,8));
_31:
if(sp()!=0)goto _36;else goto _32;
_32:
sp();
sa(sp()+1L);
if(sr()!=17)goto _35;else goto _33;
_33:
t0=gr(3,1)-999;
gw(3,1,gr(3,1)+1);
sp();
if((t0)!=0)goto _3;else goto _34;
_34:
System.Console.Out.Write(gr(1,1)+" ");
return;
_35:
sa(sr());
t0=gr(sr()+9,2);
sa(sp()+9L);
sa(8);
{long v0=sp();t1=gr(sp(),v0);}
sa(t0-t1);
sa(t0-t1);
goto _31;
_36:
sa((sp()>0)?1:0);
if(sp()!=0)goto _37;else goto _33;
_37:
gw(1,1,gr(3,1));
gw(24,8,gr(24,2));
sp();
sa(14);
sa(15);
_38:
if(sp()!=0)goto _39;else goto _33;
_39:
sa(sr());
sa(gr(sr()+9,2));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()+9L);
sa(8);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()-1);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
goto _38;
_40:
gw(1,2,(gr(3,2)*gr(2,2))-gr(1,2));
gw(2,2,td(gr(3,1)-(gr(1,2)*gr(1,2)),gr(2,2)));
sp();
sa(15);
sa(0);
_41:
if(sp()!=0)goto _42;else goto _43;
_42:
sp();
goto _9;
_43:
sa(sr());
sa(gr(sr()+9,1));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()+9L);
sa(0);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr());
sa(gr(sr()+9,2));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()+9L);
sa(1);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr());
sa(gr(sr()+9,5));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()+9L);
sa(4);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr());
sa(gr(sr()+9,6));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()+9L);
sa(5);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()-1);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa((sp()!=0)?0:1);
goto _41;
_44:
gw(2,4,t0);
goto _23;
_45:
sa(sr());
gw(3,4,(sr()+gr(2,4))-6);
sa(sp()+9L);
sa(2);
{long v0=sp();sa(gr(sp(),v0));}
sa(sp()*gr(gr(2,4)+9,2));
sa(sp()+gr(1,4));
sa(sp()+gr(gr(3,4),7));
gw(1,4,td(sr(),gr(2,1)));
goto _24;
_46:
sa(sr()+9);
sa(0);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(7);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()-1);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
goto _21;
_47:
gw(2,4,t0);
goto _17;
_48:
sa(sr());
gw(3,4,(sr()+gr(2,4))-6);
sa(sp()+9L);
sa(6);
{long v0=sp();sa(gr(sp(),v0));}
sa(sp()*gr(gr(2,4)+9,6)*gr(3,1));
sa(sp()+gr(1,4));
sa(sp()+gr(gr(3,4),9));
gw(1,4,td(sr(),gr(2,1)));
goto _18;
_49:
sa(sr()+9);
sa(0);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(9);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()-1);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
goto _15;
_50:
sa(sr());
sa(sr());
t0=gr(sr()+9,0);
sa(sp()+9L);
sa(1);
{long v0=sp();t1=gr(sp(),v0);}
t1*=gr(3,2);
sa(t0+t1+gr(1,3));
gw(1,3,td(sr(),gr(2,1)));
goto _10;
_51:
sa(sr()+8);
sa(0);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(5);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()+8);
sa(0);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(4);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()+8);
sa(0);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(1);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr()+8);
sa(0);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(0);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sp()-1L);
sa(sr());
goto _7;
_52:
gw(3,1,gr(3,1)+1);
t0=gr(3,1);
sa(gr(3,1));
sa(gr(3,1));
gw(1,0,0);
gw(2,0,t0);
goto _4;
_53:
if((sr()-gr(1,0))!=0)goto _54;else goto _5;
_54:
gw(1,0,gr(3,0));
sa(sr());
goto _4;
_55:
sa(sr()+8);
sa(0);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(8);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sp()-1L);
sa(sr());
goto _1;
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT 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 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using SharpNeat.Core;
using SharpNeat.Phenomes;
namespace SharpNeat.Domains.FunctionRegression
{
/// <summary>
/// Function regression task.
/// The function to be regressed is read from the config data. There is always one output.
/// </summary>
public class FunctionRegressionEvaluator : IPhenomeEvaluator<IBlackBox>
{
/// <summary>
/// The maximum error for the evaluator. The output at each sample point is in the range 0 to 1. Thus the error at each point has a maximum of 1.0.
/// The error for the evaulator as a whole is the root mean square error (RMSE) over all sample points. Thus max error is always 1.0
/// </summary>
const double MaxError = 1.0;
ulong _evalCount;
bool _stopConditionSatisfied;
ParameterSamplingInfo[] _paramSamplingInfoArr;
IFunction _fnTask;
double _samplePointCount;
double _samplePointCountReciprocal;
#region Constructor
/// <summary>
/// Construct a function regress evaluator with the provided parameter sampling info and function to regress.
/// </summary>
public FunctionRegressionEvaluator(ParameterSamplingInfo[] paramSamplingInfoArr, IFunction fnTask)
{
_paramSamplingInfoArr = paramSamplingInfoArr;
_fnTask = fnTask;
// Calculate the total numeber of sample points.
int samplePointCount = 1;
for(int i=0; i<_paramSamplingInfoArr.Length; i++) {
samplePointCount *= _paramSamplingInfoArr[i]._sampleCount;
}
_samplePointCount = samplePointCount;
_samplePointCountReciprocal = 1.0 / _samplePointCount;
}
#endregion
#region IPhenomeEvaluator<IBlackBox> Members
/// <summary>
/// Gets the total number of evaluations that have been performed.
/// </summary>
public ulong EvaluationCount
{
get { return _evalCount; }
}
/// <summary>
/// Gets a value indicating whether some goal fitness has been achieved and that
/// the the evolutionary algorithm/search should stop. This property's value can remain false
/// to allow the algorithm to run indefinitely.
/// </summary>
public bool StopConditionSatisfied
{
get { return _stopConditionSatisfied; }
}
/// <summary>
/// Evaluate the provided IBlackBox against the XOR problem domain and return its fitness score.
/// </summary>
public FitnessInfo Evaluate(IBlackBox box)
{
_evalCount++;
int paramCount = _paramSamplingInfoArr.Length;
int paramIdxBound = paramCount - 1;
int[] sampleIdxArr = new int[paramCount];
int[] sampleCountArr = new int[paramCount];
double[] paramValueArr = new double[paramCount];
double[] paramIncrArr = new double[paramCount];
for(int i=0; i<paramCount; i++)
{
sampleCountArr[i] = _paramSamplingInfoArr[i]._sampleCount;
paramValueArr[i] = _paramSamplingInfoArr[i]._min;
paramIncrArr[i] = _paramSamplingInfoArr[i]._incr;
}
// Error accumulator.
double errorAcc = 0.0;
for(;;)
{
// Reset black box internal state.
box.ResetState();
// Apply function arguments to black box inputs.
for(int i=0; i<paramCount; i++) {
box.InputSignalArray[i] = paramValueArr[i];
}
// Activate black box.
box.Activate();
// Get the black box's output value.
double response = box.OutputSignalArray[0];
// Get correct function value to compare with.
double correctVal = _fnTask.GetValue(paramValueArr);
// Accumulate squared error at each sample bpoint. Abs() not required because we are squaring.
errorAcc += (response-correctVal) * (response-correctVal);
// Determine next sample point.
for(int i=0; i<paramCount; i++)
{
sampleIdxArr[i]++;
if(sampleIdxArr[i] < sampleCountArr[i])
{ // The parameter has incremented without reaching its bound.
// We have the next valid sample point, so break out of the loop.
paramValueArr[i] += paramIncrArr[i];
break;
}
// The current parameter has reached its bound.
// If the *last* parameter has reached its bound then exit the outer loop.
if(i == paramIdxBound) {
goto exit;
}
// Reset the parameter and allow the inner loop to continue. This will
// increment the next parameter.
sampleIdxArr[i] = 0;
paramValueArr[i] = _paramSamplingInfoArr[i]._min;
}
}
exit:
double fitness = MaxError - Math.Sqrt(errorAcc * _samplePointCountReciprocal);
if(fitness < 0.5) {
fitness = 0.0;
} else {
fitness = (fitness-0.5) * 2.0;
}
// Note. This is correct. Network's response is subtracted from MaxError; if all responses are correct then fitness == MaxError.
if(fitness == MaxError) {
_stopConditionSatisfied = true;
}
return new FitnessInfo(fitness, fitness);
}
/// <summary>
/// Reset the internal state of the evaluation scheme if any exists.
/// </summary>
public void Reset()
{
}
#endregion
#region Public Static Methods
/// <summary>
/// Get an instance of the function class for the specified function type.
/// </summary>
/// <param name="fnId"></param>
/// <returns></returns>
public static IFunction GetFunction(FunctionId fnId)
{
switch(fnId)
{
case FunctionId.Abs:
return new AbsFunction();
case FunctionId.Log:
return new LogFunction();
case FunctionId.Multiplication:
return new MultiplicationFunction();
case FunctionId.Sine:
return new SineFunction();
case FunctionId.SineXSquared:
return new SineXSquaredFunction();
}
throw new ArgumentException(string.Format("Unknown FunctionId type [{0}]", fnId));
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Dns;
using Microsoft.Azure.Management.Dns.Models;
namespace Microsoft.Azure.Management.Dns
{
/// <summary>
/// Client for managing DNS zones and record.
/// </summary>
public static partial class ZoneOperationsExtensions
{
/// <summary>
/// Removes a DNS zone from a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='ifMatch'>
/// Optional. Defines the If-Match condition. The delete operation will
/// be performed only if the ETag of the zone on the server matches
/// this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. The delete operation
/// will be performed only if the ETag of the zone on the server does
/// not match this value.
/// </param>
/// <returns>
/// The response to a Zone Delete operation.
/// </returns>
public static ZoneDeleteResponse BeginDeleting(this IZoneOperations operations, string resourceGroupName, string zoneName, string ifMatch, string ifNoneMatch)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).BeginDeletingAsync(resourceGroupName, zoneName, ifMatch, ifNoneMatch);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Removes a DNS zone from a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='ifMatch'>
/// Optional. Defines the If-Match condition. The delete operation will
/// be performed only if the ETag of the zone on the server matches
/// this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. The delete operation
/// will be performed only if the ETag of the zone on the server does
/// not match this value.
/// </param>
/// <returns>
/// The response to a Zone Delete operation.
/// </returns>
public static Task<ZoneDeleteResponse> BeginDeletingAsync(this IZoneOperations operations, string resourceGroupName, string zoneName, string ifMatch, string ifNoneMatch)
{
return operations.BeginDeletingAsync(resourceGroupName, zoneName, ifMatch, ifNoneMatch, CancellationToken.None);
}
/// <summary>
/// Creates a DNS zone within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// Optional. The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <returns>
/// The response to a Zone CreateOrUpdate operation.
/// </returns>
public static ZoneCreateOrUpdateResponse CreateOrUpdate(this IZoneOperations operations, string resourceGroupName, string zoneName, ZoneCreateOrUpdateParameters parameters, string ifMatch, string ifNoneMatch)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).CreateOrUpdateAsync(resourceGroupName, zoneName, parameters, ifMatch, ifNoneMatch);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a DNS zone within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// Optional. The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <returns>
/// The response to a Zone CreateOrUpdate operation.
/// </returns>
public static Task<ZoneCreateOrUpdateResponse> CreateOrUpdateAsync(this IZoneOperations operations, string resourceGroupName, string zoneName, ZoneCreateOrUpdateParameters parameters, string ifMatch, string ifNoneMatch)
{
return operations.CreateOrUpdateAsync(resourceGroupName, zoneName, parameters, ifMatch, ifNoneMatch, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='ifMatch'>
/// Optional. Defines the If-Match condition. The delete operation will
/// be performed only if the ETag of the zone on the server matches
/// this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. The delete operation
/// will be performed only if the ETag of the zone on the server does
/// not match this value.
/// </param>
/// <returns>
/// The response to a Zone Delete operation.
/// </returns>
public static ZoneDeleteResponse Delete(this IZoneOperations operations, string resourceGroupName, string zoneName, string ifMatch, string ifNoneMatch)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).DeleteAsync(resourceGroupName, zoneName, ifMatch, ifNoneMatch);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='ifMatch'>
/// Optional. Defines the If-Match condition. The delete operation will
/// be performed only if the ETag of the zone on the server matches
/// this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. The delete operation
/// will be performed only if the ETag of the zone on the server does
/// not match this value.
/// </param>
/// <returns>
/// The response to a Zone Delete operation.
/// </returns>
public static Task<ZoneDeleteResponse> DeleteAsync(this IZoneOperations operations, string resourceGroupName, string zoneName, string ifMatch, string ifNoneMatch)
{
return operations.DeleteAsync(resourceGroupName, zoneName, ifMatch, ifNoneMatch, CancellationToken.None);
}
/// <summary>
/// Gets a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <returns>
/// The response to a Zone Get operation.
/// </returns>
public static ZoneGetResponse Get(this IZoneOperations operations, string resourceGroupName, string zoneName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).GetAsync(resourceGroupName, zoneName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a DNS zone.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <returns>
/// The response to a Zone Get operation.
/// </returns>
public static Task<ZoneGetResponse> GetAsync(this IZoneOperations operations, string resourceGroupName, string zoneName)
{
return operations.GetAsync(resourceGroupName, zoneName, CancellationToken.None);
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static ZoneListResponse ListNext(this IZoneOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static Task<ZoneListResponse> ListNextAsync(this IZoneOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static ZoneListResponse ListZonesInResourceGroup(this IZoneOperations operations, string resourceGroupName, ZoneListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).ListZonesInResourceGroupAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static Task<ZoneListResponse> ListZonesInResourceGroupAsync(this IZoneOperations operations, string resourceGroupName, ZoneListParameters parameters)
{
return operations.ListZonesInResourceGroupAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static ZoneListResponse ListZonesInSubscription(this IZoneOperations operations, ZoneListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).ListZonesInSubscriptionAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the DNS zones within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns the default
/// number of zones.
/// </param>
/// <returns>
/// The response to a Zone List or ListAll operation.
/// </returns>
public static Task<ZoneListResponse> ListZonesInSubscriptionAsync(this IZoneOperations operations, ZoneListParameters parameters)
{
return operations.ListZonesInSubscriptionAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Creates a DNS zone within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// Optional. The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <returns>
/// The response to a Zone Update operation.
/// </returns>
public static ZoneUpdateResponse Update(this IZoneOperations operations, string resourceGroupName, string zoneName, ZoneUpdateParameters parameters, string ifMatch, string ifNoneMatch)
{
return Task.Factory.StartNew((object s) =>
{
return ((IZoneOperations)s).UpdateAsync(resourceGroupName, zoneName, parameters, ifMatch, ifNoneMatch);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a DNS zone within a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Dns.IZoneOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// Required. The name of the zone without a terminating dot.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// Optional. The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Optional. Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <returns>
/// The response to a Zone Update operation.
/// </returns>
public static Task<ZoneUpdateResponse> UpdateAsync(this IZoneOperations operations, string resourceGroupName, string zoneName, ZoneUpdateParameters parameters, string ifMatch, string ifNoneMatch)
{
return operations.UpdateAsync(resourceGroupName, zoneName, parameters, ifMatch, ifNoneMatch, CancellationToken.None);
}
}
}
| |
// <copyright file="WebSocketServer.cs" company="WebDriver Committers">
// Copyright 2007-2012 WebDriver committers
// Copyright 2007-2012 Google Inc.
// Portions copyright 2012 Software Freedom Conservancy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
namespace OpenQA.Selenium.Safari.Internal
{
/// <summary>
/// Provides an implementation of a WebSocket server.
/// </summary>
public class WebSocketServer : IWebSocketServer
{
private readonly string scheme;
private X509Certificate2 authenticationX509Certificate;
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class.
/// </summary>
/// <param name="location">The location at which to listen for connections.</param>
public WebSocketServer(string location)
: this(8181, location)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketServer"/> class.
/// </summary>
/// <param name="port">The port on which to listen for connections.</param>
/// <param name="location">The location at which to listen for connections.</param>
public WebSocketServer(int port, string location)
{
var uri = new Uri(location);
this.Port = port > 0 ? port : uri.Port;
this.Location = location;
this.scheme = uri.Scheme;
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
this.ListenerSocket = new SocketWrapper(socket);
this.ListenerSocket.Accepted += new EventHandler<AcceptEventArgs>(this.ListenerSocketAcceptedEventHandler);
}
/// <summary>
/// Event raised when a message is received from the WebSocket.
/// </summary>
public event EventHandler<TextMessageHandledEventArgs> MessageReceived;
/// <summary>
/// Event raised when a connection is opened.
/// </summary>
public event EventHandler<ConnectionEventArgs> Opened;
/// <summary>
/// Event raised when a connection is closed.
/// </summary>
public event EventHandler<ConnectionEventArgs> Closed;
/// <summary>
/// Event raised when an error occurs.
/// </summary>
public event EventHandler<ErrorEventArgs> ErrorOccurred;
/// <summary>
/// Event raised when a non-WebSocket message is received.
/// </summary>
public event EventHandler<StandardHttpRequestReceivedEventArgs> StandardHttpRequestReceived;
/// <summary>
/// Gets or sets the <see cref="ISocket"/> on which communication occurs.
/// </summary>
public ISocket ListenerSocket { get; set; }
/// <summary>
/// Gets the location the server is listening on for connections.
/// </summary>
public string Location { get; private set; }
/// <summary>
/// Gets the port the server is listening on for connections.
/// </summary>
public int Port { get; private set; }
/// <summary>
/// Gets or sets the certificate used for authentication.
/// </summary>
public string Certificate { get; set; }
/// <summary>
/// Gets a value indicating whether the connection is secure.
/// </summary>
public bool IsSecure
{
get { return this.scheme == "wss" && this.Certificate != null; }
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
var localIPAddress = new IPEndPoint(IPAddress.Any, this.Port);
this.ListenerSocket.Bind(localIPAddress);
this.ListenerSocket.Listen(100);
if (this.scheme == "wss")
{
if (this.Certificate == null)
{
return;
}
this.authenticationX509Certificate = new X509Certificate2(this.Certificate);
}
this.ListenForClients();
}
/// <summary>
/// Releases all resources used by the <see cref="WebSocketServer"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Raises the ConnectionOpened event.
/// </summary>
/// <param name="e">A <see cref="ConnectionEventArgs"/> that contains the event data.</param>
protected void OnConnectionOpened(ConnectionEventArgs e)
{
if (this.Opened != null)
{
this.Opened(this, e);
}
}
/// <summary>
/// Raises the ConnectionClosed event.
/// </summary>
/// <param name="e">A <see cref="ConnectionEventArgs"/> that contains the event data.</param>
protected void OnConnectionClosed(ConnectionEventArgs e)
{
if (this.Closed != null)
{
this.Closed(this, e);
}
}
/// <summary>
/// Raises the StandardHttpRequestReceived event.
/// </summary>
/// <param name="e">A <see cref="StandardHttpRequestReceivedEventArgs"/> that contains the event data.</param>
protected void OnStandardHttpRequestReceived(StandardHttpRequestReceivedEventArgs e)
{
if (this.StandardHttpRequestReceived != null)
{
this.StandardHttpRequestReceived(this, e);
}
}
/// <summary>
/// Raises the MessageReceived event.
/// </summary>
/// <param name="e">A <see cref="TextMessageHandledEventArgs"/> that contains the event data.</param>
protected void OnMessageReceived(TextMessageHandledEventArgs e)
{
if (this.MessageReceived != null)
{
this.MessageReceived(this, e);
}
}
/// <summary>
/// Raises the ErrorOccurred event.
/// </summary>
/// <param name="e">An <see cref="ErrorEventArgs"/> that contains the event data.</param>
protected void OnErrorOccurred(ErrorEventArgs e)
{
if (this.ErrorOccurred != null)
{
this.ErrorOccurred(this, e);
}
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="SocketWrapper"/> and optionally
/// releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release managed and resources;
/// <see langword="false"/> to only release unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.ListenerSocket.Dispose();
}
}
private void ListenForClients()
{
this.ListenerSocket.Accept();
}
private void OnClientConnect(ISocket clientSocket)
{
this.ListenForClients();
WebSocketConnection connection = null;
connection = new WebSocketConnection(clientSocket, this.scheme);
connection.MessageReceived += new EventHandler<TextMessageHandledEventArgs>(this.ConnectionMessageReceivedEventHandler);
connection.BinaryMessageReceived += new EventHandler<BinaryMessageHandledEventArgs>(this.ConnectionBinaryMessageReceivedEventHandler);
connection.Opened += new EventHandler<ConnectionEventArgs>(this.ConnectionOpenedEventHandler);
connection.Closed += new EventHandler<ConnectionEventArgs>(this.ConnectionClosedEventHandler);
connection.ErrorReceived += new EventHandler<ErrorEventArgs>(this.ConnectionErrorEventHandler);
connection.StandardHttpRequestReceived += new EventHandler<StandardHttpRequestReceivedEventArgs>(this.ConnectionStandardHttpRequestReceivedEventHandler);
if (this.IsSecure)
{
clientSocket.Authenticated += new EventHandler(this.SocketAuthenticatedEventHandler);
clientSocket.Authenticate(this.authenticationX509Certificate);
}
else
{
connection.StartReceiving();
}
}
private void ListenerSocketAcceptedEventHandler(object sender, AcceptEventArgs e)
{
this.OnClientConnect(e.Socket);
}
private void ConnectionClosedEventHandler(object sender, ConnectionEventArgs e)
{
this.OnConnectionClosed(new ConnectionEventArgs(e.Connection));
}
private void ConnectionOpenedEventHandler(object sender, ConnectionEventArgs e)
{
this.OnConnectionOpened(new ConnectionEventArgs(e.Connection));
}
private void ConnectionBinaryMessageReceivedEventHandler(object sender, BinaryMessageHandledEventArgs e)
{
throw new NotImplementedException();
}
private void ConnectionMessageReceivedEventHandler(object sender, TextMessageHandledEventArgs e)
{
this.OnMessageReceived(e);
}
private void ConnectionStandardHttpRequestReceivedEventHandler(object sender, StandardHttpRequestReceivedEventArgs e)
{
this.OnStandardHttpRequestReceived(e);
}
private void ConnectionErrorEventHandler(object sender, ErrorEventArgs e)
{
this.OnErrorOccurred(e);
}
private void SocketAuthenticatedEventHandler(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Windows;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Outlining;
using Microsoft.Cci;
using UtilitiesNamespace;
namespace Adornments {
/// <summary>
/// Used to manager adornments on a particular text view's adornment layer (<see cref="IAdornmentLayer"/>).
/// </summary>
public class AdornmentManager {
readonly IWpfTextView _textView;
readonly IAdornmentLayer _layer;
readonly IOutliningManager _outliningManager;
/// <summary>
/// A collection of adornments, indexed by a special "Tag" object, that should be rendered in this's adornment layer.
/// </summary>
readonly IDictionary<object, IAdornment> _adornments = new Dictionary<object, IAdornment>();
public IDictionary<object, IAdornment> Adornments
{
get
{
Contract.Ensures(Contract.Result<IDictionary<object, IAdornment>>() != null);
return this._adornments;
}
}
readonly IList<IStaticAdornment> _staticAdornments = new List<IStaticAdornment>();
///// <summary>
///// An array of "Adorments"'s keys sorted by appearance in text view.
///// </summary>
//public object[] SortedAdornmentKeys;
#if TRACKING_REMOVED_ADORNMENTS
bool _adornmentWasRemoved = false;
#endif
/// <summary>
/// Checks to see if this AdornmentManager has an adornment for the method specified by a given "Tag".
/// </summary>
public bool ContainsAdornment(object tag) {
return Adornments.ContainsKey(tag);
}
bool _newStaticAdornments = false;
//KeyValuePair<object, IAdornment>? currentCaretAdornment = null;
readonly Logger _logger;
//bool _shouldRefreshLineTransformer = false;
[ContractInvariantMethod]
void ObjectInvariant() {
Contract.Invariant(_textView != null);
Contract.Invariant(_logger != null);
Contract.Invariant(_adornments != null);
}
/// <summary>
/// Gets or creates an adornment manager for a particular text view.
/// </summary>
public static AdornmentManager GetOrCreateAdornmentManager(IWpfTextView textView, string adornmentLayer, IOutliningManager outliningManager, Logger logger) {
Contract.Requires(textView != null);
Contract.Requires(!String.IsNullOrEmpty(adornmentLayer));
Contract.Requires(outliningManager != null);
Contract.Requires(logger != null);
Contract.Ensures(Contract.Result<AdornmentManager>() != null);
return textView.Properties.GetOrCreateSingletonProperty<AdornmentManager>(adornmentLayer, delegate { return new AdornmentManager(textView, adornmentLayer, outliningManager, logger); });
}
/// <summary>
/// Tries to get an adornment manager for a particular text view.
/// </summary>
public static bool TryGetAdornmentManager(IWpfTextView textView, string adornmentLayer, out AdornmentManager adornmentManager) {
Contract.Requires(textView != null);
return textView.Properties.TryGetProperty<AdornmentManager>(adornmentLayer, out adornmentManager);
}
/// <summary>
/// Initializes a new AdornmentManger.
/// </summary>
/// <remarks>
/// Use <see cref="AdornmentManager.GetOrCreateAdornmentManager"/> to create a new AdornmentManager.
/// </remarks>
private AdornmentManager(IWpfTextView textView, string adornmentLayer, IOutliningManager outliningManager, Logger logger) {
Contract.Requires(textView != null);
Contract.Requires(!String.IsNullOrEmpty(adornmentLayer));
Contract.Requires(outliningManager != null);
Contract.Requires(logger != null);
_logger = logger;
_logger.Failed += OnFailed;
_textView = textView;
_layer = textView.GetAdornmentLayer(adornmentLayer);
_textView.LayoutChanged += OnLayoutChanged;
_textView.Closed += OnTextViewClosed;
_textView.ViewportHeightChanged += UpdateStaticAdornments;
_textView.ViewportWidthChanged += UpdateStaticAdornments;
//_textView.Caret.PositionChanged += OnCaretMoved;
//textView.MouseHover += OnMouseHover;
_outliningManager = outliningManager;
_outliningManager.RegionsCollapsed += OnRegionsCollapsed;
_outliningManager.RegionsExpanded += OnRegionsExpanded;
}
void OnFailed() {
_logger.Failed -= OnFailed;
UnsubscribeFromAllEvents();
}
public void QueueRefreshLineTransformer() {
_logger.QueueWorkItem(_textView.RefreshLineTransformer);
}
void UpdateStaticAdornments(object sender, EventArgs e) {
foreach (var adornment in _staticAdornments) {
_layer.RemoveAdornment(adornment.Visual);
if (adornment.OffsetLeft) {
Canvas.SetLeft(adornment.Visual, adornment.OffsetWidth);
} else {
Canvas.SetLeft(adornment.Visual, _textView.ViewportRight - adornment.OffsetWidth - adornment.Visual.ActualWidth);
}
if (adornment.OffsetTop) {
Canvas.SetTop(adornment.Visual, _textView.ViewportTop + adornment.OffsetHeight);
} else {
Canvas.SetTop(adornment.Visual, _textView.ViewportBottom - adornment.OffsetWidth - adornment.Visual.ActualHeight);
}
_layer.AddAdornment(AdornmentPositioningBehavior.ViewportRelative, null, null, adornment.Visual, null);
}
}
void OnTextViewClosed(object sender, EventArgs e) {
_logger.PublicEntry(() => {
UnsubscribeFromAllEvents();
}, "OnTextViewClosed");
}
void UnsubscribeFromAllEvents() {
_textView.LayoutChanged -= OnLayoutChanged;
_textView.Closed -= OnTextViewClosed;
_textView.ViewportHeightChanged -= UpdateStaticAdornments;
_textView.ViewportWidthChanged -= UpdateStaticAdornments;
_outliningManager.RegionsCollapsed -= OnRegionsCollapsed;
_outliningManager.RegionsExpanded -= OnRegionsExpanded;
Adornments.Clear();
_staticAdornments.Clear();
_layer.RemoveAllAdornments();
_logger.WriteToLog("Emptied adornments from the adornments manager.");
}
/// <summary>
/// If that layout is updated, add this's adornments back onto this's text view's adornment layer.
/// </summary>
/// <remarks>
/// When a text view's layout is updated, any adornments that were attached to the new or reformatted lines are removed.
/// </remarks>
void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) {
try {
//if (adornmentWasRemoved) {
foreach (var line in e.NewOrReformattedLines)
CreateVisuals(line);
#if TRACKING_REMOVED_ADORNMENTS
_adornmentWasRemoved = false;
#endif
//}
if (_newStaticAdornments)
UpdateStaticAdornments(null, null);
} catch (Exception exn) {
_logger.PublicEntryException(exn, "OnLayoutChanged");
}
}
/// <summary>
/// When a region is expanded, we want to make sure all adornments within that region are visable.
/// </summary>
void OnRegionsExpanded(object sender, RegionsExpandedEventArgs e) {
//return;//TODO: Dead?
_logger.PublicEntry(() => {
foreach (var region in e.ExpandedRegions) {
ShowVisuals(region.Extent);
}
}, "OnRegionsExpanded");
}
/// <summary>
/// When a region is collapsed, we want to make sure all adornments within that region are hidden.
/// </summary>
void OnRegionsCollapsed(object sender, RegionsCollapsedEventArgs e) {
//return;//TODO: Dead?
_logger.PublicEntry(() => {
foreach (var region in e.CollapsedRegions) {
CollapseVisuals(region.Extent);
}
}, "OnRegionsCollapsed");
}
/// <summary>
/// Hide all adornments within the given extent.
/// </summary>
public void CollapseVisuals(ITrackingSpan extent) {
Contract.Requires(extent != null);
var extentSpan = extent.GetSpan(_textView.TextBuffer.CurrentSnapshot.Version);
foreach (var entry in Adornments) {
IAdornment adornment = entry.Value;
var adornmentSpan = adornment.Span.GetSpan(_textView.TextBuffer.CurrentSnapshot);
if (extentSpan.IntersectsWith(adornmentSpan)) {
adornment.CollapsedRegionDepth++;
QueueRefreshLineTransformer();
}
}
}
public void CollapseVisuals() {
foreach (var entry in Adornments) {
IAdornment adornment = entry.Value;
adornment.IsClosedByUser = true;
}
QueueRefreshLineTransformer();
}
/// <summary>
/// Shoe all adornments within the given extent.
/// </summary>
public void ShowVisuals(ITrackingSpan extent) {
Contract.Requires(extent != null);
var extentSpan = extent.GetSpan(_textView.TextBuffer.CurrentSnapshot.Version);
foreach (var entry in Adornments) {
IAdornment adornment = entry.Value;
var adornmentSpan = adornment.Span.GetSpan(_textView.TextBuffer.CurrentSnapshot);
if (extentSpan.IntersectsWith(adornmentSpan)) {
adornment.CollapsedRegionDepth--;
QueueRefreshLineTransformer();
}
}
}
public void ShowVisuals() {
foreach (var entry in Adornments) {
IAdornment adornment = entry.Value;
adornment.IsClosedByUser = false;
}
QueueRefreshLineTransformer();
}
/// <summary>
/// Adds all of this's adornments onto this's text view's adornment layer.
/// </summary>
void CreateVisuals() {
foreach (var line in _textView.TextViewLines)
CreateVisuals(line);
#if TRACKING_REMOVED_ADORNMENTS
_adornmentWasRemoved = false;
#endif
//foreach (var entry in adornments) {
// IAdornment adornment = entry.Value;
// object tag = entry.Key;
// CreateVisual(adornment, tag);
//}
}
/// <summary>
/// Adds all of this's adornments that pertain to a particular text view line back onto this's text view's adornment layer.
/// </summary>
void CreateVisuals(ITextViewLine line) {
foreach (var entry in Adornments) {
var adornment = entry.Value;
var tag = entry.Key;
if (line.ContainsBufferPosition(adornment.Span.GetStartPoint(_textView.TextSnapshot))) {
_layer.RemoveAdornmentsByTag(tag);
CreateVisual(line, adornment, tag);
}
}
}
/// <summary>
/// Adds a particular adornment onto this's text view's adornment layer.
/// </summary>
void CreateVisual(IAdornment adornment, object tag) {
ITextViewLine line = _textView.TextViewLines.GetTextViewLineContainingBufferPosition(adornment.Span.GetStartPoint(_textView.TextSnapshot));
if (line == null)
return;
CreateVisual(line, adornment, tag);
}
/// <summary>
/// Adds a particular adornment onto this's text view's adornment layer.
/// </summary>
void CreateVisual(ITextViewLine line, IAdornment adornment, object tag) {
FrameworkElement elem = adornment.Visual;
var span = adornment.Span.GetSpan(_textView.TextSnapshot);
Geometry g = _textView.TextViewLines.GetMarkerGeometry(new SnapshotSpan(_textView.TextSnapshot, Span.FromBounds(span.Start, line.End)));
if (g != null) {
//position the adornment such that it is at the top left corner of the line
Canvas.SetLeft(elem, g.Bounds.Left);
Canvas.SetTop(elem, g.Bounds.Top - adornment.Visual.ActualHeight);
} else {
_logger.WriteToLog("Failed to get marker geometry for adornment.");
}
AddAdornment(elem, line.Extent, tag);
}
void EvaluateAdornmentRegionDepth(IAdornment adornment) {
Contract.Requires(adornment != null && adornment.Span != null);
Contract.Requires(_outliningManager != null);
Contract.Requires(_textView != null);
try {
var workingSnapshot = _textView.TextSnapshot;
var collapsedRegionsAdornmentIsIn = _outliningManager.GetCollapsedRegions(adornment.Span.GetSpan(workingSnapshot));
Contract.Assume(collapsedRegionsAdornmentIsIn != null, "Let's make the assumption explicit");
adornment.CollapsedRegionDepth = collapsedRegionsAdornmentIsIn.Count();
} catch (ObjectDisposedException e) {
if (e.ObjectName == "OutliningManager")
_logger.WriteToLog("Error: The 'OutliningManager' is disposed, adornments may not be formatted correctly.");
else
throw e;
}
}
/// <summary>
/// Adds a particular adornment onto this's text view's adornment layer.
/// </summary>
void AddAdornment(UIElement element, SnapshotSpan span, object tag) {
_layer.AddAdornment(behavior: AdornmentPositioningBehavior.TextRelative,
visualSpan: span,
tag: tag,
adornment: element,
removedCallback: OnAdornmentRemoved);
}
/// <summary>
/// Adds a particular adornment onto this's text view's adornment layer.
/// </summary>
public void AddAdornment(IAdornment adornment, object tag) {
Contract.Requires(adornment != null);
Adornments[tag] = adornment;
CreateVisual(adornment, tag);
EvaluateAdornmentRegionDepth(adornment);
}
public void AddStaticAdornment(IStaticAdornment staticAdornment) {
_staticAdornments.Add(staticAdornment);
//staticAdornment.Visual.UpdateLayout();
_newStaticAdornments = true;
}
/// <summary>
/// Notifies this AdornmentManager that an adornment was removed so that on the next layout update, this's adornments can be updated.
/// </summary>
void OnAdornmentRemoved(object tag, UIElement visual) {
//Public Entry
#if TRACKING_REMOVED_ADORNMENTS
_adornmentWasRemoved = true;
#endif
}
/// <summary>
/// Gets a particular adornment.
/// </summary>
public IAdornment GetAdornment(object tag) {
IAdornment result;
if (Adornments.TryGetValue(tag, out result))
return result;
return null;
}
/// <summary>
/// Removes a particular adornment.
/// </summary>
public void RemoveAdornment(object tag) {
Adornments.Remove(tag);
_layer.RemoveAdornmentsByTag(tag);
}
}
static class ExtensionsHelper {
/// <summary>
/// Forces the line transformer to revaluate its transforms.
/// </summary>
/// <remarks>
/// Should not be called during the LayoutChanged event
/// </remarks>
public static void RefreshLineTransformer(this ITextView textView) {
var line = textView.TextViewLines.FirstVisibleLine;
textView.DisplayTextLineContainingBufferPosition(line.Start, line.Top - textView.ViewportTop, ViewRelativePosition.Top);
}
}
}
| |
// <copyright file="UserQRTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex.Factorization;
using MathNet.Numerics.LinearAlgebra.Factorization;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Factorization
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// QR factorization tests for a user matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class UserQRTests
{
/// <summary>
/// Constructor with wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void ConstructorWideMatrixThrowsInvalidMatrixOperationException()
{
Assert.That(() => UserQR.Create(new UserDefinedMatrix(3, 4)), Throws.ArgumentException);
}
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorQR = matrixI.QR();
var q = factorQR.Q;
var r = factorQR.R;
Assert.AreEqual(matrixI.RowCount, r.RowCount);
Assert.AreEqual(matrixI.ColumnCount, r.ColumnCount);
for (var i = 0; i < r.RowCount; i++)
{
for (var j = 0; j < r.ColumnCount; j++)
{
if (i == j)
{
Assert.AreEqual(-Complex.One, r[i, j]);
}
else
{
Assert.AreEqual(Complex.Zero, r[i, j]);
}
}
}
}
/// <summary>
/// Can factorize identity matrix using thin QR.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentityUsingThinQR(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorQR = matrixI.QR(QRMethod.Thin);
var r = factorQR.R;
Assert.AreEqual(matrixI.RowCount, r.RowCount);
Assert.AreEqual(matrixI.ColumnCount, r.ColumnCount);
for (var i = 0; i < r.RowCount; i++)
{
for (var j = 0; j < r.ColumnCount; j++)
{
if (i == j)
{
Assert.AreEqual(-Complex.One, r[i, j]);
}
else
{
Assert.AreEqual(Complex.Zero, r[i, j]);
}
}
}
}
/// <summary>
/// Identity determinant is one.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void IdentityDeterminantIsOne(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorQR = matrixI.QR();
Assert.AreEqual(Complex.One, factorQR.Determinant);
}
/// <summary>
/// Can factorize a random matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(10, 6)]
[TestCase(50, 48)]
[TestCase(100, 98)]
public void CanFactorizeRandomMatrix(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var factorQR = matrixA.QR(QRMethod.Full);
var q = factorQR.Q;
var r = factorQR.R;
// Make sure the R has the right dimensions.
Assert.AreEqual(row, r.RowCount);
Assert.AreEqual(column, r.ColumnCount);
// Make sure the Q has the right dimensions.
Assert.AreEqual(row, q.RowCount);
Assert.AreEqual(row, q.ColumnCount);
// Make sure the R factor is upper triangular.
for (var i = 0; i < r.RowCount; i++)
{
for (var j = 0; j < r.ColumnCount; j++)
{
if (i > j)
{
Assert.AreEqual(Complex.Zero, r[i, j]);
}
}
}
// Make sure the Q*R is the original matrix.
var matrixQfromR = q * r;
for (var i = 0; i < matrixQfromR.RowCount; i++)
{
for (var j = 0; j < matrixQfromR.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(matrixA[i, j], matrixQfromR[i, j], 9);
}
}
}
/// <summary>
/// Can factorize a random matrix using thin QR.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(10, 6)]
[TestCase(50, 48)]
[TestCase(100, 98)]
public void CanFactorizeRandomMatrixUsingThinQR(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var factorQR = matrixA.QR(QRMethod.Thin);
var q = factorQR.Q;
var r = factorQR.R;
// Make sure the R has the right dimensions.
Assert.AreEqual(column, r.RowCount);
Assert.AreEqual(column, r.ColumnCount);
// Make sure the Q has the right dimensions.
Assert.AreEqual(row, q.RowCount);
Assert.AreEqual(column, q.ColumnCount);
// Make sure the R factor is upper triangular.
for (var i = 0; i < r.RowCount; i++)
{
for (var j = 0; j < r.ColumnCount; j++)
{
if (i > j)
{
Assert.AreEqual(Complex.Zero, r[i, j]);
}
}
}
// Make sure the Q*R is the original matrix.
var matrixQfromR = q * r;
for (var i = 0; i < matrixQfromR.RowCount; i++)
{
for (var j = 0; j < matrixQfromR.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(matrixA[i, j], matrixQfromR[i, j], 9);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVector(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.QR();
var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(order, 1).ToArray());
var resultx = factorQR.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.QR();
var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixX = factorQR.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.QR();
var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(order, 1).ToArray());
var vectorbCopy = vectorb.Clone();
var resultx = new UserDefinedVector(order);
factorQR.Solve(vectorb, resultx);
Assert.AreEqual(vectorb.Count, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.QR();
var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixBCopy = matrixB.Clone();
var matrixX = new UserDefinedMatrix(order, order);
factorQR.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorUsingThinQR(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.QR(QRMethod.Thin);
var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(order, 1).ToArray());
var resultx = factorQR.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrixUsingThinQR(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.QR(QRMethod.Thin);
var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixX = factorQR.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGivenUsingThinQR(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.QR(QRMethod.Thin);
var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(order, 1).ToArray());
var vectorbCopy = vectorb.Clone();
var resultx = new UserDefinedVector(order);
factorQR.Solve(vectorb, resultx);
Assert.AreEqual(vectorb.Count, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrixWhenResultMatrixGivenUsingThinQR(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.QR(QRMethod.Thin);
var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var matrixBCopy = matrixB.Clone();
var matrixX = new UserDefinedMatrix(order, order);
factorQR.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Dynamic.Utils;
namespace System.Linq.Expressions.Compiler
{
/// <summary>
/// This type tracks "runtime" constants--live objects that appear in
/// ConstantExpression nodes and must be bound to the delegate.
/// </summary>
internal sealed class BoundConstants
{
/// <summary>
/// Constants can emit themselves as different types
/// For caching purposes, we need to treat each distinct Type as a
/// separate thing to cache. (If we have to cast it on the way out, it
/// ends up using a JIT temp and defeats the purpose of caching the
/// value in a local)
/// </summary>
private struct TypedConstant : IEquatable<TypedConstant>
{
internal readonly object Value;
internal readonly Type Type;
internal TypedConstant(object value, Type type)
{
Value = value;
Type = type;
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(Value) ^ Type.GetHashCode();
}
public bool Equals(TypedConstant other)
{
return object.ReferenceEquals(Value, other.Value) && Type.Equals(other.Type);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2231:OverloadOperatorEqualsOnOverridingValueTypeEquals")]
public override bool Equals(object obj)
{
return (obj is TypedConstant) && Equals((TypedConstant)obj);
}
}
/// <summary>
/// The list of constants in the order they appear in the constant array
/// </summary>
private readonly List<object> _values = new List<object>();
/// <summary>
/// The index of each constant in the constant array
/// </summary>
private readonly Dictionary<object, int> _indexes = new Dictionary<object, int>(ReferenceEqualityComparer<object>.Instance);
/// <summary>
/// Each constant referenced within this lambda, and how often it was referenced
/// </summary>
private readonly Dictionary<TypedConstant, int> _references = new Dictionary<TypedConstant, int>();
/// <summary>
/// IL locals for storing frequently used constants
/// </summary>
private readonly Dictionary<TypedConstant, LocalBuilder> _cache = new Dictionary<TypedConstant, LocalBuilder>();
internal int Count
{
get { return _values.Count; }
}
internal object[] ToArray()
{
return _values.ToArray();
}
/// <summary>
/// Called by VariableBinder. Adds the constant to the list (if needed)
/// and increases the reference count by one
/// </summary>
internal void AddReference(object value, Type type)
{
if (!_indexes.ContainsKey(value))
{
_indexes.Add(value, _values.Count);
_values.Add(value);
}
Helpers.IncrementCount(new TypedConstant(value, type), _references);
}
/// <summary>
/// Emits a live object as a constant
/// </summary>
internal void EmitConstant(LambdaCompiler lc, object value, Type type)
{
Debug.Assert(!ILGen.CanEmitConstant(value, type));
if (!lc.CanEmitBoundConstants)
{
throw Error.CannotCompileConstant(value);
}
LocalBuilder local;
if (_cache.TryGetValue(new TypedConstant(value, type), out local))
{
lc.IL.Emit(OpCodes.Ldloc, local);
return;
}
EmitConstantsArray(lc);
EmitConstantFromArray(lc, value, type);
}
/// <summary>
/// Emit code to cache frequently used constants into IL locals,
/// instead of pulling them out of the array each time
/// </summary>
internal void EmitCacheConstants(LambdaCompiler lc)
{
int count = 0;
foreach (var reference in _references)
{
if (!lc.CanEmitBoundConstants)
{
throw Error.CannotCompileConstant(reference.Key.Value);
}
if (ShouldCache(reference.Value))
{
count++;
}
}
if (count == 0)
{
return;
}
EmitConstantsArray(lc);
// The same lambda can be in multiple places in the tree, so we
// need to clear any locals from last time.
_cache.Clear();
foreach (var reference in _references)
{
if (ShouldCache(reference.Value))
{
if (--count > 0)
{
// Dup array to keep it on the stack
lc.IL.Emit(OpCodes.Dup);
}
LocalBuilder local = lc.IL.DeclareLocal(reference.Key.Type);
EmitConstantFromArray(lc, reference.Key.Value, local.LocalType);
lc.IL.Emit(OpCodes.Stloc, local);
_cache.Add(reference.Key, local);
}
}
}
private static bool ShouldCache(int refCount)
{
// This caching is too aggressive in the face of conditionals and
// switch. Also, it is too conservative for variables used inside
// of loops.
return refCount > 2;
}
private static void EmitConstantsArray(LambdaCompiler lc)
{
Debug.Assert(lc.CanEmitBoundConstants); // this should've been checked already
lc.EmitClosureArgument();
lc.IL.Emit(OpCodes.Ldfld, typeof(Closure).GetField("Constants"));
}
private void EmitConstantFromArray(LambdaCompiler lc, object value, Type type)
{
int index;
if (!_indexes.TryGetValue(value, out index))
{
_indexes.Add(value, index = _values.Count);
_values.Add(value);
}
lc.IL.EmitInt(index);
lc.IL.Emit(OpCodes.Ldelem_Ref);
if (type.GetTypeInfo().IsValueType)
{
lc.IL.Emit(OpCodes.Unbox_Any, type);
}
else if (type != typeof(object))
{
lc.IL.Emit(OpCodes.Castclass, type);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using ChristmasPi.Data.Models;
using ChristmasPi.Data;
using ChristmasPi.Util;
using Serilog;
namespace ChristmasPi.Util {
public class ServiceInstaller : IDisposable {
/*
Installation Process
1. Check if requested service is already installed
Yes: Uninstall service
2. Copy service file to systemd directory
3. Systemd enable service
4. Systemd start service
*/
public delegate void InstallSuccessHandler(ServiceInstallState state);
public delegate void InstallFailureHandler(ServiceInstallState state);
public delegate void InstallProgressHandler(ServiceInstallState state);
// Executed after install succeeded
public InstallSuccessHandler OnInstallSuccess;
// Executed after install failed
public InstallFailureHandler OnInstallFailure;
// Executed after installation has made progress
public InstallProgressHandler OnInstallProgress;
private InstallationStatus status;
private OutputWriter output;
private object locker;
private Thread installerThread;
private string serviceName;
private string servicePath;
private bool isDisposed;
public bool RebootRequired { get; private set;}
// Regexes
private Regex LoadedUnitsRegex = new Regex(@"([0-9]+) loaded units listed\.");
public ServiceInstaller(string service) {
if (!File.Exists(service)) {
throw new FileNotFoundException($"Unable to find {service} in the installation directory, cannot install");
}
status = InstallationStatus.Waiting;
locker = new object();
output = new OutputWriter();
serviceName = Path.GetFileNameWithoutExtension(service);
servicePath = service;
isDisposed = false;
RebootRequired = false;
}
// Starts the installation process with progress reported to Progress
public void StartInstall() {
if (isDisposed || status != InstallationStatus.Waiting) {
Log.ForContext<ServiceInstaller>().Error("Can't start install for service {serviceName}, already ran", serviceName);
Log.ForContext<ServiceInstaller>().Debug("ServiceInstaller status: {status}, disposed? {isDisposed}", status, isDisposed);
throw new Exception("Can't install service, already installed");
}
installerThread = new Thread(installerMonitor);
installerThread.Start();
}
// Safely gets the progress object
public InstallationStatus GetStatus() {
lock (locker) {
return status;
}
}
public OutputWriter GetWriter() {
lock (locker) {
return output;
}
}
protected ServiceInstallState getState() => new ServiceInstallState() { ServiceName = serviceName, Status = status };
private void installerMonitor() {
try {
startInstall();
bool installResult = ConfigurationManager.Instance.RuntimeConfiguration.UseServiceInstallerStub ? installerStub() : installer();
if (installResult) {
Log.ForContext<ServiceInstaller>().Debug("Success");
finishInstall();
OnInstallSuccess.Invoke(getState());
}
else {
Log.ForContext<ServiceInstaller>().Debug("Failure");
failedInstall();
OnInstallFailure.Invoke(getState());
}
}
catch (Exception e) {
writeline("Installer failed with exception {0}", e.Message);
writeline(e.StackTrace);
failedInstall();
OnInstallFailure.Invoke(getState());
}
}
private bool installerStub() {
writeline("Starting installation process");
writeline("Info\t\tname: {0}, path: {1}", this.serviceName, this.servicePath);
writeline("Wrote PID file");
Thread.Sleep(1500);
for (int i = 0; i < 10; i++) {
writeline("Step {0}", i);
Thread.Sleep(750);
}
writeline("Finished installation process");
RebootRequired = true;
writeline("Reboot required");
return true;
}
private bool installer() {
writeline("Starting installation process");
writeline("Info\t\tname: {0}, path: {1}", this.serviceName, this.servicePath);
InitSystem initSystem = OSUtils.GetInitSystemType();
if (initSystem != InitSystem.systemd) {
writeline("Init System {0} is not supported.", initSystem);
RebootRequired = false;
return false;
}
if (isServiceInstalled()) {
writeline("Service already installed, exiting");
return true;
}
writeline("Copying service files");
copyServiceFile();
writeline("Enabling service");
if (!enableService()) {
writeline("Failed to enable service");
return false;
}
writeline("Starting {0} service", this.serviceName);
if (!startService()) {
writeline("Failed to start service");
return false;
}
RebootRequired = true;
return true;
}
private bool isServiceInstalled() {
// systemctl list-units --full -all | grep "cron.service"
/* Success
UNIT LOAD ACTIVE SUB DESCRIPTION
cron.service loaded active running Regular background program processing daemon
LOAD = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB = The low-level unit activation state, values depend on unit type.
1 loaded units listed.
To show all installed unit files use 'systemctl list-unit-files'.
*/
/* Failure
Running command systemctl with list-units --full -all | grep "cron2.service"
0 loaded units listed.
To show all installed unit files use 'systemctl list-unit-files'.
*/
writeline($"systemctl list-units --full -all | grep \"{servicePath}\"");
string output = ProcessRunner.Run("systemctl", $"list-units --full -all | grep \"{servicePath}\"");
writeline(output);
Match outputMatch = LoadedUnitsRegex.Match(output);
if (outputMatch.Success) {
int servicesInstalled = int.Parse(outputMatch.Groups[1].Value);
return servicesInstalled > 0;
}
else
throw new Exception("Unable to get program output");
}
private bool uninstallService() {
// systemctl show -p FragmentPath cron.service
// FragmentPath=/lib/systemd/system/cron.service
// find servicefile
// rm servicefile
// disable service
// daemon reload
throw new NotImplementedException();
}
private void copyServiceFile() {
// copy service file to /etc/systemd/system/
if (File.Exists($"/etc/systemd/system/{servicePath}"))
throw new Exception("Service file already exists, cannot install new service file");
File.Copy(servicePath, $"/etc/systemd/system/{servicePath}");
writeline($"Copying {servicePath}");
}
private bool enableService() {
// systemctl enable service.service
writeline($"systemctl enable {servicePath}");
Process process = ProcessRunner.Popen("systemctl", $"enable {servicePath}");
return process.ExitCode == 0;
}
private bool startService() {
// systemctl start service.service
writeline($"systemctl start {servicePath}");
Process process = ProcessRunner.Popen("systemctl", $"start {servicePath}");
return process.ExitCode == 0;
}
private bool daemonReload() {
// systemctl daemon-reload
writeline("systemctl daemon-reload");
Process process = ProcessRunner.Popen("systemctl", "daemon-reload");
return process.ExitCode == 0;
}
private void startInstall() {
lock (locker) {
status = InstallationStatus.Installing;
}
}
private void failedInstall() {
lock (locker) {
status = InstallationStatus.Failed;
}
}
private void finishInstall() {
lock(locker) {
status = InstallationStatus.Success;
}
}
private void writeline(string format, params object[] args) {
lock (locker) {
output.WriteLine(format, args);
Log.ForContext<ServiceInstaller>().Debug($"\t{String.Format(format, args)}");
OnInstallProgress.Invoke(getState());
}
}
private void writeline(string line) {
lock (locker) {
output.WriteLine(line);
Log.ForContext<ServiceInstaller>().Debug($"\t{line}");
OnInstallProgress.Invoke(getState());
}
}
private void write(string format, params object[] args) {
lock (locker) {
output.Write(format, args);
Log.ForContext<ServiceInstaller>().Debug($"\t{String.Format(format, args)}");
OnInstallProgress.Invoke(getState());
}
}
private void write(string line) {
lock (locker) {
output.Write(line);
Log.ForContext<ServiceInstaller>().Debug($"\t{line}");
OnInstallProgress.Invoke(getState());
}
}
public void Dispose() {
if (!isDisposed) {
isDisposed = true;
OnInstallFailure = null;
OnInstallProgress = null;
OnInstallSuccess = null;
status = InstallationStatus.Success | InstallationStatus.Failed;
output = null;
if (installerThread.IsAlive)
installerThread.Abort();
}
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections.Specialized;
using MindTouch.Data;
using MindTouch.Deki.Data;
using MySql.Data.MySqlClient;
namespace MindTouch.Deki.Data.MySql {
public partial class MySqlDekiDataSession {
private static readonly IDictionary<ServicesSortField, string> SERVICES_SORT_FIELD_MAPPING = new Dictionary<ServicesSortField, string>()
{ { ServicesSortField.DESCRIPTION, "service_description" },
{ ServicesSortField.INIT, "service_local" },
{ ServicesSortField.LOCAL, "service_local" }, // deprecated
{ ServicesSortField.SID, "service_sid" },
{ ServicesSortField.TYPE, "service_type" },
{ ServicesSortField.URI, "service_uri" },
{ ServicesSortField.ID, "service_id"} };
public IList<ServiceBE> Services_GetAll() {
IList<ServiceBE> result = null;
Catalog.NewQuery(@" /* Services_GetAll */
select *
from services;
select *
from service_config;
select *
from service_prefs;")
.Execute(delegate(IDataReader dr) {
result = Services_Populate(dr);
});
return result;
}
public IList<ServiceBE> Services_GetByQuery(string serviceType, SortDirection sortDir, ServicesSortField sortField, uint? offset, uint? limit, out uint totalCount, out uint queryCount) {
IList<ServiceBE> services = null;
uint totalCountTemp = 0;
uint queryCountTemp = 0;
StringBuilder whereQuery = new StringBuilder(" where 1=1");
if(!string.IsNullOrEmpty(serviceType)) {
whereQuery.AppendFormat(" AND service_type = '{0}'", DataCommand.MakeSqlSafe(serviceType));
}
StringBuilder sortLimitQuery = new StringBuilder();
string sortFieldString = null;
//Sort by id if no sort specified.
if(sortField == ServicesSortField.UNDEFINED) {
sortField = ServicesSortField.ID;
}
if(SERVICES_SORT_FIELD_MAPPING.TryGetValue(sortField, out sortFieldString)) {
sortLimitQuery.AppendFormat(" order by {0} ", sortFieldString);
if(sortDir != SortDirection.UNDEFINED) {
sortLimitQuery.Append(sortDir.ToString());
}
}
if(limit != null || offset != null) {
sortLimitQuery.AppendFormat(" limit {0} offset {1}", limit ?? int.MaxValue, offset ?? 0);
}
string query = string.Format(@" /* Services_GetByQuery */
select *
from services
{0}
{1};
select service_config.*
from service_config
join (
select service_id
from services
{0}
{1}
) s on service_config.service_id = s.service_id;
select service_prefs.*
from service_prefs
join (
select service_id
from services
{0}
{1}
) s on service_prefs.service_id = s.service_id;
select count(*) as totalcount from services;
select count(*) as querycount from services {0};
", whereQuery, sortLimitQuery);
Catalog.NewQuery(query)
.Execute(delegate(IDataReader dr) {
services = Services_Populate(dr);
if(dr.NextResult() && dr.Read()) {
totalCountTemp = DbUtils.Convert.To<uint>(dr["totalcount"], 0);
}
if(dr.NextResult() && dr.Read()) {
queryCountTemp = DbUtils.Convert.To<uint>(dr["querycount"], 0);
}
});
totalCount = totalCountTemp;
queryCount = queryCountTemp;
return services == null ? new List<ServiceBE>() : services;
}
public ServiceBE Services_GetById(uint serviceid) {
IList<ServiceBE> result = null;
Catalog.NewQuery(@" /* Services_GetById */
select *
from services
where service_id = ?SERVICEID;
select *
from service_config
where service_id = ?SERVICEID;
select *
from service_prefs
where service_id = ?SERVICEID;")
.With("SERVICEID", serviceid)
.Execute(delegate(IDataReader dr) {
result = Services_Populate(dr);
});
return (result.Count > 0) ? result[0] : null;
}
public void Services_Delete(uint serviceId) {
Catalog.NewQuery(@" /* Services_Delete */
delete from services where service_id = ?ID;
delete from service_prefs where service_id = ?ID;
delete from service_config where service_id = ?ID;"
).With("ID", serviceId)
.Execute();
}
public uint Services_Insert(ServiceBE service) {
StringBuilder query = null;
if(service.Id == 0) {
//new service
query = new StringBuilder(@" /* Services_Insert */
insert into services (service_type, service_sid, service_uri, service_description, service_local, service_enabled, service_last_edit, service_last_status)
values (?TYPE, ?SID, ?URI, ?DESC, ?LOCAL, ?ENABLED, ?TIMESTAMP, ?LASTSTATUS);
");
query.AppendLine("select LAST_INSERT_ID() into @service_id;");
query.AppendLine("select LAST_INSERT_ID() as service_id;");
} else {
//update existing service
query = new StringBuilder(@" /* Services_Insert (with id) */
insert into services (service_id, service_type, service_sid, service_uri, service_description, service_local, service_enabled, service_last_edit, service_last_status)
values (?ID, ?TYPE, ?SID, ?URI, ?DESC, ?LOCAL, ?ENABLED, ?TIMESTAMP, ?LASTSTATUS);
");
query.AppendLine(string.Format("select {0} into @service_id;", service.Id));
query.AppendLine(string.Format("select {0} as service_id;", service.Id));
}
if(service.Preferences != null && service.Preferences.Count > 0) {
query.Append("insert into service_prefs (service_id, pref_name, pref_value) values ");
for(int i = 0; i < service.Preferences.AllKeys.Length; i++) {
string key = DataCommand.MakeSqlSafe(service.Preferences.AllKeys[i]);
string val = DataCommand.MakeSqlSafe(service.Preferences[key]);
query.AppendFormat("{0}(@service_id, '{1}', '{2}')\n", i > 0 ? "," : string.Empty, key, val);
}
query.AppendLine(";");
}
if(service.Config != null && service.Config.Count > 0) {
query.Append("insert into service_config (service_id, config_name, config_value) values ");
for(int i = 0; i < service.Config.AllKeys.Length; i++) {
string key = DataCommand.MakeSqlSafe(service.Config.AllKeys[i]);
string val = DataCommand.MakeSqlSafe(service.Config[key]);
query.AppendFormat("{0}(@service_id, '{1}', '{2}')\n", i > 0 ? "," : string.Empty, key, val);
}
query.AppendLine(";");
}
uint serviceId = 0;
try {
serviceId = Catalog.NewQuery(query.ToString())
.With("ID", service.Id)
.With("TYPE", service.Type.ToString())
.With("SID", service.SID)
.With("URI", service.Uri)
.With("DESC", service.Description)
.With("LOCAL", service.ServiceLocal)
.With("ENABLED", service.ServiceEnabled)
.With("TIMESTAMP", service.ServiceLastEdit)
.With("LASTSTATUS", service.ServiceLastStatus)
.ReadAsUInt() ?? 0;
} catch(MySqlException e) {
// catch Duplicate Key (1062)
if(e.Number == 1062) {
serviceId = service.Id;
} else {
throw;
}
}
return serviceId;
}
private IList<ServiceBE> Services_Populate(IDataReader dr) {
// read all services
List<ServiceBE> orderedServiceList = new List<ServiceBE>();
Dictionary<uint, ServiceBE> result = new Dictionary<uint, ServiceBE>();
ServiceBE s = null;
while(dr.Read()) {
s = new ServiceBE();
s._ServiceEnabled = dr.Read<byte>("service_enabled");
s._ServiceLocal = dr.Read<byte>("service_local");
s.Description = dr.Read<string>("service_description");
s.Id = dr.Read<uint>("service_id");
s.ServiceLastEdit = dr.Read<DateTime>("service_last_edit");
s.ServiceLastStatus = dr.Read<string>("service_last_status");
s.SID = dr.Read<string>("service_sid");
s.Type = dr.Read<ServiceType>("service_type");
s.Uri = dr.Read<string>("service_uri");
result.Add(s.Id, s);
orderedServiceList.Add(s);
}
// read config key/value pairs for each service
dr.NextResult();
while(dr.Read()) {
uint serviceId = DbUtils.Convert.To<uint>(dr["service_id"], 0);
if(serviceId != 0 && result.ContainsKey(serviceId)) {
s = result[serviceId];
string config_name = DbUtils.Convert.To<string>(dr["config_name"], "");
string config_value = DbUtils.Convert.To<string>(dr["config_value"], "");
s.Config[config_name] = config_value;
}
}
// read preference key/value pairs for each service
dr.NextResult();
while(dr.Read()) {
uint serviceId = DbUtils.Convert.To<uint>(dr["service_id"], 0);
if(serviceId != 0 && result.ContainsKey(serviceId)) {
s = result[serviceId];
string pref_name = DbUtils.Convert.To<string>(dr["pref_name"], "");
string pref_value = DbUtils.Convert.To<string>(dr["pref_value"], "");
s.Preferences[pref_name] = pref_value;
}
}
return orderedServiceList;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
#if CAP_TypeOfPointer
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess01.arrayaccess01
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess01.arrayaccess01;
// <Area> dynamic in unsafe code </Area>
// <Title>pointer operator</Title>
// <Description>
// member access
// </Description>
// <RelatedBug>564384</RelatedBug>
//<Expects Status=success></Expects>
// <Code>
[TestClass]
unsafe public class Test
{
[Test]
[Priority(Priority.Priority0)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); }
public static int MainMethod(string[] args)
{
int* ptr = stackalloc int[10];
for (int i = 0; i < 10; i++)
{
*(ptr + i) = i;
}
dynamic d = 5;
int x = ptr[d];
if (x != 5) return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess02.arrayaccess02
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess02.arrayaccess02;
// <Area> dynamic with pointer indexer </Area>
// <Title>pointer operator</Title>
// <Description>
// member access
// </Description>
// <RelatedBug></RelatedBug>
//<Expects Status=success></Expects>
// <Code>
[TestClass]
unsafe public class Test
{
[Test]
[Priority(Priority.Priority0)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); }
public static int MainMethod(string[] args)
{
int* ptr = stackalloc int[10];
for (int i = 0; i < 10; i++)
{
*(ptr + i) = i;
}
int test = 0, success = 0;
dynamic d;
int x;
test++;
d = (uint)5;
x = ptr[d];
if (x == 5) success++;
test++;
d = (ulong)5;
x = ptr[d];
if (x == 5) success++;
test++;
d = (long)5;
x = ptr[d];
if (x == 5) success++;
return test == success ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.sizeof01.sizeof01
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.sizeof01.sizeof01;
// <Area> dynamic in unsafe code </Area>
// <Title>pointer operator</Title>
// <Description>
// sizeof operator
// </Description>
// <RelatedBug></RelatedBug>
//<Expects Status=success></Expects>
// <Code>
[TestClass]
unsafe public class Test
{
[Test]
[Priority(Priority.Priority1)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); }
public static int MainMethod(string[] args)
{
dynamic d = sizeof(int);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.stackalloc01.stackalloc01
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.stackalloc01.stackalloc01;
// <Area> dynamic in unsafe code </Area>
// <Title>pointer operator</Title>
// <Description>
// stackalloc
// </Description>
// <RelatedBug></RelatedBug>
//<Expects Status=success></Expects>
// <Code>
[TestClass]
unsafe public class Test
{
[Test]
[Priority(Priority.Priority1)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); }
public static int MainMethod(string[] args)
{
dynamic d = 10;
int* ptr = stackalloc int[d];
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.pointegeregerertype01.pointegeregerertype01
{
using ManagedTests.DynamicCSharp.Test;
using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.pointegeregerertype01.pointegeregerertype01;
// <Area> dynamic in unsafe code </Area>
// <Title>Regression</Title>
// <Description>
// VerificationException thrown when dynamically dispatching a method call with out/ref arguments which are pointer types
// </Description>
// <RelatedBug></RelatedBug>
// <Expects Status=success></Expects>
// <Code>
using System;
using System.Security;
[TestClass]
public class TestClass
{
public unsafe void Method(out int* arg)
{
arg = (int*)5;
}
}
struct Driver
{
[Test]
[Priority(Priority.Priority2)]
public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod()); }
public static unsafe int MainMethod()
{
int* ptr = null;
dynamic tc = new TestClass();
try
{
tc.Method(out ptr);
}
catch (VerificationException e)
{
return 0; //this was won't fix
}
return 1;
}
}
// </Code>
}
#endif
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
public enum ProfileShape : byte
{
Circle = 0,
Square = 1,
IsometricTriangle = 2,
EquilateralTriangle = 3,
RightTriangle = 4,
HalfCircle = 5
}
public enum HollowShape : byte
{
Same = 0,
Circle = 16,
Square = 32,
Triangle = 48
}
public enum PCodeEnum : byte
{
Primitive = 9,
Avatar = 47,
Grass = 95,
NewTree = 111,
ParticleSystem = 143,
Tree = 255
}
public enum Extrusion : byte
{
Straight = 16,
Curve1 = 32,
Curve2 = 48,
Flexible = 128
}
[Serializable]
public class PrimitiveBaseShape
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly byte[] DEFAULT_TEXTURE = new Primitive.TextureEntry(new UUID("89556747-24cb-43ed-920b-47caed15465f")).GetBytes();
private byte[] m_textureEntry;
private ushort _pathBegin;
private byte _pathCurve;
private ushort _pathEnd;
private sbyte _pathRadiusOffset;
private byte _pathRevolutions;
private byte _pathScaleX;
private byte _pathScaleY;
private byte _pathShearX;
private byte _pathShearY;
private sbyte _pathSkew;
private sbyte _pathTaperX;
private sbyte _pathTaperY;
private sbyte _pathTwist;
private sbyte _pathTwistBegin;
private byte _pCode;
private ushort _profileBegin;
private ushort _profileEnd;
private ushort _profileHollow;
private Vector3 _scale;
private byte _state;
private byte _lastattach;
private ProfileShape _profileShape;
private HollowShape _hollowShape;
// Sculpted
[XmlIgnore] private UUID _sculptTexture;
[XmlIgnore] private byte _sculptType;
[XmlIgnore] private byte[] _sculptData = Utils.EmptyBytes;
// Flexi
[XmlIgnore] private int _flexiSoftness;
[XmlIgnore] private float _flexiTension;
[XmlIgnore] private float _flexiDrag;
[XmlIgnore] private float _flexiGravity;
[XmlIgnore] private float _flexiWind;
[XmlIgnore] private float _flexiForceX;
[XmlIgnore] private float _flexiForceY;
[XmlIgnore] private float _flexiForceZ;
//Bright n sparkly
[XmlIgnore] private float _lightColorR;
[XmlIgnore] private float _lightColorG;
[XmlIgnore] private float _lightColorB;
[XmlIgnore] private float _lightColorA = 1.0f;
[XmlIgnore] private float _lightRadius;
[XmlIgnore] private float _lightCutoff;
[XmlIgnore] private float _lightFalloff;
[XmlIgnore] private float _lightIntensity = 1.0f;
[XmlIgnore] private bool _flexiEntry;
[XmlIgnore] private bool _lightEntry;
[XmlIgnore] private bool _sculptEntry;
// Light Projection Filter
[XmlIgnore] private bool _projectionEntry;
[XmlIgnore] private UUID _projectionTextureID;
[XmlIgnore] private float _projectionFOV;
[XmlIgnore] private float _projectionFocus;
[XmlIgnore] private float _projectionAmb;
public byte ProfileCurve
{
get { return (byte)((byte)HollowShape | (byte)ProfileShape); }
set
{
// Handle hollow shape component
byte hollowShapeByte = (byte)(value & 0xf0);
if (!Enum.IsDefined(typeof(HollowShape), hollowShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.",
hollowShapeByte);
this._hollowShape = HollowShape.Same;
}
else
{
this._hollowShape = (HollowShape)hollowShapeByte;
}
// Handle profile shape component
byte profileShapeByte = (byte)(value & 0xf);
if (!Enum.IsDefined(typeof(ProfileShape), profileShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.",
profileShapeByte);
this._profileShape = ProfileShape.Square;
}
else
{
this._profileShape = (ProfileShape)profileShapeByte;
}
}
}
/// <summary>
/// Entries to store media textures on each face
/// </summary>
/// Do not change this value directly - always do it through an IMoapModule.
/// Lock before manipulating.
public MediaList Media { get; set; }
public PrimitiveBaseShape()
{
PCode = (byte)PCodeEnum.Primitive;
m_textureEntry = DEFAULT_TEXTURE;
}
/// <summary>
/// Construct a PrimitiveBaseShape object from a OpenMetaverse.Primitive object
/// </summary>
/// <param name="prim"></param>
public PrimitiveBaseShape(Primitive prim)
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Creating from {0}", prim.ID);
PCode = (byte)prim.PrimData.PCode;
State = prim.PrimData.State;
LastAttachPoint = prim.PrimData.State;
PathBegin = Primitive.PackBeginCut(prim.PrimData.PathBegin);
PathEnd = Primitive.PackEndCut(prim.PrimData.PathEnd);
PathScaleX = Primitive.PackPathScale(prim.PrimData.PathScaleX);
PathScaleY = Primitive.PackPathScale(prim.PrimData.PathScaleY);
PathShearX = (byte)Primitive.PackPathShear(prim.PrimData.PathShearX);
PathShearY = (byte)Primitive.PackPathShear(prim.PrimData.PathShearY);
PathSkew = Primitive.PackPathTwist(prim.PrimData.PathSkew);
ProfileBegin = Primitive.PackBeginCut(prim.PrimData.ProfileBegin);
ProfileEnd = Primitive.PackEndCut(prim.PrimData.ProfileEnd);
Scale = prim.Scale;
PathCurve = (byte)prim.PrimData.PathCurve;
ProfileCurve = (byte)prim.PrimData.ProfileCurve;
ProfileHollow = Primitive.PackProfileHollow(prim.PrimData.ProfileHollow);
PathRadiusOffset = Primitive.PackPathTwist(prim.PrimData.PathRadiusOffset);
PathRevolutions = Primitive.PackPathRevolutions(prim.PrimData.PathRevolutions);
PathTaperX = Primitive.PackPathTaper(prim.PrimData.PathTaperX);
PathTaperY = Primitive.PackPathTaper(prim.PrimData.PathTaperY);
PathTwist = Primitive.PackPathTwist(prim.PrimData.PathTwist);
PathTwistBegin = Primitive.PackPathTwist(prim.PrimData.PathTwistBegin);
m_textureEntry = prim.Textures.GetBytes();
if (prim.Sculpt != null)
{
SculptEntry = (prim.Sculpt.Type != OpenMetaverse.SculptType.None);
SculptData = prim.Sculpt.GetBytes();
SculptTexture = prim.Sculpt.SculptTexture;
SculptType = (byte)prim.Sculpt.Type;
}
else
{
SculptType = (byte)OpenMetaverse.SculptType.None;
}
}
[XmlIgnore]
public Primitive.TextureEntry Textures
{
get
{
// m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length);
try { return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length); }
catch { }
m_log.Warn("[SHAPE]: Failed to decode texture, length=" + ((m_textureEntry != null) ? m_textureEntry.Length : 0));
return new Primitive.TextureEntry(UUID.Zero);
}
set { m_textureEntry = value.GetBytes(); }
}
public byte[] TextureEntry
{
get { return m_textureEntry; }
set
{
if (value == null)
m_textureEntry = new byte[1];
else
m_textureEntry = value;
}
}
public static PrimitiveBaseShape Default
{
get
{
PrimitiveBaseShape boxShape = CreateBox();
boxShape.SetScale(0.5f);
return boxShape;
}
}
public static PrimitiveBaseShape Create()
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
return shape;
}
public static PrimitiveBaseShape CreateBox()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Straight;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateSphere()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.HalfCircle;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateCylinder()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public void SetScale(float side)
{
_scale = new Vector3(side, side, side);
}
public void SetHeigth(float height)
{
_scale.Z = height;
}
public void SetRadius(float radius)
{
_scale.X = _scale.Y = radius * 2f;
}
// TODO: void returns need to change of course
public virtual void GetMesh()
{
}
public PrimitiveBaseShape Copy()
{
return (PrimitiveBaseShape) MemberwiseClone();
}
public static PrimitiveBaseShape CreateCylinder(float radius, float heigth)
{
PrimitiveBaseShape shape = CreateCylinder();
shape.SetHeigth(heigth);
shape.SetRadius(radius);
return shape;
}
public void SetPathRange(Vector3 pathRange)
{
_pathBegin = Primitive.PackBeginCut(pathRange.X);
_pathEnd = Primitive.PackEndCut(pathRange.Y);
}
public void SetPathRange(float begin, float end)
{
_pathBegin = Primitive.PackBeginCut(begin);
_pathEnd = Primitive.PackEndCut(end);
}
public void SetSculptProperties(byte sculptType, UUID SculptTextureUUID)
{
_sculptType = sculptType;
_sculptTexture = SculptTextureUUID;
}
public void SetProfileRange(Vector3 profileRange)
{
_profileBegin = Primitive.PackBeginCut(profileRange.X);
_profileEnd = Primitive.PackEndCut(profileRange.Y);
}
public void SetProfileRange(float begin, float end)
{
_profileBegin = Primitive.PackBeginCut(begin);
_profileEnd = Primitive.PackEndCut(end);
}
public byte[] ExtraParams
{
get
{
return ExtraParamsToBytes();
}
set
{
ReadInExtraParamsBytes(value);
}
}
public ushort PathBegin {
get {
return _pathBegin;
}
set {
_pathBegin = value;
}
}
public byte PathCurve {
get {
return _pathCurve;
}
set {
_pathCurve = value;
}
}
public ushort PathEnd {
get {
return _pathEnd;
}
set {
_pathEnd = value;
}
}
public sbyte PathRadiusOffset {
get {
return _pathRadiusOffset;
}
set {
_pathRadiusOffset = value;
}
}
public byte PathRevolutions {
get {
return _pathRevolutions;
}
set {
_pathRevolutions = value;
}
}
public byte PathScaleX {
get {
return _pathScaleX;
}
set {
_pathScaleX = value;
}
}
public byte PathScaleY {
get {
return _pathScaleY;
}
set {
_pathScaleY = value;
}
}
public byte PathShearX {
get {
return _pathShearX;
}
set {
_pathShearX = value;
}
}
public byte PathShearY {
get {
return _pathShearY;
}
set {
_pathShearY = value;
}
}
public sbyte PathSkew {
get {
return _pathSkew;
}
set {
_pathSkew = value;
}
}
public sbyte PathTaperX {
get {
return _pathTaperX;
}
set {
_pathTaperX = value;
}
}
public sbyte PathTaperY {
get {
return _pathTaperY;
}
set {
_pathTaperY = value;
}
}
public sbyte PathTwist {
get {
return _pathTwist;
}
set {
_pathTwist = value;
}
}
public sbyte PathTwistBegin {
get {
return _pathTwistBegin;
}
set {
_pathTwistBegin = value;
}
}
public byte PCode {
get {
return _pCode;
}
set {
_pCode = value;
}
}
public ushort ProfileBegin {
get {
return _profileBegin;
}
set {
_profileBegin = value;
}
}
public ushort ProfileEnd {
get {
return _profileEnd;
}
set {
_profileEnd = value;
}
}
public ushort ProfileHollow {
get {
return _profileHollow;
}
set {
_profileHollow = value;
}
}
public Vector3 Scale {
get {
return _scale;
}
set {
_scale = value;
}
}
public byte State {
get {
return _state;
}
set {
_state = value;
}
}
public byte LastAttachPoint {
get {
return _lastattach;
}
set {
_lastattach = value;
}
}
public ProfileShape ProfileShape {
get {
return _profileShape;
}
set {
_profileShape = value;
}
}
public HollowShape HollowShape {
get {
return _hollowShape;
}
set {
_hollowShape = value;
}
}
public UUID SculptTexture {
get {
return _sculptTexture;
}
set {
_sculptTexture = value;
}
}
public byte SculptType
{
get
{
return _sculptType;
}
set
{
_sculptType = value;
}
}
// This is only used at runtime. For sculpties this holds the texture data, and for meshes
// the mesh data.
public byte[] SculptData
{
get
{
return _sculptData;
}
set
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Setting SculptData to data with length {0}", value.Length);
_sculptData = value;
}
}
public int FlexiSoftness
{
get
{
return _flexiSoftness;
}
set
{
_flexiSoftness = value;
}
}
public float FlexiTension {
get {
return _flexiTension;
}
set {
_flexiTension = value;
}
}
public float FlexiDrag {
get {
return _flexiDrag;
}
set {
_flexiDrag = value;
}
}
public float FlexiGravity {
get {
return _flexiGravity;
}
set {
_flexiGravity = value;
}
}
public float FlexiWind {
get {
return _flexiWind;
}
set {
_flexiWind = value;
}
}
public float FlexiForceX {
get {
return _flexiForceX;
}
set {
_flexiForceX = value;
}
}
public float FlexiForceY {
get {
return _flexiForceY;
}
set {
_flexiForceY = value;
}
}
public float FlexiForceZ {
get {
return _flexiForceZ;
}
set {
_flexiForceZ = value;
}
}
public float LightColorR {
get {
return _lightColorR;
}
set {
_lightColorR = value;
}
}
public float LightColorG {
get {
return _lightColorG;
}
set {
_lightColorG = value;
}
}
public float LightColorB {
get {
return _lightColorB;
}
set {
_lightColorB = value;
}
}
public float LightColorA {
get {
return _lightColorA;
}
set {
_lightColorA = value;
}
}
public float LightRadius {
get {
return _lightRadius;
}
set {
_lightRadius = value;
}
}
public float LightCutoff {
get {
return _lightCutoff;
}
set {
_lightCutoff = value;
}
}
public float LightFalloff {
get {
return _lightFalloff;
}
set {
_lightFalloff = value;
}
}
public float LightIntensity {
get {
return _lightIntensity;
}
set {
_lightIntensity = value;
}
}
public bool FlexiEntry {
get {
return _flexiEntry;
}
set {
_flexiEntry = value;
}
}
public bool LightEntry {
get {
return _lightEntry;
}
set {
_lightEntry = value;
}
}
public bool SculptEntry {
get {
return _sculptEntry;
}
set {
_sculptEntry = value;
}
}
public bool ProjectionEntry {
get {
return _projectionEntry;
}
set {
_projectionEntry = value;
}
}
public UUID ProjectionTextureUUID {
get {
return _projectionTextureID;
}
set {
_projectionTextureID = value;
}
}
public float ProjectionFOV {
get {
return _projectionFOV;
}
set {
_projectionFOV = value;
}
}
public float ProjectionFocus {
get {
return _projectionFocus;
}
set {
_projectionFocus = value;
}
}
public float ProjectionAmbiance {
get {
return _projectionAmb;
}
set {
_projectionAmb = value;
}
}
public ulong GetMeshKey(Vector3 size, float lod)
{
ulong hash = 5381;
hash = djb2(hash, this.PathCurve);
hash = djb2(hash, (byte)((byte)this.HollowShape | (byte)this.ProfileShape));
hash = djb2(hash, this.PathBegin);
hash = djb2(hash, this.PathEnd);
hash = djb2(hash, this.PathScaleX);
hash = djb2(hash, this.PathScaleY);
hash = djb2(hash, this.PathShearX);
hash = djb2(hash, this.PathShearY);
hash = djb2(hash, (byte)this.PathTwist);
hash = djb2(hash, (byte)this.PathTwistBegin);
hash = djb2(hash, (byte)this.PathRadiusOffset);
hash = djb2(hash, (byte)this.PathTaperX);
hash = djb2(hash, (byte)this.PathTaperY);
hash = djb2(hash, this.PathRevolutions);
hash = djb2(hash, (byte)this.PathSkew);
hash = djb2(hash, this.ProfileBegin);
hash = djb2(hash, this.ProfileEnd);
hash = djb2(hash, this.ProfileHollow);
// TODO: Separate scale out from the primitive shape data (after
// scaling is supported at the physics engine level)
byte[] scaleBytes = size.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
// Include LOD in hash, accounting for endianness
byte[] lodBytes = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lodBytes, 0, 4);
}
for (int i = 0; i < lodBytes.Length; i++)
hash = djb2(hash, lodBytes[i]);
// include sculpt UUID
if (this.SculptEntry)
{
scaleBytes = this.SculptTexture.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
}
return hash;
}
private ulong djb2(ulong hash, byte c)
{
return ((hash << 5) + hash) + (ulong)c;
}
private ulong djb2(ulong hash, ushort c)
{
hash = ((hash << 5) + hash) + (ulong)((byte)c);
return ((hash << 5) + hash) + (ulong)(c >> 8);
}
public byte[] ExtraParamsToBytes()
{
// m_log.DebugFormat("[EXTRAPARAMS]: Called ExtraParamsToBytes()");
ushort FlexiEP = 0x10;
ushort LightEP = 0x20;
ushort SculptEP = 0x30;
ushort ProjectionEP = 0x40;
int i = 0;
uint TotalBytesLength = 1; // ExtraParamsNum
uint ExtraParamsNum = 0;
if (_flexiEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_lightEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_sculptEntry)
{
ExtraParamsNum++;
TotalBytesLength += 17;// data
TotalBytesLength += 2 + 4; // type
}
if (_projectionEntry)
{
ExtraParamsNum++;
TotalBytesLength += 28;// data
TotalBytesLength += 2 + 4;// type
}
byte[] returnbytes = new byte[TotalBytesLength];
// uint paramlength = ExtraParamsNum;
// Stick in the number of parameters
returnbytes[i++] = (byte)ExtraParamsNum;
if (_flexiEntry)
{
byte[] FlexiData = GetFlexiBytes();
returnbytes[i++] = (byte)(FlexiEP % 256);
returnbytes[i++] = (byte)((FlexiEP >> 8) % 256);
returnbytes[i++] = (byte)(FlexiData.Length % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 8) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 16) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 24) % 256);
Array.Copy(FlexiData, 0, returnbytes, i, FlexiData.Length);
i += FlexiData.Length;
}
if (_lightEntry)
{
byte[] LightData = GetLightBytes();
returnbytes[i++] = (byte)(LightEP % 256);
returnbytes[i++] = (byte)((LightEP >> 8) % 256);
returnbytes[i++] = (byte)(LightData.Length % 256);
returnbytes[i++] = (byte)((LightData.Length >> 8) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 16) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 24) % 256);
Array.Copy(LightData, 0, returnbytes, i, LightData.Length);
i += LightData.Length;
}
if (_sculptEntry)
{
byte[] SculptData = GetSculptBytes();
returnbytes[i++] = (byte)(SculptEP % 256);
returnbytes[i++] = (byte)((SculptEP >> 8) % 256);
returnbytes[i++] = (byte)(SculptData.Length % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 8) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 16) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 24) % 256);
Array.Copy(SculptData, 0, returnbytes, i, SculptData.Length);
i += SculptData.Length;
}
if (_projectionEntry)
{
byte[] ProjectionData = GetProjectionBytes();
returnbytes[i++] = (byte)(ProjectionEP % 256);
returnbytes[i++] = (byte)((ProjectionEP >> 8) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 16) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 20) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 24) % 256);
Array.Copy(ProjectionData, 0, returnbytes, i, ProjectionData.Length);
i += ProjectionData.Length;
}
if (!_flexiEntry && !_lightEntry && !_sculptEntry && !_projectionEntry)
{
byte[] returnbyte = new byte[1];
returnbyte[0] = 0;
return returnbyte;
}
return returnbytes;
}
public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data)
{
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
switch (type)
{
case FlexiEP:
if (!inUse)
{
_flexiEntry = false;
return;
}
ReadFlexiData(data, 0);
break;
case LightEP:
if (!inUse)
{
_lightEntry = false;
return;
}
ReadLightData(data, 0);
break;
case SculptEP:
if (!inUse)
{
_sculptEntry = false;
return;
}
ReadSculptData(data, 0);
break;
case ProjectionEP:
if (!inUse)
{
_projectionEntry = false;
return;
}
ReadProjectionData(data, 0);
break;
}
}
public void ReadInExtraParamsBytes(byte[] data)
{
if (data == null || data.Length == 1)
return;
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
bool lGotFlexi = false;
bool lGotLight = false;
bool lGotSculpt = false;
bool lGotFilter = false;
int i = 0;
byte extraParamCount = 0;
if (data.Length > 0)
{
extraParamCount = data[i++];
}
for (int k = 0; k < extraParamCount; k++)
{
ushort epType = Utils.BytesToUInt16(data, i);
i += 2;
// uint paramLength = Helpers.BytesToUIntBig(data, i);
i += 4;
switch (epType)
{
case FlexiEP:
ReadFlexiData(data, i);
i += 16;
lGotFlexi = true;
break;
case LightEP:
ReadLightData(data, i);
i += 16;
lGotLight = true;
break;
case SculptEP:
ReadSculptData(data, i);
i += 17;
lGotSculpt = true;
break;
case ProjectionEP:
ReadProjectionData(data, i);
i += 28;
lGotFilter = true;
break;
}
}
if (!lGotFlexi)
_flexiEntry = false;
if (!lGotLight)
_lightEntry = false;
if (!lGotSculpt)
_sculptEntry = false;
if (!lGotFilter)
_projectionEntry = false;
}
public void ReadSculptData(byte[] data, int pos)
{
UUID SculptUUID;
byte SculptTypel;
if (data.Length-pos >= 17)
{
_sculptEntry = true;
byte[] SculptTextureUUID = new byte[16];
SculptTypel = data[16 + pos];
Array.Copy(data, pos, SculptTextureUUID,0, 16);
SculptUUID = new UUID(SculptTextureUUID, 0);
}
else
{
_sculptEntry = false;
SculptUUID = UUID.Zero;
SculptTypel = 0x00;
}
if (_sculptEntry)
{
if (_sculptType != (byte)1 && _sculptType != (byte)2 && _sculptType != (byte)3 && _sculptType != (byte)4)
_sculptType = 4;
}
_sculptTexture = SculptUUID;
_sculptType = SculptTypel;
//m_log.Info("[SCULPT]:" + SculptUUID.ToString());
}
public byte[] GetSculptBytes()
{
byte[] data = new byte[17];
_sculptTexture.GetBytes().CopyTo(data, 0);
data[16] = (byte)_sculptType;
return data;
}
public void ReadFlexiData(byte[] data, int pos)
{
if (data.Length-pos >= 16)
{
_flexiEntry = true;
_flexiSoftness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
_flexiTension = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiDrag = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiGravity = (float)(data[pos++] / 10.0f) - 10.0f;
_flexiWind = (float)data[pos++] / 10.0f;
Vector3 lForce = new Vector3(data, pos);
_flexiForceX = lForce.X;
_flexiForceY = lForce.Y;
_flexiForceZ = lForce.Z;
}
else
{
_flexiEntry = false;
_flexiSoftness = 0;
_flexiTension = 0.0f;
_flexiDrag = 0.0f;
_flexiGravity = 0.0f;
_flexiWind = 0.0f;
_flexiForceX = 0f;
_flexiForceY = 0f;
_flexiForceZ = 0f;
}
}
public byte[] GetFlexiBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((_flexiSoftness & 2) << 6);
data[i + 1] = (byte)((_flexiSoftness & 1) << 7);
data[i++] |= (byte)((byte)(_flexiTension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(_flexiDrag * 10.01f) & 0x7F);
data[i++] = (byte)((_flexiGravity + 10.0f) * 10.01f);
data[i++] = (byte)(_flexiWind * 10.01f);
Vector3 lForce = new Vector3(_flexiForceX, _flexiForceY, _flexiForceZ);
lForce.GetBytes().CopyTo(data, i);
return data;
}
public void ReadLightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
_lightEntry = true;
Color4 lColor = new Color4(data, pos, false);
_lightIntensity = lColor.A;
_lightColorA = 1f;
_lightColorR = lColor.R;
_lightColorG = lColor.G;
_lightColorB = lColor.B;
_lightRadius = Utils.BytesToFloat(data, pos + 4);
_lightCutoff = Utils.BytesToFloat(data, pos + 8);
_lightFalloff = Utils.BytesToFloat(data, pos + 12);
}
else
{
_lightEntry = false;
_lightColorA = 1f;
_lightColorR = 0f;
_lightColorG = 0f;
_lightColorB = 0f;
_lightRadius = 0f;
_lightCutoff = 0f;
_lightFalloff = 0f;
_lightIntensity = 0f;
}
}
public byte[] GetLightBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
Color4 tmpColor = new Color4(_lightColorR,_lightColorG,_lightColorB,_lightIntensity);
tmpColor.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_lightRadius).CopyTo(data, 4);
Utils.FloatToBytes(_lightCutoff).CopyTo(data, 8);
Utils.FloatToBytes(_lightFalloff).CopyTo(data, 12);
return data;
}
public void ReadProjectionData(byte[] data, int pos)
{
byte[] ProjectionTextureUUID = new byte[16];
if (data.Length - pos >= 28)
{
_projectionEntry = true;
Array.Copy(data, pos, ProjectionTextureUUID,0, 16);
_projectionTextureID = new UUID(ProjectionTextureUUID, 0);
_projectionFOV = Utils.BytesToFloat(data, pos + 16);
_projectionFocus = Utils.BytesToFloat(data, pos + 20);
_projectionAmb = Utils.BytesToFloat(data, pos + 24);
}
else
{
_projectionEntry = false;
_projectionTextureID = UUID.Zero;
_projectionFOV = 0f;
_projectionFocus = 0f;
_projectionAmb = 0f;
}
}
public byte[] GetProjectionBytes()
{
byte[] data = new byte[28];
_projectionTextureID.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_projectionFOV).CopyTo(data, 16);
Utils.FloatToBytes(_projectionFocus).CopyTo(data, 20);
Utils.FloatToBytes(_projectionAmb).CopyTo(data, 24);
return data;
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <returns></returns>
public Primitive ToOmvPrimitive()
{
// position and rotation defaults here since they are not available in PrimitiveBaseShape
return ToOmvPrimitive(new Vector3(0.0f, 0.0f, 0.0f),
new Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <param name="position"></param>
/// <param name="rotation"></param>
/// <returns></returns>
public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation)
{
OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive();
prim.Scale = this.Scale;
prim.Position = position;
prim.Rotation = rotation;
if (this.SculptEntry)
{
prim.Sculpt = new Primitive.SculptData();
prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType;
prim.Sculpt.SculptTexture = this.SculptTexture;
}
prim.PrimData.PathShearX = this.PathShearX < 128 ? (float)this.PathShearX * 0.01f : (float)(this.PathShearX - 256) * 0.01f;
prim.PrimData.PathShearY = this.PathShearY < 128 ? (float)this.PathShearY * 0.01f : (float)(this.PathShearY - 256) * 0.01f;
prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f;
prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f;
prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f;
prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f;
prim.PrimData.PathTaperX = this.PathTaperX * 0.01f;
prim.PrimData.PathTaperY = this.PathTaperY * 0.01f;
prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f;
prim.PrimData.PathTwist = this.PathTwist * 0.01f;
prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f;
prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f;
prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f;
prim.PrimData.profileCurve = this.ProfileCurve;
prim.PrimData.ProfileHole = (HoleType)this.HollowShape;
prim.PrimData.PathCurve = (PathCurve)this.PathCurve;
prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset;
prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions;
prim.PrimData.PathSkew = 0.01f * this.PathSkew;
prim.PrimData.PCode = OpenMetaverse.PCode.Prim;
prim.PrimData.State = 0;
if (this.FlexiEntry)
{
prim.Flexible = new Primitive.FlexibleData();
prim.Flexible.Drag = this.FlexiDrag;
prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ);
prim.Flexible.Gravity = this.FlexiGravity;
prim.Flexible.Softness = this.FlexiSoftness;
prim.Flexible.Tension = this.FlexiTension;
prim.Flexible.Wind = this.FlexiWind;
}
if (this.LightEntry)
{
prim.Light = new Primitive.LightData();
prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA);
prim.Light.Cutoff = this.LightCutoff;
prim.Light.Falloff = this.LightFalloff;
prim.Light.Intensity = this.LightIntensity;
prim.Light.Radius = this.LightRadius;
}
prim.Textures = this.Textures;
prim.Properties = new Primitive.ObjectProperties();
prim.Properties.Name = "Primitive";
prim.Properties.Description = "";
prim.Properties.CreatorID = UUID.Zero;
prim.Properties.GroupID = UUID.Zero;
prim.Properties.OwnerID = UUID.Zero;
prim.Properties.Permissions = new Permissions();
prim.Properties.SalePrice = 10;
prim.Properties.SaleType = new SaleType();
return prim;
}
/// <summary>
/// Encapsulates a list of media entries.
/// </summary>
/// This class is necessary because we want to replace auto-serialization of MediaEntry with something more
/// OSD like and less vulnerable to change.
public class MediaList : List<MediaEntry>, IXmlSerializable
{
public const string MEDIA_TEXTURE_TYPE = "sl";
public MediaList() : base() {}
public MediaList(IEnumerable<MediaEntry> collection) : base(collection) {}
public MediaList(int capacity) : base(capacity) {}
public XmlSchema GetSchema()
{
return null;
}
public string ToXml()
{
lock (this)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
xtw.WriteStartElement("OSMedia");
xtw.WriteAttributeString("type", MEDIA_TEXTURE_TYPE);
xtw.WriteAttributeString("version", "0.1");
OSDArray meArray = new OSDArray();
foreach (MediaEntry me in this)
{
OSD osd = (null == me ? new OSD() : me.GetOSD());
meArray.Add(osd);
}
xtw.WriteStartElement("OSData");
xtw.WriteRaw(OSDParser.SerializeLLSDXmlString(meArray));
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.Flush();
return sw.ToString();
}
}
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteRaw(ToXml());
}
public static MediaList FromXml(string rawXml)
{
MediaList ml = new MediaList();
ml.ReadXml(rawXml);
return ml;
}
public void ReadXml(string rawXml)
{
using (StringReader sr = new StringReader(rawXml))
{
using (XmlTextReader xtr = new XmlTextReader(sr))
{
xtr.MoveToContent();
string type = xtr.GetAttribute("type");
//m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type);
if (type != MEDIA_TEXTURE_TYPE)
return;
xtr.ReadStartElement("OSMedia");
OSDArray osdMeArray = (OSDArray)OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
foreach (OSD osdMe in osdMeArray)
{
MediaEntry me = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
Add(me);
}
xtr.ReadEndElement();
}
}
}
public void ReadXml(XmlReader reader)
{
if (reader.IsEmptyElement)
return;
ReadXml(reader.ReadInnerXml());
}
}
}
}
| |
using System;
using System.ComponentModel;
using GuruComponents.Netrix.UserInterface;
namespace GuruComponents.Netrix.XmlDesigner
{
/// <summary>
/// Modifies the descriptor content populated to propertygrid for Edx access.
/// </summary>
/// <remarks>
/// This overwrites the default property names and enhances the standard attributes with the DisplayNameAttribute.
/// </remarks>
public class EdxPropertyDescriptor : PropertyDescriptor
{
private PropertyDescriptor baseProp;
/// <summary>
/// The constructor called on first access to the property from any designer.
/// </summary>
/// <remarks>
/// This class should not being instantiated directly. It supports the NetRix infrastructure
/// and external designers, like VS.NET or the propertygrid.
/// </remarks>
/// <param name="pd">The descriptor for which the properties beeing requested.</param>
/// <param name="filter">The filter which controls the properties not beeing shown.</param>
public EdxPropertyDescriptor(PropertyDescriptor pd, Attribute[] filter)
: base(pd)
{
baseProp = pd;
}
/// <summary>
/// Ctor with base descriptor.
/// </summary>
public EdxPropertyDescriptor(PropertyDescriptor pd)
: base(pd)
{
baseProp = pd;
}
/// <summary>
/// Makes the decsriptor localizable.
/// </summary>
/// <remarks>
/// This property is overwritten to return always <c>true</c>.
/// </remarks>
public override bool IsLocalizable
{
get
{
return true;
}
}
/// <summary>
/// Retrieve the resource string from localization assembly.
/// </summary>
/// <remarks>
/// The resource strings must follow
/// the pattern "Type.Attribute", e.g. "Category.Class".
/// </remarks>
/// <param name="Type">Type, such as "Attribute", "Category"</param>
/// <param name="Element">Attribute name for the given type</param>
/// <returns>String with the localized name</returns>
private static string GetResource(string Type, string Element)
{
string getter = String.Concat(Type, ".", Element);
string r = ResourceManager.GetString(getter);
if (r == null)
{
return Element;
}
else
{
return r;
}
}
/// <summary>
/// Indicates the category that the property will appear in.
/// </summary>
/// <remarks>
/// The value will be the value given for the CategoryAttribute
/// attribute for the property, if one exists. If there is no CategoryAttribute, then this will be DefaultCategoryName.
/// </remarks>
public override string Category
{
get
{
AttributeCollection atts = baseProp.Attributes;
if (atts.Count > 0)
{
if (((CategoryAttribute)atts[typeof(CategoryAttribute)]).Category == String.Empty)
{
return GetResource("Category", baseProp.Name);
}
else
{
return GetResource("Category", ((CategoryAttribute)atts[typeof(CategoryAttribute)]).Category);
}
}
else
{
return "General";
}
}
}
/// <summary>
/// Indicates the name for the property that will be displayed in the PropertyGrid control.
/// </summary>
/// <remarks>
/// The value will be the value given for the
/// isplayNameAttribute attribute for the property. If there is no DisplayNameAttribute, then this will be the name of
/// the property.
/// </remarks>
public override string DisplayName
{
get
{
AttributeCollection atts = baseProp.Attributes;
if (atts.Count > 0 && ResourceManager.GetGridLanguage() == ResourceManager.GridLanguageType.Localized)
{
if (atts[typeof(DisplayNameAttribute)] == null || ((DisplayNameAttribute)atts[typeof(DisplayNameAttribute)]).DisplayName == String.Empty)
{
return GetResource("Attribute", baseProp.Name);
}
else
{
return GetResource("Attribute", ((DisplayNameAttribute)atts[typeof(DisplayNameAttribute)]).DisplayName);
}
}
else
{
return baseProp.Name;
}
}
}
/// <summary>
/// Indicates the description for the property.</summary><remarks>The value will be the value given for the <see cref="DescriptionAttribute"/>
/// attribute for the property, if one exists. If there is no DescriptionAttribute, then this will be null.
/// </remarks>
public override string Description
{
get
{
AttributeCollection atts = baseProp.Attributes;
if (atts.Count > 0)
{
if (atts[typeof(DescriptionAttribute)] == null || ((DescriptionAttribute)atts[typeof(DescriptionAttribute)]).Description == String.Empty)
{
return GetResource("Description", baseProp.Name);
}
else
{
return GetResource("Description", ((DescriptionAttribute)atts[typeof(DescriptionAttribute)]).Description);
}
}
else
{
return baseProp.Name;
}
}
}
/// <summary>
/// Returns whether this property is browsable (viewable) in the grid.
/// </summary>
public override bool IsBrowsable
{
get
{
return baseProp.IsBrowsable;
}
}
/// <summary>
/// Returns whether this property is readonly.
/// </summary>
public override bool IsReadOnly
{
get
{
return baseProp.IsReadOnly;
}
}
/// <summary>
/// Returns whether this property resetting when the value is overwritten.
/// </summary>
/// <param name="component"></param>
/// <returns></returns>
public override bool CanResetValue(object component)
{
return this.baseProp.CanResetValue(component);
}
/// <summary>
/// Returns the type of the component containing this property.
/// </summary>
public override Type ComponentType
{
get
{
return baseProp.ComponentType;
}
}
/// <summary>
/// Gets the value of the property.
/// </summary>
/// <param name="component">The component which contains the property.</param>
/// <returns>An object that represents the value. It is up to the caller to cast to the right type.</returns>
public override object GetValue(object component)
{
return this.baseProp.GetValue(component);
}
/// <summary>
/// The type of the property themselfes.
/// </summary>
public override Type PropertyType
{
get
{
return this.baseProp.PropertyType;
}
}
/// <summary>
/// Reset the value of the property to the default one.
/// </summary>
/// <param name="component">The component which contains the property.</param>
public override void ResetValue(object component)
{
baseProp.ResetValue(component);
}
/// <summary>
/// Set the value of the property.
/// </summary>
/// <param name="component">The component which contains the property.</param>
/// <param name="Value">The value beeing set.</param>
public override void SetValue(object component, object Value)
{
this.baseProp.SetValue(component, Value);
}
/// <summary>
/// Determines a value indicating whether the value of this property needs to be persistend.
/// </summary>
/// <param name="component">The component which contains the property.</param>
/// <returns><c>True</c> if the property should be persistent; otherwise, <c>false</c>.</returns>
public override bool ShouldSerializeValue(object component)
{
return this.baseProp.ShouldSerializeValue(component);
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using Spine;
namespace Spine.Unity {
/// <summary>Loads and stores a Spine atlas and list of materials.</summary>
public class AtlasAsset : ScriptableObject {
public TextAsset atlasFile;
public Material[] materials;
protected Atlas atlas;
public bool IsLoaded { get { return this.atlas != null; } }
#region Runtime Instantiation
/// <summary>
/// Creates a runtime AtlasAsset</summary>
public static AtlasAsset CreateRuntimeInstance (TextAsset atlasText, Material[] materials, bool initialize) {
AtlasAsset atlasAsset = ScriptableObject.CreateInstance<AtlasAsset>();
atlasAsset.Reset();
atlasAsset.atlasFile = atlasText;
atlasAsset.materials = materials;
if (initialize)
atlasAsset.GetAtlas();
return atlasAsset;
}
/// <summary>
/// Creates a runtime AtlasAsset. Only providing the textures is slower because it has to search for atlas page matches. <seealso cref="Spine.Unity.AtlasAsset.CreateRuntimeInstance(TextAsset, Material[], bool)"/></summary>
public static AtlasAsset CreateRuntimeInstance (TextAsset atlasText, Texture2D[] textures, Material materialPropertySource, bool initialize) {
// Get atlas page names.
string atlasString = atlasText.text;
atlasString = atlasString.Replace("\r", "");
string[] atlasLines = atlasString.Split('\n');
var pages = new List<string>();
for (int i = 0; i < atlasLines.Length - 1; i++) {
if (atlasLines[i].Trim().Length == 0)
pages.Add(atlasLines[i + 1].Trim().Replace(".png", ""));
}
// Populate Materials[] by matching texture names with page names.
var materials = new Material[pages.Count];
for (int i = 0, n = pages.Count; i < n; i++) {
Material mat = null;
// Search for a match.
string pageName = pages[i];
for (int j = 0, m = textures.Length; j < m; j++) {
if (string.Equals(pageName, textures[j].name, System.StringComparison.OrdinalIgnoreCase)) {
// Match found.
mat = new Material(materialPropertySource);
mat.mainTexture = textures[j];
break;
}
}
if (mat != null)
materials[i] = mat;
else
throw new ArgumentException("Could not find matching atlas page in the texture array.");
}
// Create AtlasAsset normally
return CreateRuntimeInstance(atlasText, materials, initialize);
}
/// <summary>
/// Creates a runtime AtlasAsset. Only providing the textures is slower because it has to search for atlas page matches. <seealso cref="Spine.Unity.AtlasAsset.CreateRuntimeInstance(TextAsset, Material[], bool)"/></summary>
public static AtlasAsset CreateRuntimeInstance (TextAsset atlasText, Texture2D[] textures, Shader shader, bool initialize) {
if (shader == null)
shader = Shader.Find("Spine/Skeleton");
Material materialProperySource = new Material(shader);
var oa = CreateRuntimeInstance(atlasText, textures, materialProperySource, initialize);
return oa;
}
#endregion
void Reset () {
Clear();
}
public virtual void Clear () {
atlas = null;
}
/// <returns>The atlas or null if it could not be loaded.</returns>
public virtual Atlas GetAtlas () {
if (atlasFile == null) {
Debug.LogError("Atlas file not set for atlas asset: " + name, this);
Clear();
return null;
}
if (materials == null || materials.Length == 0) {
Debug.LogError("Materials not set for atlas asset: " + name, this);
Clear();
return null;
}
if (atlas != null) return atlas;
try {
atlas = new Atlas(new StringReader(atlasFile.text), "", new MaterialsTextureLoader(this));
atlas.FlipV();
return atlas;
} catch (Exception ex) {
Debug.LogError("Error reading atlas file for atlas asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, this);
return null;
}
}
public Mesh GenerateMesh (string name, Mesh mesh, out Material material, float scale = 0.01f) {
AtlasRegion region = atlas.FindRegion(name);
material = null;
if (region != null) {
if (mesh == null) {
mesh = new Mesh();
mesh.name = name;
}
Vector3[] verts = new Vector3[4];
Vector2[] uvs = new Vector2[4];
Color[] colors = { Color.white, Color.white, Color.white, Color.white };
int[] triangles = { 0, 1, 2, 2, 3, 0 };
float left, right, top, bottom;
left = region.width / -2f;
right = left * -1f;
top = region.height / 2f;
bottom = top * -1;
verts[0] = new Vector3(left, bottom, 0) * scale;
verts[1] = new Vector3(left, top, 0) * scale;
verts[2] = new Vector3(right, top, 0) * scale;
verts[3] = new Vector3(right, bottom, 0) * scale;
float u, v, u2, v2;
u = region.u;
v = region.v;
u2 = region.u2;
v2 = region.v2;
if (!region.rotate) {
uvs[0] = new Vector2(u, v2);
uvs[1] = new Vector2(u, v);
uvs[2] = new Vector2(u2, v);
uvs[3] = new Vector2(u2, v2);
} else {
uvs[0] = new Vector2(u2, v2);
uvs[1] = new Vector2(u, v2);
uvs[2] = new Vector2(u, v);
uvs[3] = new Vector2(u2, v);
}
mesh.triangles = new int[0];
mesh.vertices = verts;
mesh.uv = uvs;
mesh.colors = colors;
mesh.triangles = triangles;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
material = (Material)region.page.rendererObject;
} else {
mesh = null;
}
return mesh;
}
}
public class MaterialsTextureLoader : TextureLoader {
AtlasAsset atlasAsset;
public MaterialsTextureLoader (AtlasAsset atlasAsset) {
this.atlasAsset = atlasAsset;
}
public void Load (AtlasPage page, string path) {
String name = Path.GetFileNameWithoutExtension(path);
Material material = null;
foreach (Material other in atlasAsset.materials) {
if (other.mainTexture == null) {
Debug.LogError("Material is missing texture: " + other.name, other);
return;
}
if (other.mainTexture.name == name) {
material = other;
break;
}
}
if (material == null) {
Debug.LogError("Material with texture name \"" + name + "\" not found for atlas asset: " + atlasAsset.name, atlasAsset);
return;
}
page.rendererObject = material;
// Very old atlas files expected the texture's actual size to be used at runtime.
if (page.width == 0 || page.height == 0) {
page.width = material.mainTexture.width;
page.height = material.mainTexture.height;
}
}
public void Unload (object texture) { }
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Tools.ModelElement
// Description: An abstract class that handles drawing boxes for elements in the modeler window
//
// ********************************************************************************************************
// 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 Toolbox.dll for the DotSpatial 4.6/6 ToolManager project
//
// The Initial Developer of this Original Code is Brian Marchionni. Created in Nov, 2008.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using DotSpatial.Symbology;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
using Point = System.Drawing.Point;
namespace DotSpatial.Modeling.Forms
{
/// <summary>
/// Defines the base class for all model components
/// </summary>
public class ModelElement : ICloneable
{
#region --------------- class variables
private Color _color = Color.Wheat;
private Font _font = SystemFonts.MessageBoxFont;
private int _height = 100;
private double _highlight = 1;
private Point _location = new Point(0, 0);
private List<ModelElement> _modelElements;
private string _name = string.Empty;
private ModelShape _shape = ModelShape.Triangle;
private int _width = 170;
#endregion
#region --------------- Constructors
/// <summary>
/// Creates an instance of the model Element
/// <param name="modelElements">A list of all the elements in the model</param>
/// </summary>
public ModelElement(List<ModelElement> modelElements)
{
_modelElements = modelElements;
}
#endregion
#region --------------- Methods
/// <summary>
/// This returns a duplicate of this object.
/// </summary>
/// <returns></returns>
public object Clone()
{
return Copy();
}
/// <summary>
/// Returns a shallow copy of the Parameter class
/// </summary>
/// <returns>A new Parameters class that is a shallow copy of the original parameters class</returns>
public ModelElement Copy()
{
return MemberwiseClone() as ModelElement;
}
/// <summary>
/// Darkens the component slightly
/// </summary>
/// <param name="highlighted">Darkens if true returns to normal if false</param>
public virtual void Highlighted(bool highlighted)
{
if (highlighted)
_highlight = 0.85;
else
_highlight = 1.0;
}
/// <summary>
/// Repaints the form with cool background and stuff
/// </summary>
/// <param name="graph">The graphics object to paint to, the element will be drawn to 0, 0</param>
public virtual void Paint(Graphics graph)
{
//Sets up the colors to use
Pen outlinePen = new Pen(SymbologyGlobal.ColorFromHsl(Color.GetHue(), Color.GetSaturation(), Color.GetBrightness() * 0.6 * Highlight), 1.75F);
Color gradientTop = SymbologyGlobal.ColorFromHsl(Color.GetHue(), Color.GetSaturation(), Color.GetBrightness() * 0.7 * Highlight);
Color gradientBottom = SymbologyGlobal.ColorFromHsl(Color.GetHue(), Color.GetSaturation(), Color.GetBrightness() * 1.0 * Highlight);
//The path used for drop shadows
GraphicsPath shadowPath = new GraphicsPath();
ColorBlend colorBlend = new ColorBlend(3);
colorBlend.Colors = new[] { Color.Transparent, Color.FromArgb(180, Color.DarkGray), Color.FromArgb(180, Color.DimGray) };
colorBlend.Positions = new[] { 0f, 0.125f, 1f };
//Draws Rectangular Shapes
if (Shape == ModelShape.Rectangle)
{
//Draws the shadow
shadowPath.AddPath(GetRoundedRect(new Rectangle(5, 5, Width, Height), 10), true);
PathGradientBrush shadowBrush = new PathGradientBrush(shadowPath);
shadowBrush.WrapMode = WrapMode.Clamp;
shadowBrush.InterpolationColors = colorBlend;
graph.FillPath(shadowBrush, shadowPath);
//Draws the basic shape
Rectangle fillRectange = new Rectangle(0, 0, Width - 5, Height - 5);
GraphicsPath fillArea = GetRoundedRect(fillRectange, 5);
LinearGradientBrush myBrush = new LinearGradientBrush(fillRectange, gradientBottom, gradientTop, LinearGradientMode.Vertical);
graph.FillPath(myBrush, fillArea);
graph.DrawPath(outlinePen, fillArea);
//Draws the status light
DrawStatusLight(graph);
//Draws the text
SizeF textSize = graph.MeasureString(Name, Font, Width);
RectangleF textRect;
if ((textSize.Width < Width) || (textSize.Height < Height))
textRect = new RectangleF((Width - textSize.Width) / 2, (Height - textSize.Height) / 2, textSize.Width, textSize.Height);
else
textRect = new RectangleF(0, (Height - textSize.Height) / 2, Width, textSize.Height);
graph.DrawString(Name, Font, new SolidBrush(Color.FromArgb(50, Color.Black)), textRect);
textRect.X = textRect.X - 1;
textRect.Y = textRect.Y - 1;
graph.DrawString(Name, Font, Brushes.Black, textRect);
//Garbage collection
fillArea.Dispose();
myBrush.Dispose();
}
//Draws Ellipse Shapes
if (_shape == ModelShape.Ellipse)
{
//Draws the shadow
shadowPath.AddEllipse(0, 5, Width + 5, Height);
PathGradientBrush shadowBrush = new PathGradientBrush(shadowPath);
shadowBrush.WrapMode = WrapMode.Clamp;
shadowBrush.InterpolationColors = colorBlend;
graph.FillPath(shadowBrush, shadowPath);
//Draws the Ellipse
Rectangle fillArea = new Rectangle(0, 0, Width, Height);
LinearGradientBrush myBrush = new LinearGradientBrush(fillArea, gradientBottom, gradientTop, LinearGradientMode.Vertical);
graph.FillEllipse(myBrush, 1, 1, Width - 5, Height - 5);
graph.DrawEllipse(outlinePen, 1, 1, Width - 5, Height - 5);
//Draws the text
SizeF textSize = graph.MeasureString(_name, _font, Width);
RectangleF textRect;
if ((textSize.Width < Width) || (textSize.Height < Height))
textRect = new RectangleF((Width - textSize.Width) / 2, (Height - textSize.Height) / 2, textSize.Width, textSize.Height);
else
textRect = new RectangleF(0, (Height - textSize.Height) / 2, Width, textSize.Height);
graph.DrawString(Name, Font, new SolidBrush(Color.FromArgb(50, Color.Black)), textRect);
textRect.X = textRect.X - 1;
textRect.Y = textRect.Y - 1;
graph.DrawString(Name, Font, Brushes.Black, textRect);
//Garbage collection
myBrush.Dispose();
}
//Draws Triangular Shapes
if (_shape == ModelShape.Triangle)
{
//Draws the shadow
Point[] ptShadow = new Point[4];
ptShadow[0] = new Point(5, 5);
ptShadow[1] = new Point(Width + 5, ((Height - 5) / 2) + 5);
ptShadow[2] = new Point(5, Height + 2);
ptShadow[3] = new Point(5, 5);
shadowPath.AddLines(ptShadow);
PathGradientBrush shadowBrush = new PathGradientBrush(shadowPath);
shadowBrush.WrapMode = WrapMode.Clamp;
shadowBrush.InterpolationColors = colorBlend;
graph.FillPath(shadowBrush, shadowPath);
//Draws the shape
Point[] pt = new Point[4];
pt[0] = new Point(0, 0);
pt[1] = new Point(Width - 5, (Height - 5) / 2);
pt[2] = new Point(0, Height - 5);
pt[3] = new Point(0, 0);
GraphicsPath myPath = new GraphicsPath();
myPath.AddLines(pt);
Rectangle fillArea = new Rectangle(1, 1, Width - 5, Height - 5);
LinearGradientBrush myBrush = new LinearGradientBrush(fillArea, gradientBottom, gradientTop, LinearGradientMode.Vertical);
graph.FillPath(myBrush, myPath);
graph.DrawPath(outlinePen, myPath);
//Draws the text
SizeF textSize = graph.MeasureString(Name, Font, Width);
RectangleF textRect;
if ((textSize.Width < Width) || (textSize.Height < Height))
textRect = new RectangleF((Width - textSize.Width) / 2, (Height - textSize.Height) / 2, textSize.Width, textSize.Height);
else
textRect = new RectangleF(0, (Height - textSize.Height) / 2, Width, textSize.Height);
graph.DrawString(Name, Font, Brushes.Black, textRect);
//Garbage collection
myBrush.Dispose();
}
//Garbage collection
shadowPath.Dispose();
outlinePen.Dispose();
}
/// <summary>
/// This does nothing in the base class but child classes may override it
/// </summary>
/// <param name="graph"></param>
protected virtual void DrawStatusLight(Graphics graph)
{
}
/// <summary>
/// Returns true if the point is in the extents rectangle of the element
/// </summary>
/// <param name="pt">A point to test, assuming 0, 0 is the top left corner of the shapes drawing rectangle</param>
/// <returns></returns>
protected virtual bool PointInExtents(Point pt)
{
if ((pt.X > 0 && pt.X < Width) && (pt.Y > 0 && pt.Y < Height))
return true;
return false;
}
/// <summary>
/// Calculates if a point is within the shape that defines the element
/// </summary>
/// <param name="point">A point to test in the virtual modeling plane</param>
/// <returns></returns>
public virtual bool PointInElement(Point point)
{
Point pt = new Point(point.X - Location.X, point.Y - Location.Y);
switch (Shape)
{
case ModelShape.Rectangle:
if ((pt.X > 0 && pt.X < Width) && (pt.Y > 0 && pt.Y < Height))
return true;
break;
case ModelShape.Ellipse:
double a = Width / 2.0;
double b = Height / 2.0;
double x = pt.X - a;
double y = pt.Y - b;
if (((x * x) / (a * a)) + ((y * y) / (b * b)) <= 1)
return true;
break;
case ModelShape.Triangle:
if ((pt.X >= 0) && (pt.X < Width))
{
double y1 = (((Height / 2.0) / Width) * pt.X) + 0;
double y2 = (-((Height / 2.0) / Width) * pt.X) + Height;
if ((pt.Y < y2) && (pt.Y > y1))
return true;
}
break;
default:
return false;
}
return false;
}
/// <summary>
/// Returns true if the element intersect the rectangle from the parent class
/// </summary>
/// <param name="rect">The rectangle to test must be in the virtual modeling coordinant plane</param>
/// <returns></returns>
public virtual bool ElementInRectangle(Rectangle rect)
{
IGeometry rectanglePoly;
if ((rect.Height == 0) && (rect.Width == 0))
{
rectanglePoly = new NetTopologySuite.Geometries.Point(rect.X, rect.Y);
}
else if (rect.Width == 0)
{
Coordinate[] rectanglePoints = new Coordinate[2];
rectanglePoints[0] = new Coordinate(rect.X, rect.Y);
rectanglePoints[1] = new Coordinate(rect.X, rect.Y + rect.Height);
rectanglePoly = new LineString(rectanglePoints);
}
else if (rect.Height == 0)
{
Coordinate[] rectanglePoints = new Coordinate[2];
rectanglePoints[0] = new Coordinate(rect.X, rect.Y);
rectanglePoints[1] = new Coordinate(rect.X + rect.Width, rect.Y);
rectanglePoly = new LineString(rectanglePoints);
}
else
{
Coordinate[] rectanglePoints = new Coordinate[5];
rectanglePoints[0] = new Coordinate(rect.X, rect.Y);
rectanglePoints[1] = new Coordinate(rect.X, rect.Y + rect.Height);
rectanglePoints[2] = new Coordinate(rect.X + rect.Width, rect.Y + rect.Height);
rectanglePoints[3] = new Coordinate(rect.X + rect.Width, rect.Y);
rectanglePoints[4] = new Coordinate(rect.X, rect.Y);
rectanglePoly = new Polygon(new LinearRing(rectanglePoints));
}
switch (Shape)
{
case ModelShape.Rectangle:
return (rect.IntersectsWith(Rectangle));
case ModelShape.Ellipse:
int b = Height / 2;
int a = Width / 2;
Coordinate[] ellipsePoints = new Coordinate[(4 * a) + 1];
for (int x = -a; x <= a; x++)
{
if (x == 0)
{
ellipsePoints[x + a] = new Coordinate(Location.X + x + a, Location.Y);
ellipsePoints[3 * a - x] = new Coordinate(Location.X + x + a, Location.Y + Height);
}
else
{
ellipsePoints[x + a] = new Coordinate(Location.X + x + a, Location.Y + b - Math.Sqrt(Math.Abs(((b * b * x * x) / (a * a)) - (b * b))));
ellipsePoints[3 * a - x] = new Coordinate(Location.X + x + a, Location.Y + b + Math.Sqrt(Math.Abs(((b * b * x * x) / (a * a)) - (b * b))));
}
}
Polygon ellipsePoly = new Polygon(new LinearRing(ellipsePoints));
return (ellipsePoly.Intersects(rectanglePoly));
case ModelShape.Triangle:
Coordinate[] trianglePoints = new Coordinate[4];
trianglePoints[0] = new Coordinate(Location.X, Location.Y);
trianglePoints[1] = new Coordinate(Location.X, Location.Y + Height);
trianglePoints[2] = new Coordinate(Location.X + Width - 5, Location.Y + ((Height - 5) / 2));
trianglePoints[3] = new Coordinate(Location.X, Location.Y);
Polygon trianglePoly = new Polygon(new LinearRing(trianglePoints));
return (trianglePoly.Intersects(rectanglePoly));
default:
return false;
}
}
/// <summary>
/// Returns true if a point is in a rectangle
/// </summary>
/// <param name="pt"></param>
/// <param name="rect"></param>
protected virtual bool PointInRectangle(Point pt, Rectangle rect)
{
if ((pt.X >= rect.X && pt.X <= (rect.X + rect.Width)) && (pt.Y >= rect.Y && pt.Y <= (rect.Y + rect.Height)))
return true;
return false;
}
/// <summary>
/// When a double click is caught by the parent class call this method
/// </summary>
public virtual bool DoubleClick()
{
return true;
}
/// <summary>
/// Creates a rounded corner rectangle from a regular rectangel
/// </summary>
/// <param name="baseRect"></param>
/// <param name="radius"></param>
/// <returns></returns>
private static GraphicsPath GetRoundedRect(RectangleF baseRect, float radius)
{
if ((radius <= 0.0F) || radius >= ((Math.Min(baseRect.Width, baseRect.Height)) / 2.0))
{
GraphicsPath mPath = new GraphicsPath();
mPath.AddRectangle(baseRect);
mPath.CloseFigure();
return mPath;
}
float diameter = radius * 2.0F;
SizeF sizeF = new SizeF(diameter, diameter);
RectangleF arc = new RectangleF(baseRect.Location, sizeF);
GraphicsPath path = new GraphicsPath();
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = baseRect.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = baseRect.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = baseRect.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
/// <summary>
/// Returns true if this model element is downstram of the potentialUpstream element
/// </summary>
/// <param name="potentialUpstream"></param>
/// <returns></returns>
public bool IsDownstreamOf(ModelElement potentialUpstream)
{ return IsDownstreamOf(potentialUpstream, this); }
private bool IsDownstreamOf(ModelElement potentialUpstream, ModelElement child)
{
foreach (ModelElement mEl in _modelElements)
{
ArrowElement mAr = mEl as ArrowElement;
if (mAr != null)
{
if (mAr.StopElement == null) continue;
if (mAr.StopElement == child)
{
if (mAr.StartElement == null) continue;
if (mAr.StartElement == potentialUpstream) return true;
foreach (ModelElement parents in GetParents(mAr.StartElement))
{
if (IsDownstreamOf(potentialUpstream, parents)) return true;
}
return false;
}
}
}
return false;
}
/// <summary>
/// Returns a list of all model elements that are direct parents of this element
/// </summary>
/// <returns></returns>
public List<ModelElement> GetParents()
{ return GetParents(this); }
private List<ModelElement> GetParents(ModelElement child)
{
List<ModelElement> listParents = new List<ModelElement>();
foreach (ModelElement mEl in _modelElements)
{
ArrowElement mAr = mEl as ArrowElement;
if (mAr != null)
if (mAr.StopElement != null)
if (mAr.StopElement == child) listParents.Add(mAr.StartElement);
}
return listParents;
}
/// <summary>
/// Returns true if this model element is downstream of the potentialUpstream element
/// </summary>
/// <param name="potentialDownstream"></param>
/// <returns></returns>
public bool IsUpstreamOf(ModelElement potentialDownstream)
{ return IsUpstreamOf(potentialDownstream, this); }
private bool IsUpstreamOf(ModelElement potentialDownstream, ModelElement parent)
{
foreach (ModelElement mEl in _modelElements)
{
ArrowElement mAr = mEl as ArrowElement;
if (mAr != null)
{
if (mAr.StartElement == null) continue;
if (mAr.StartElement == parent)
{
if (mAr.StopElement == null) continue;
if (mAr.StopElement == potentialDownstream) return true;
foreach (ModelElement children in GetChildren(mAr.StartElement))
{
if (IsUpstreamOf(potentialDownstream, children)) return true;
}
return false;
}
}
}
return false;
}
/// <summary>
/// Returns a list of all model elements that are direct children of this element
/// </summary>
/// <returns></returns>
public List<ModelElement> GetChildren()
{ return GetChildren(this); }
private List<ModelElement> GetChildren(ModelElement parent)
{
List<ModelElement> listChildren = new List<ModelElement>();
foreach (ModelElement mEl in _modelElements)
{
ArrowElement mAr = mEl as ArrowElement;
if (mAr != null)
if (mAr.StartElement != null)
if (mAr.StartElement == parent) listChildren.Add(mAr.StopElement);
}
return listChildren;
}
#endregion
#region --------------- Properties
/// <summary>
/// Gets a list of all elements in the model
/// </summary>
internal List<ModelElement> ModelElements
{
get { return _modelElements; }
set { _modelElements = value; }
}
/// <summary>
/// Returns 1 if the object is not highlighted less than 1 if it is highlighted
/// </summary>
public double Highlight
{
get { return _highlight; }
set { _highlight = value; }
}
/// <summary>
/// Gets or sets the text that is drawn on the element
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// Gets or sets the font used to draw the text on the element
/// </summary>
public Font Font
{
get { return _font; }
set { _font = value; }
}
/// <summary>
/// Gets or Sets the shape of the model component
/// </summary>
public ModelShape Shape
{
get { return _shape; }
set { _shape = value; }
}
/// <summary>
/// Gets or set the base color of the shapes gradient
/// </summary>
public Color Color
{
get { return _color; }
set { _color = value; }
}
/// <summary>
/// Gets a rectangle representing the element, top left corner being the location of the parent form of the element
/// </summary>
public Rectangle Rectangle
{
get { return (new Rectangle(Location.X, Location.Y, Width, Height)); }
}
/// <summary>
/// Gets or sets the width of the element
/// </summary>
public int Width
{
get { return _width; }
set { _width = value; }
}
/// <summary>
/// Gets or sets the shape of the element
/// </summary>
public int Height
{
get { return _height; }
set { _height = value; }
}
/// <summary>
/// Gets or sets the location of the element in the parent form
/// </summary>
public Point Location
{
get { return _location; }
set { _location = value; }
}
#endregion
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Discovery
{
using System;
using System.Collections.Generic;
using System.Runtime;
using System.Threading;
using System.Xml;
using SR2 = System.ServiceModel.Discovery.SR;
class AsyncOperationLifetimeManager
{
[Fx.Tag.SynchronizationObject()]
object thisLock;
bool isAborted;
AsyncWaitHandle closeHandle;
Dictionary<UniqueId, AsyncOperationContext> activeOperations;
public AsyncOperationLifetimeManager()
{
this.thisLock = new object();
this.activeOperations = new Dictionary<UniqueId, AsyncOperationContext>();
}
public bool IsAborted
{
get
{
return this.isAborted;
}
}
public bool IsClosed
{
get
{
return this.closeHandle != null;
}
}
public bool TryAdd(AsyncOperationContext context)
{
Fx.Assert(context != null, "The context must be non null.");
lock (this.thisLock)
{
if (this.IsAborted || this.IsClosed)
{
return false;
}
if (this.activeOperations.ContainsKey(context.OperationId))
{
return false;
}
this.activeOperations.Add(context.OperationId, context);
}
return true;
}
public AsyncOperationContext[] Abort()
{
AsyncOperationContext[] retValue = null;
bool setCloseHandle = false;
lock (this.thisLock)
{
if (this.IsAborted)
{
return new AsyncOperationContext[] { };
}
else
{
this.isAborted = true;
}
retValue = new AsyncOperationContext[this.activeOperations.Count];
this.activeOperations.Values.CopyTo(retValue, 0);
this.activeOperations.Clear();
setCloseHandle = this.closeHandle != null;
}
if (setCloseHandle)
{
this.closeHandle.Set();
}
return retValue;
}
public bool TryLookup(UniqueId operationId, out AsyncOperationContext context)
{
bool success;
lock (this.thisLock)
{
success = this.activeOperations.TryGetValue(operationId, out context);
}
return success;
}
public bool TryLookup<T>(UniqueId operationId, out T context) where T : AsyncOperationContext
{
AsyncOperationContext asyncContext = null;
if (TryLookup(operationId, out asyncContext))
{
context = asyncContext as T;
if (context != null)
{
return true;
}
}
context = null;
return false;
}
public T Remove<T>(UniqueId operationId) where T : AsyncOperationContext
{
AsyncOperationContext context = null;
bool setCloseHandle = false;
lock (this.thisLock)
{
if ((this.activeOperations.TryGetValue(operationId, out context)) &&
(context is T))
{
this.activeOperations.Remove(operationId);
setCloseHandle = (this.closeHandle != null) && (this.activeOperations.Count == 0);
}
else
{
context = null;
}
}
if (setCloseHandle)
{
this.closeHandle.Set();
}
return context as T;
}
public bool TryRemoveUnique(object userState, out AsyncOperationContext context)
{
bool success = false;
bool setCloseHandle = false;
context = null;
lock (this.thisLock)
{
foreach (AsyncOperationContext value in this.activeOperations.Values)
{
if (object.Equals(value.UserState, userState))
{
if (success)
{
success = false;
break;
}
else
{
context = value;
success = true;
}
}
}
if (success)
{
this.activeOperations.Remove(context.OperationId);
setCloseHandle = (this.closeHandle != null) && (this.activeOperations.Count == 0);
}
}
if (setCloseHandle)
{
this.closeHandle.Set();
}
return success;
}
public void Close(TimeSpan timeout)
{
InitializeCloseHandle();
if (!this.closeHandle.Wait(timeout))
{
throw FxTrace.Exception.AsError(new TimeoutException(SR2.TimeoutOnOperation(timeout)));
}
}
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
InitializeCloseHandle();
return new CloseAsyncResult(this.closeHandle, timeout, callback, state);
}
public void EndClose(IAsyncResult result)
{
CloseAsyncResult.End(result);
}
void InitializeCloseHandle()
{
bool setCloseHandle = false;
lock (this.thisLock)
{
this.closeHandle = new AsyncWaitHandle(EventResetMode.ManualReset);
setCloseHandle = (this.activeOperations.Count == 0);
if (this.IsAborted)
{
setCloseHandle = true;
}
}
if (setCloseHandle)
{
this.closeHandle.Set();
}
}
class CloseAsyncResult : AsyncResult
{
static Action<object, TimeoutException> onWaitCompleted = new Action<object, TimeoutException>(OnWaitCompleted);
AsyncWaitHandle asyncWaitHandle;
internal CloseAsyncResult(AsyncWaitHandle asyncWaitHandle, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.asyncWaitHandle = asyncWaitHandle;
if (this.asyncWaitHandle.WaitAsync(onWaitCompleted, this, timeout))
{
Complete(true);
}
}
static void OnWaitCompleted(object state, TimeoutException asyncException)
{
CloseAsyncResult thisPtr = (CloseAsyncResult)state;
thisPtr.Complete(false, asyncException);
}
internal static void End(IAsyncResult result)
{
AsyncResult.End<CloseAsyncResult>(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;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the SysSexo class.
/// </summary>
[Serializable]
public partial class SysSexoCollection : ActiveList<SysSexo, SysSexoCollection>
{
public SysSexoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysSexoCollection</returns>
public SysSexoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysSexo 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 Sys_Sexo table.
/// </summary>
[Serializable]
public partial class SysSexo : ActiveRecord<SysSexo>, IActiveRecord
{
#region .ctors and Default Settings
public SysSexo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysSexo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysSexo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysSexo(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("Sys_Sexo", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdSexo = new TableSchema.TableColumn(schema);
colvarIdSexo.ColumnName = "idSexo";
colvarIdSexo.DataType = DbType.Int32;
colvarIdSexo.MaxLength = 0;
colvarIdSexo.AutoIncrement = true;
colvarIdSexo.IsNullable = false;
colvarIdSexo.IsPrimaryKey = true;
colvarIdSexo.IsForeignKey = false;
colvarIdSexo.IsReadOnly = false;
colvarIdSexo.DefaultSetting = @"";
colvarIdSexo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdSexo);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Sys_Sexo",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdSexo")]
[Bindable(true)]
public int IdSexo
{
get { return GetColumnValue<int>(Columns.IdSexo); }
set { SetColumnValue(Columns.IdSexo, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.SysPacienteCollection colSysPacienteRecords;
public DalSic.SysPacienteCollection SysPacienteRecords
{
get
{
if(colSysPacienteRecords == null)
{
colSysPacienteRecords = new DalSic.SysPacienteCollection().Where(SysPaciente.Columns.IdSexo, IdSexo).Load();
colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged);
}
return colSysPacienteRecords;
}
set
{
colSysPacienteRecords = value;
colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged);
}
}
void colSysPacienteRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colSysPacienteRecords[e.NewIndex].IdSexo = IdSexo;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
SysSexo item = new SysSexo();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdSexo,string varNombre)
{
SysSexo item = new SysSexo();
item.IdSexo = varIdSexo;
item.Nombre = varNombre;
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 IdSexoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdSexo = @"idSexo";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colSysPacienteRecords != null)
{
foreach (DalSic.SysPaciente item in colSysPacienteRecords)
{
if (item.IdSexo != IdSexo)
{
item.IdSexo = IdSexo;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colSysPacienteRecords != null)
{
colSysPacienteRecords.SaveAll();
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Xunit;
namespace Microsoft.Extensions.Internal
{
public class TypeNameHelperTest
{
[Theory]
// Predefined Types
[InlineData(typeof(int), "int")]
[InlineData(typeof(List<int>), "System.Collections.Generic.List<int>")]
[InlineData(typeof(Dictionary<int, string>), "System.Collections.Generic.Dictionary<int, string>")]
[InlineData(typeof(Dictionary<int, List<string>>), "System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>")]
[InlineData(typeof(List<List<string>>), "System.Collections.Generic.List<System.Collections.Generic.List<string>>")]
// Classes inside NonGeneric class
[InlineData(typeof(A),
"Microsoft.Extensions.Internal.TypeNameHelperTest+A")]
[InlineData(typeof(B<int>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+B<int>")]
[InlineData(typeof(C<int, string>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+C<int, string>")]
[InlineData(typeof(B<B<string>>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+B<Microsoft.Extensions.Internal.TypeNameHelperTest+B<string>>")]
[InlineData(typeof(C<int, B<string>>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+C<int, Microsoft.Extensions.Internal.TypeNameHelperTest+B<string>>")]
// Classes inside Generic class
[InlineData(typeof(Outer<int>.D),
"Microsoft.Extensions.Internal.TypeNameHelperTest+Outer<int>+D")]
[InlineData(typeof(Outer<int>.E<int>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+Outer<int>+E<int>")]
[InlineData(typeof(Outer<int>.F<int, string>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+Outer<int>+F<int, string>")]
[InlineData(typeof(Level1<int>.Level2<bool>.Level3<int>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+Level1<int>+Level2<bool>+Level3<int>")]
[InlineData(typeof(Outer<int>.E<Outer<int>.E<string>>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+Outer<int>+E<Microsoft.Extensions.Internal.TypeNameHelperTest+Outer<int>+E<string>>")]
[InlineData(typeof(Outer<int>.F<int, Outer<int>.E<string>>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+Outer<int>+F<int, Microsoft.Extensions.Internal.TypeNameHelperTest+Outer<int>+E<string>>")]
[InlineData(typeof(OuterGeneric<int>.InnerNonGeneric.InnerGeneric<int, string>.InnerGenericLeafNode<bool>),
"Microsoft.Extensions.Internal.TypeNameHelperTest+OuterGeneric<int>+InnerNonGeneric+InnerGeneric<int, string>+InnerGenericLeafNode<bool>")]
public void Can_pretty_print_CLR_full_name(Type type, string expected)
{
Assert.Equal(expected, TypeNameHelper.GetTypeDisplayName(type));
}
[Fact]
public void DoesNotPrintNamespace_ForGenericTypes_IfNullOrEmpty()
{
// Arrange
var type = typeof(ClassInGlobalNamespace<int>);
// Act & Assert
Assert.Equal("ClassInGlobalNamespace<int>", TypeNameHelper.GetTypeDisplayName(type));
}
[Theory]
// Predefined Types
[InlineData(typeof(int), "int")]
[InlineData(typeof(List<int>), "List<int>")]
[InlineData(typeof(Dictionary<int, string>), "Dictionary<int, string>")]
[InlineData(typeof(Dictionary<int, List<string>>), "Dictionary<int, List<string>>")]
[InlineData(typeof(List<List<string>>), "List<List<string>>")]
// Classes inside NonGeneric class
[InlineData(typeof(A), "A")]
[InlineData(typeof(B<int>), "B<int>")]
[InlineData(typeof(C<int, string>), "C<int, string>")]
[InlineData(typeof(C<int, B<string>>), "C<int, B<string>>")]
[InlineData(typeof(B<B<string>>), "B<B<string>>")]
// Classes inside Generic class
[InlineData(typeof(Outer<int>.D), "D")]
[InlineData(typeof(Outer<int>.E<int>), "E<int>")]
[InlineData(typeof(Outer<int>.F<int, string>), "F<int, string>")]
[InlineData(typeof(Outer<int>.F<int, Outer<int>.E<string>>), "F<int, E<string>>")]
[InlineData(typeof(Outer<int>.E<Outer<int>.E<string>>), "E<E<string>>")]
[InlineData(typeof(OuterGeneric<int>.InnerNonGeneric.InnerGeneric<int, string>.InnerGenericLeafNode<bool>), "InnerGenericLeafNode<bool>")]
public void Can_pretty_print_CLR_name(Type type, string expected)
{
Assert.Equal(expected, TypeNameHelper.GetTypeDisplayName(type, false));
}
[Theory]
[InlineData(typeof(void), "void")]
[InlineData(typeof(bool), "bool")]
[InlineData(typeof(byte), "byte")]
[InlineData(typeof(char), "char")]
[InlineData(typeof(decimal), "decimal")]
[InlineData(typeof(double), "double")]
[InlineData(typeof(float), "float")]
[InlineData(typeof(int), "int")]
[InlineData(typeof(long), "long")]
[InlineData(typeof(object), "object")]
[InlineData(typeof(sbyte), "sbyte")]
[InlineData(typeof(short), "short")]
[InlineData(typeof(string), "string")]
[InlineData(typeof(uint), "uint")]
[InlineData(typeof(ulong), "ulong")]
[InlineData(typeof(ushort), "ushort")]
public void Returns_common_name_for_built_in_types(Type type, string expected)
{
Assert.Equal(expected, TypeNameHelper.GetTypeDisplayName(type));
}
[Theory]
[InlineData(typeof(int[]), true, "int[]")]
[InlineData(typeof(string[][]), true, "string[][]")]
[InlineData(typeof(int[,]), true, "int[,]")]
[InlineData(typeof(bool[,,,]), true, "bool[,,,]")]
[InlineData(typeof(A[,][,,]), true, "Microsoft.Extensions.Internal.TypeNameHelperTest+A[,][,,]")]
[InlineData(typeof(List<int[,][,,]>), true, "System.Collections.Generic.List<int[,][,,]>")]
[InlineData(typeof(List<int[,,][,]>[,][,,]), false, "List<int[,,][,]>[,][,,]")]
public void Can_pretty_print_array_name(Type type, bool fullName, string expected)
{
Assert.Equal(expected, TypeNameHelper.GetTypeDisplayName(type, fullName));
}
public static TheoryData GetOpenGenericsTestData()
{
var openDictionaryType = typeof(Dictionary<,>);
var genArgsDictionary = openDictionaryType.GetGenericArguments();
genArgsDictionary[0] = typeof(B<>);
var closedDictionaryType = openDictionaryType.MakeGenericType(genArgsDictionary);
var openLevelType = typeof(Level1<>.Level2<>.Level3<>);
var genArgsLevel = openLevelType.GetGenericArguments();
genArgsLevel[1] = typeof(string);
var closedLevelType = openLevelType.MakeGenericType(genArgsLevel);
var openInnerType = typeof(OuterGeneric<>.InnerNonGeneric.InnerGeneric<,>.InnerGenericLeafNode<>);
var genArgsInnerType = openInnerType.GetGenericArguments();
genArgsInnerType[3] = typeof(bool);
var closedInnerType = openInnerType.MakeGenericType(genArgsInnerType);
return new TheoryData<Type, bool, string>
{
{ typeof(List<>), false, "List<>" },
{ typeof(Dictionary<,>), false , "Dictionary<,>" },
{ typeof(List<>), true , "System.Collections.Generic.List<>" },
{ typeof(Dictionary<,>), true , "System.Collections.Generic.Dictionary<,>" },
{ typeof(Level1<>.Level2<>.Level3<>), true, "Microsoft.Extensions.Internal.TypeNameHelperTest+Level1<>+Level2<>+Level3<>" },
{
typeof(PartiallyClosedGeneric<>).BaseType,
true,
"Microsoft.Extensions.Internal.TypeNameHelperTest+C<, int>"
},
{
typeof(OuterGeneric<>.InnerNonGeneric.InnerGeneric<,>.InnerGenericLeafNode<>),
true,
"Microsoft.Extensions.Internal.TypeNameHelperTest+OuterGeneric<>+InnerNonGeneric+InnerGeneric<,>+InnerGenericLeafNode<>"
},
{
closedDictionaryType,
true,
"System.Collections.Generic.Dictionary<Microsoft.Extensions.Internal.TypeNameHelperTest+B<>,>"
},
{
closedLevelType,
true,
"Microsoft.Extensions.Internal.TypeNameHelperTest+Level1<>+Level2<string>+Level3<>"
},
{
closedInnerType,
true,
"Microsoft.Extensions.Internal.TypeNameHelperTest+OuterGeneric<>+InnerNonGeneric+InnerGeneric<,>+InnerGenericLeafNode<bool>"
}
};
}
[Theory]
[MemberData(nameof(GetOpenGenericsTestData))]
public void Can_pretty_print_open_generics(Type type, bool fullName, string expected)
{
Assert.Equal(expected, TypeNameHelper.GetTypeDisplayName(type, fullName));
}
public static TheoryData GetTypeDisplayName_IncludesGenericParameterNamesWhenOptionIsSetData =>
new TheoryData<Type, string>
{
{ typeof(B<>),"Microsoft.Extensions.Internal.TypeNameHelperTest+B<T>" },
{ typeof(C<,>),"Microsoft.Extensions.Internal.TypeNameHelperTest+C<T1, T2>" },
{ typeof(PartiallyClosedGeneric<>).BaseType,"Microsoft.Extensions.Internal.TypeNameHelperTest+C<T, int>" },
{ typeof(Level1<>.Level2<>),"Microsoft.Extensions.Internal.TypeNameHelperTest+Level1<T1>+Level2<T2>" },
};
[Theory]
[MemberData(nameof(GetTypeDisplayName_IncludesGenericParameterNamesWhenOptionIsSetData))]
public void GetTypeDisplayName_IncludesGenericParameterNamesWhenOptionIsSet(Type type, string expected)
{
// Arrange & Act
var actual = TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameterNames: true);
// Assert
Assert.Equal(expected, actual);
}
public static TheoryData GetTypeDisplayName_WithoutFullName_IncludesGenericParameterNamesWhenOptionIsSetData =>
new TheoryData<Type, string>
{
{ typeof(B<>),"B<T>" },
{ typeof(C<,>),"C<T1, T2>" },
{ typeof(PartiallyClosedGeneric<>).BaseType,"C<T, int>" },
{ typeof(Level1<>.Level2<>),"Level2<T2>" },
};
[Theory]
[MemberData(nameof(GetTypeDisplayName_WithoutFullName_IncludesGenericParameterNamesWhenOptionIsSetData))]
public void GetTypeDisplayName_WithoutFullName_IncludesGenericParameterNamesWhenOptionIsSet(Type type, string expected)
{
// Arrange & Act
var actual = TypeNameHelper.GetTypeDisplayName(type, fullName: false, includeGenericParameterNames: true);
// Assert
Assert.Equal(expected, actual);
}
public static TheoryData<Type, string> FullTypeNameData
{
get
{
return new TheoryData<Type, string>
{
// Predefined Types
{ typeof(int), "int" },
{ typeof(List<int>), "System.Collections.Generic.List" },
{ typeof(Dictionary<int, string>), "System.Collections.Generic.Dictionary" },
{ typeof(Dictionary<int, List<string>>), "System.Collections.Generic.Dictionary" },
{ typeof(List<List<string>>), "System.Collections.Generic.List" },
// Classes inside NonGeneric class
{ typeof(A), "Microsoft.Extensions.Internal.TypeNameHelperTest.A" },
{ typeof(B<int>), "Microsoft.Extensions.Internal.TypeNameHelperTest.B" },
{ typeof(C<int, string>), "Microsoft.Extensions.Internal.TypeNameHelperTest.C" },
{ typeof(C<int, B<string>>), "Microsoft.Extensions.Internal.TypeNameHelperTest.C" },
{ typeof(B<B<string>>), "Microsoft.Extensions.Internal.TypeNameHelperTest.B" },
// Classes inside Generic class
{ typeof(Outer<int>.D), "Microsoft.Extensions.Internal.TypeNameHelperTest.Outer.D" },
{ typeof(Outer<int>.E<int>), "Microsoft.Extensions.Internal.TypeNameHelperTest.Outer.E" },
{ typeof(Outer<int>.F<int, string>), "Microsoft.Extensions.Internal.TypeNameHelperTest.Outer.F" },
{ typeof(Outer<int>.F<int, Outer<int>.E<string>>),"Microsoft.Extensions.Internal.TypeNameHelperTest.Outer.F" },
{ typeof(Outer<int>.E<Outer<int>.E<string>>), "Microsoft.Extensions.Internal.TypeNameHelperTest.Outer.E" }
};
}
}
[Theory]
[MemberData(nameof(FullTypeNameData))]
public void Can_PrettyPrint_FullTypeName_WithoutGenericParametersAndNestedTypeDelimiter(Type type, string expectedTypeName)
{
// Arrange & Act
var displayName = TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameters: false, nestedTypeDelimiter: '.');
// Assert
Assert.Equal(expectedTypeName, displayName);
}
private class A { }
private class B<T> { }
private class C<T1, T2> { }
private class PartiallyClosedGeneric<T> : C<T, int> { }
private class Outer<T>
{
public class D { }
public class E<T1> { }
public class F<T1, T2> { }
}
private class OuterGeneric<T1>
{
public class InnerNonGeneric
{
public class InnerGeneric<T2, T3>
{
public class InnerGenericLeafNode<T4> { }
public class InnerLeafNode { }
}
}
}
private class Level1<T1>
{
public class Level2<T2>
{
public class Level3<T3>
{
}
}
}
}
}
internal class ClassInGlobalNamespace<T>
{
}
| |
using System;
using System.Collections;
using System.IO;
using Raksha.Bcpg;
using Raksha.Bcpg.OpenPgp;
using Raksha.IO;
using Raksha.Security;
using Raksha.Utilities.IO;
namespace Raksha.Tests.Bcpg.OpenPgp.Examples
{
/**
* A simple utility class that encrypts/decrypts public key based
* encryption large files.
* <p>
* To encrypt a file: KeyBasedLargeFileProcessor -e [-a|-ai] fileName publicKeyFile.<br/>
* If -a is specified the output file will be "ascii-armored".
* If -i is specified the output file will be have integrity checking added.</p>
* <p>
* To decrypt: KeyBasedLargeFileProcessor -d fileName secretKeyFile passPhrase.</p>
* <p>
* Note 1: this example will silently overwrite files, nor does it pay any attention to
* the specification of "_CONSOLE" in the filename. It also expects that a single pass phrase
* will have been used.</p>
* <p>
* Note 2: this example Generates partial packets to encode the file, the output it Generates
* will not be readable by older PGP products or products that don't support partial packet
* encoding.</p>
* <p>
* Note 3: if an empty file name has been specified in the literal data object contained in the
* encrypted packet a file with the name filename.out will be generated in the current working directory.</p>
*/
public sealed class KeyBasedLargeFileProcessor
{
private KeyBasedLargeFileProcessor()
{
}
private static void DecryptFile(
string inputFileName,
string keyFileName,
char[] passwd,
string defaultFileName)
{
using (Stream input = File.OpenRead(inputFileName),
keyIn = File.OpenRead(keyFileName))
{
DecryptFile(input, keyIn, passwd, defaultFileName);
}
}
/**
* decrypt the passed in message stream
*/
private static void DecryptFile(
Stream inputStream,
Stream keyIn,
char[] passwd,
string defaultFileName)
{
inputStream = PgpUtilities.GetDecoderStream(inputStream);
try
{
PgpObjectFactory pgpF = new PgpObjectFactory(inputStream);
PgpEncryptedDataList enc;
PgpObject o = pgpF.NextPgpObject();
//
// the first object might be a PGP marker packet.
//
if (o is PgpEncryptedDataList)
{
enc = (PgpEncryptedDataList)o;
}
else
{
enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
}
//
// find the secret key
//
PgpPrivateKey sKey = null;
PgpPublicKeyEncryptedData pbe = null;
PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(
PgpUtilities.GetDecoderStream(keyIn));
foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
{
sKey = PgpExampleUtilities.FindSecretKey(pgpSec, pked.KeyId, passwd);
if (sKey != null)
{
pbe = pked;
break;
}
}
if (sKey == null)
{
throw new ArgumentException("secret key for message not found.");
}
Stream clear = pbe.GetDataStream(sKey);
PgpObjectFactory plainFact = new PgpObjectFactory(clear);
PgpCompressedData cData = (PgpCompressedData) plainFact.NextPgpObject();
PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream());
PgpObject message = pgpFact.NextPgpObject();
if (message is PgpLiteralData)
{
PgpLiteralData ld = (PgpLiteralData)message;
string outFileName = ld.FileName;
if (outFileName.Length == 0)
{
outFileName = defaultFileName;
}
Stream fOut = File.Create(outFileName);
Stream unc = ld.GetInputStream();
Streams.PipeAll(unc, fOut);
fOut.Close();
}
else if (message is PgpOnePassSignatureList)
{
throw new PgpException("encrypted message contains a signed message - not literal data.");
}
else
{
throw new PgpException("message is not a simple encrypted file - type unknown.");
}
if (pbe.IsIntegrityProtected())
{
if (!pbe.Verify())
{
Console.Error.WriteLine("message failed integrity check");
}
else
{
Console.Error.WriteLine("message integrity check passed");
}
}
else
{
Console.Error.WriteLine("no message integrity check");
}
}
catch (PgpException e)
{
Console.Error.WriteLine(e);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
{
Console.Error.WriteLine(underlyingException.Message);
Console.Error.WriteLine(underlyingException.StackTrace);
}
}
}
private static void EncryptFile(
string outputFileName,
string inputFileName,
string encKeyFileName,
bool armor,
bool withIntegrityCheck)
{
PgpPublicKey encKey = PgpExampleUtilities.ReadPublicKey(encKeyFileName);
using (Stream output = File.Create(outputFileName))
{
EncryptFile(output, inputFileName, encKey, armor, withIntegrityCheck);
}
}
private static void EncryptFile(
Stream outputStream,
string fileName,
PgpPublicKey encKey,
bool armor,
bool withIntegrityCheck)
{
if (armor)
{
outputStream = new ArmoredOutputStream(outputStream);
}
try
{
PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
cPk.AddMethod(encKey);
Stream cOut = cPk.Open(outputStream, new byte[1 << 16]);
PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
CompressionAlgorithmTag.Zip);
PgpUtilities.WriteFileToLiteralData(
comData.Open(cOut),
PgpLiteralData.Binary,
new Net45FileInfo(fileName),
new byte[1 << 16]);
comData.Close();
cOut.Close();
if (armor)
{
outputStream.Close();
}
}
catch (PgpException e)
{
Console.Error.WriteLine(e);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
{
Console.Error.WriteLine(underlyingException.Message);
Console.Error.WriteLine(underlyingException.StackTrace);
}
}
}
public static void Main(
string[] args)
{
if (args.Length == 0)
{
Console.Error.WriteLine("usage: KeyBasedLargeFileProcessor -e|-d [-a|ai] file [secretKeyFile passPhrase|pubKeyFile]");
return;
}
if (args[0].Equals("-e"))
{
if (args[1].Equals("-a") || args[1].Equals("-ai") || args[1].Equals("-ia"))
{
EncryptFile(args[2] + ".asc", args[2], args[3], true, (args[1].IndexOf('i') > 0));
}
else if (args[1].Equals("-i"))
{
EncryptFile(args[2] + ".bpg", args[2], args[3], false, true);
}
else
{
EncryptFile(args[1] + ".bpg", args[1], args[2], false, false);
}
}
else if (args[0].Equals("-d"))
{
DecryptFile(args[1], args[2], args[3].ToCharArray(), new FileInfo(args[1]).Name + ".out");
}
else
{
Console.Error.WriteLine("usage: KeyBasedLargeFileProcessor -d|-e [-a|ai] file [secretKeyFile passPhrase|pubKeyFile]");
}
}
}
}
| |
/*
* 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 ParquetSharp.Schema
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using ParquetSharp.IO;
/**
* Represents the declared type for a field in a schema.
* The Type object represents both the actual underlying type of the object
* (eg a primitive or group) as well as its attributes such as whether it is
* repeated, required, or optional.
*/
abstract public class Type : IEquatable<Type>
{
/**
* represents a field ID
*
* @author Julien Le Dem
*
*/
public class ID
{
private int id;
public ID(int id)
{
this.id = id;
}
public int intValue()
{
return id;
}
public override bool Equals(object obj)
{
return (obj is ID) && ((ID)obj).id == id;
}
public override int GetHashCode()
{
return id;
}
public override string ToString()
{
return id.ToString(CultureInfo.InvariantCulture);
}
}
/**
* Constraint on the repetition of a field
*
* @author Julien Le Dem
*/
public enum Repetition
{
REQUIRED, // exactly 1
OPTIONAL, // 0 or 1
REPEATED, // 0 or more
}
private string name;
private Repetition repetition;
private OriginalType? originalType;
private ID id;
/**
* @param name the name of the type
* @param repetition OPTIONAL, REPEATED, REQUIRED
* @param originalType (optional) the original type to help with cross schema conversion (LIST, MAP, ...)
* @param id (optional) the id of the fields.
*/
public Type(string name, Repetition repetition, OriginalType? originalType = null, ID id = null)
{
this.name = Preconditions.checkNotNull(name, "name");
this.repetition = Preconditions.checkNotNull(repetition, "repetition");
this.originalType = originalType;
this.id = id;
}
/**
* @param id
* @return the same type with the id field set
*/
public abstract Type withId(int id);
/**
* @return the name of the type
*/
public string getName()
{
return name;
}
/**
* @param rep
* @return if repetition of the type is rep
*/
public bool isRepetition(Repetition rep)
{
return repetition == rep;
}
/**
* @return the repetition constraint
*/
public Repetition getRepetition()
{
return repetition;
}
/**
* @return the id of the field (if defined)
*/
public ID getId()
{
return id;
}
/**
* @return the original type (LIST, MAP, ...)
*/
public OriginalType? getOriginalType()
{
return originalType;
}
/**
* @return if this is a primitive type
*/
abstract public bool isPrimitive();
/**
* @return this if it's a group type
* @throws InvalidCastException if not
*/
public GroupType asGroupType()
{
if (isPrimitive())
{
throw new InvalidCastException(this + " is not a group");
}
return (GroupType)this;
}
/**
* @return this if it's a primitive type
* @throws InvalidCastException if not
*/
public PrimitiveType asPrimitiveType()
{
if (!isPrimitive())
{
throw new InvalidCastException(this + " is not primitive");
}
return (PrimitiveType)this;
}
/**
* Writes a string representation to the provided StringBuilder
* @param sb the StringBuilder to write itself to
* @param indent indentation level
*/
abstract public void writeToStringBuilder(StringBuilder sb, string indent);
/**
* Visits this type with the given visitor
* @param visitor the visitor to visit this type
*/
abstract public void accept(TypeVisitor visitor);
[Obsolete]
abstract protected int typeHashCode();
[Obsolete]
abstract protected bool typeEquals(Type other);
public override int GetHashCode()
{
int c = repetition.GetHashCode();
c = 31 * c + name.GetHashCode();
if (originalType != null)
{
c = 31 * c + originalType.GetHashCode();
}
if (id != null)
{
c = 31 * c + id.GetHashCode();
}
return c;
}
public virtual bool Equals(Type other)
{
return
name.Equals(other.name)
&& repetition == other.repetition
&& eqOrBothNull(repetition, other.repetition)
&& eqOrBothNull(id, other.id);
}
sealed public override bool Equals(object other)
{
if (!(other is Type) || other == null)
{
return false;
}
return Equals((Type)other);
}
protected bool eqOrBothNull(object o1, object o2)
{
return (o1 == null && o2 == null) || (o1 != null && o1.Equals(o2));
}
internal abstract int getMaxRepetitionLevel(string[] path, int i);
internal abstract int getMaxDefinitionLevel(string[] path, int i);
internal abstract Type getType(string[] path, int i);
internal abstract List<string[]> getPaths(int depth);
internal abstract bool containsPath(string[] path, int depth);
/**
* @param toMerge the type to merge into this one
* @return the union result of merging toMerge into this
*/
internal abstract Type union(Type toMerge);
/**
* @param toMerge the type to merge into this one
* @param strict should schema primitive types match
* @return the union result of merging toMerge into this
*/
internal abstract Type union(Type toMerge, bool strict);
/**
* {@inheritDoc}
*/
public override string ToString()
{
StringBuilder sb = new StringBuilder();
writeToStringBuilder(sb, "");
return sb.ToString();
}
internal virtual void checkContains(Type subType)
{
if (!this.name.Equals(subType.name)
|| this.repetition != subType.repetition)
{
throw new InvalidRecordException(subType + " found: expected " + this);
}
}
/**
*
* @param converter logic to convert the tree
* @return the converted tree
*/
internal abstract T convert<T>(List<GroupType> path, TypeConverter<T> converter);
}
static class TypeHelpers
{
public static bool isMoreRestrictiveThan(this Type.Repetition self, Type.Repetition other)
{
switch (self)
{
case Type.Repetition.REQUIRED:
return other != Type.Repetition.REQUIRED;
case Type.Repetition.OPTIONAL:
return other == Type.Repetition.REPEATED;
case Type.Repetition.REPEATED:
return false;
default:
throw new InvalidOperationException();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.