context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Cache.Query.Continuous
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Resource;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
using CQU = ContinuousQueryUtils;
/// <summary>
/// Continuous query handle interface.
/// </summary>
internal interface IContinuousQueryHandleImpl : IDisposable
{
/// <summary>
/// Process callback.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>Result.</returns>
void Apply(IBinaryStream stream);
}
/// <summary>
/// Continuous query handle.
/// </summary>
internal class ContinuousQueryHandleImpl<TK, TV> : IContinuousQueryHandleImpl, IContinuousQueryFilter,
IContinuousQueryHandle<ICacheEntry<TK, TV>>
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Keep binary flag. */
private readonly bool _keepBinary;
/** Real listener. */
private readonly ICacheEntryEventListener<TK, TV> _lsnr;
/** Real filter. */
private readonly ICacheEntryEventFilter<TK, TV> _filter;
/** GC handle. */
private readonly long _hnd;
/** Native query. */
private readonly IUnmanagedTarget _nativeQry;
/** Initial query cursor. */
private volatile IQueryCursor<ICacheEntry<TK, TV>> _initialQueryCursor;
/** Disposed flag. */
private bool _disposed;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="qry">Query.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="keepBinary">Keep binary flag.</param>
/// <param name="createTargetCb">The initialization callback.</param>
/// <param name="initialQry">The initial query.</param>
public ContinuousQueryHandleImpl(ContinuousQuery<TK, TV> qry, Marshaller marsh, bool keepBinary,
Func<Action<BinaryWriter>, IUnmanagedTarget> createTargetCb, QueryBase initialQry)
{
_marsh = marsh;
_keepBinary = keepBinary;
_lsnr = qry.Listener;
_filter = qry.Filter;
// 1. Inject resources.
ResourceProcessor.Inject(_lsnr, _marsh.Ignite);
ResourceProcessor.Inject(_filter, _marsh.Ignite);
try
{
// 2. Allocate handle.
_hnd = _marsh.Ignite.HandleRegistry.Allocate(this);
// 3. Call Java.
_nativeQry = createTargetCb(writer =>
{
writer.WriteLong(_hnd);
writer.WriteBoolean(qry.Local);
writer.WriteBoolean(_filter != null);
var javaFilter = _filter as PlatformJavaObjectFactoryProxy;
if (javaFilter != null)
{
writer.WriteObject(javaFilter.GetRawProxy());
}
else
{
var filterHolder = _filter == null || qry.Local
? null
: new ContinuousQueryFilterHolder(_filter, _keepBinary);
writer.WriteObject(filterHolder);
}
writer.WriteInt(qry.BufferSize);
writer.WriteLong((long)qry.TimeInterval.TotalMilliseconds);
writer.WriteBoolean(qry.AutoUnsubscribe);
if (initialQry != null)
{
writer.WriteInt((int)initialQry.OpId);
initialQry.Write(writer, _keepBinary);
}
else
writer.WriteInt(-1); // no initial query
});
// 4. Initial query.
var nativeInitialQryCur = UU.TargetOutObject(_nativeQry, 0);
_initialQueryCursor = nativeInitialQryCur == null
? null
: new QueryCursor<TK, TV>(nativeInitialQryCur, _marsh, _keepBinary);
}
catch (Exception)
{
if (_hnd > 0)
_marsh.Ignite.HandleRegistry.Release(_hnd);
if (_nativeQry != null)
_nativeQry.Dispose();
if (_initialQueryCursor != null)
_initialQueryCursor.Dispose();
throw;
}
}
/** <inheritdoc /> */
public void Apply(IBinaryStream stream)
{
ICacheEntryEvent<TK, TV>[] evts = CQU.ReadEvents<TK, TV>(stream, _marsh, _keepBinary);
_lsnr.OnEvent(evts);
}
/** <inheritdoc /> */
public bool Evaluate(IBinaryStream stream)
{
Debug.Assert(_filter != null, "Evaluate should not be called if filter is not set.");
ICacheEntryEvent<TK, TV> evt = CQU.ReadEvent<TK, TV>(stream, _marsh, _keepBinary);
return _filter.Evaluate(evt);
}
/** <inheritdoc /> */
public void Inject(Ignite grid)
{
throw new NotSupportedException("Should not be called.");
}
/** <inheritdoc /> */
public long Allocate()
{
throw new NotSupportedException("Should not be called.");
}
/** <inheritdoc /> */
public void Release()
{
_marsh.Ignite.HandleRegistry.Release(_hnd);
}
/** <inheritdoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> GetInitialQueryCursor()
{
lock (this)
{
if (_disposed)
throw new ObjectDisposedException("Continuous query handle has been disposed.");
var cur = _initialQueryCursor;
if (cur == null)
throw new InvalidOperationException("GetInitialQueryCursor() can be called only once.");
_initialQueryCursor = null;
return cur;
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
Justification = "There is no finalizer.")]
public void Dispose()
{
lock (this)
{
if (_disposed || _nativeQry == null)
return;
try
{
UU.TargetInLongOutLong(_nativeQry, 0, 0);
}
finally
{
_nativeQry.Dispose();
_disposed = true;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Extensions.FileSystemGlobbing;
using NuGet.Common;
using NuGet.Frameworks;
using NuGet.Packaging;
using NuGet.Packaging.Core;
namespace NupkgWrench
{
public static class Util
{
/// <summary>
/// Remove files from a zip
/// </summary>
public static void RemoveFiles(ZipArchive zip, string pathWildcard, ILogger log)
{
var entries = zip.Entries.Where(e => IsMatch(e.FullName, pathWildcard)).ToList();
foreach (var entry in entries)
{
log.LogInformation($"removing : {entry.FullName}");
entry.Delete();
}
}
/// <summary>
/// Fix slashes to match a zip entry.
/// </summary>
public static string GetZipPath(string path)
{
return path.Replace("\\", "/").TrimStart('/');
}
/// <summary>
/// Add or update a root level metadata entry in a nuspec file
/// </summary>
public static void AddOrUpdateMetadataElement(XDocument doc, string name, string value)
{
var metadata = GetMetadataElement(doc);
if (metadata == null)
{
throw new InvalidDataException("Invalid nuspec");
}
var doNotAdd = false;
foreach (var node in metadata.Elements().Where(e => e.Name.LocalName.Equals(name, StringComparison.OrdinalIgnoreCase)).ToArray())
{
if (string.IsNullOrWhiteSpace(value))
{
node.Remove();
doNotAdd = true;
}
else
{
node.SetValue(value);
doNotAdd = true;
}
}
if (!doNotAdd)
{
metadata.Add(new XElement(XName.Get(name.ToLowerInvariant(), metadata.GetDefaultNamespace().NamespaceName), value));
}
}
/// <summary>
/// Get nuspec metadata element
/// </summary>
public static XElement GetMetadataElement(XDocument doc)
{
var package = doc.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("package", StringComparison.OrdinalIgnoreCase));
return package?.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("metadata", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Add or update an xml zip entry
/// </summary>
public static void AddOrReplaceZipEntry(string nupkgPath, string filePath, XDocument doc, ILogger log)
{
using (var stream = new MemoryStream())
{
doc.Save(stream);
AddOrReplaceZipEntry(nupkgPath, filePath, stream, log);
}
}
/// <summary>
/// Add or update a zip entry
/// </summary>
public static void AddOrReplaceZipEntry(string nupkgPath, string filePath, Stream stream, ILogger log)
{
stream.Seek(0, SeekOrigin.Begin);
// Get nuspec file entry
using (var nupkgStream = File.Open(nupkgPath, FileMode.Open, FileAccess.ReadWrite))
using (var zip = new ZipArchive(nupkgStream, ZipArchiveMode.Update))
{
AddOrReplaceZipEntry(zip, nupkgPath, filePath, stream, log);
}
}
public static void AddOrReplaceZipEntry(ZipArchive zip, string nupkgPath, string filePath, Stream stream, ILogger log)
{
stream.Seek(0, SeekOrigin.Begin);
// normalize path
filePath = Util.GetZipPath(filePath);
// Remove existing file
RemoveFiles(zip, filePath, log);
log.LogInformation($"{nupkgPath} : adding {filePath}");
var entry = zip.CreateEntry(filePath, CompressionLevel.Optimal);
using (var entryStream = entry.Open())
{
stream.CopyTo(entryStream);
}
}
/// <summary>
/// Wildcard pattern match
/// </summary>
public static bool IsMatch(string input, string wildcardPattern)
{
if (string.IsNullOrEmpty(wildcardPattern))
{
// Match everything if no pattern was given
return true;
}
var normalizedInput = input.Replace("\\", "/").ToLowerInvariant();
var regexPattern = Regex.Escape(wildcardPattern)
.Replace(@"\*", ".*")
.Replace(@"\?", ".");
// Regex match, ignore case since package ids and versions are case insensitive
return Regex.IsMatch(normalizedInput, $"^{regexPattern}$".ToLowerInvariant());
}
/// <summary>
/// Filter packages down to a single package or throw.
/// </summary>
public static string GetSinglePackageWithFilter(
CommandOption idFilter,
CommandOption versionFilter,
CommandOption excludeSymbols,
CommandOption highestVersionFilter,
string[] inputs)
{
var packages = GetPackagesWithFilter(idFilter,
versionFilter,
excludeSymbols,
highestVersionFilter,
inputs)
.ToArray();
if (packages.Length > 1)
{
var joinString = Environment.NewLine + " - ";
throw new ArgumentException($"This command only works for a single nupkg. The input filters given match multiple nupkgs:{joinString}{string.Join(joinString, packages)}");
}
else if (packages.Length < 1)
{
throw new ArgumentException($"This command only works for a single nupkg. The input filters given match zero nupkgs.");
}
return packages[0];
}
/// <summary>
/// Filter packages
/// </summary>
public static IEnumerable<string> GetPackagesWithFilter(
CommandOption idFilter,
CommandOption versionFilter,
CommandOption excludeSymbols,
CommandOption highestVersionFilter,
string[] inputs)
{
return GetPackagesWithFilter(idFilter.HasValue() ? idFilter.Value() : null,
versionFilter.HasValue() ? versionFilter.Value() : null,
excludeSymbols.HasValue(),
highestVersionFilter.HasValue(),
inputs);
}
/// <summary>
/// Filter packages
/// </summary>
public static SortedSet<string> GetPackagesWithFilter(
string idFilter,
string versionFilter,
bool excludeSymbols,
bool highestVersionFilter,
string[] inputs)
{
var files = GetPackages(inputs);
if (!string.IsNullOrEmpty(idFilter) || !string.IsNullOrEmpty(versionFilter) || excludeSymbols)
{
files.RemoveWhere(path => !IsFilterMatch(idFilter, versionFilter, excludeSymbols, path));
}
if (highestVersionFilter)
{
var identities = GetPathToIdentity(files);
var highestVersions = GetHighestVersionsById(identities);
files = new SortedSet<string>(identities.Where(e => highestVersions.Contains(e.Value)).Select(e => e.Key));
}
return files;
}
private static HashSet<PackageIdentity> GetHighestVersionsById(Dictionary<string, PackageIdentity> identities)
{
var results = new HashSet<PackageIdentity>();
foreach (var group in identities.GroupBy(e => e.Value.Id, StringComparer.OrdinalIgnoreCase))
{
results.Add(group.OrderByDescending(e => e.Value.Version).First().Value);
}
return results;
}
public static Dictionary<string, PackageIdentity> GetPathToIdentity(SortedSet<string> paths)
{
var mappings = new Dictionary<string, PackageIdentity>(StringComparer.Ordinal);
foreach (var path in paths)
{
var identity = GetIdentityOrNull(path);
// Filter out bad packages
if (identity != null)
{
mappings.Add(path, identity);
}
}
return mappings;
}
private static bool IsFilterMatch(string idFilter, string versionFilter, bool excludeSymbols, string path)
{
var identity = GetIdentityOrNull(path);
// Check all forms of the version
if (identity != null
&& IsMatch(identity.Id, idFilter)
&& (IsMatch(identity.Version.ToString(), versionFilter)
|| IsMatch(identity.Version.ToNormalizedString(), versionFilter)
|| IsMatch(identity.Version.ToFullString(), versionFilter))
&& (!excludeSymbols || !path.EndsWith(".symbols.nupkg", StringComparison.OrdinalIgnoreCase)))
{
return true;
}
return false;
}
/// <summary>
/// Convert inputs to a set of nupkg files.
/// </summary>
private static SortedSet<string> GetPackages(params string[] inputs)
{
var files = new SortedSet<string>(StringComparer.Ordinal);
foreach (var input in inputs)
{
if (IsGlobbingPattern(input))
{
// Resolver globbing pattern
files.AddRange(ResolveGlobbingPattern(input));
}
else
{
// Resolve file or directory
var inputFile = Path.GetFullPath(input);
if (Directory.Exists(inputFile))
{
var directoryFiles = Directory.GetFiles(inputFile, "*.nupkg", SearchOption.AllDirectories).ToList();
files.UnionWith(directoryFiles);
}
else if (inputFile.EndsWith(".nupkg", StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(inputFile))
{
files.Add(inputFile);
}
else
{
throw new FileNotFoundException($"Unable to find '{inputFile}'.");
}
}
}
}
return files;
}
private static SortedSet<string> ResolveGlobbingPattern(string pattern)
{
var patternSplit = SplitGlobbingPattern(pattern);
var matcher = new Matcher();
matcher = matcher.AddInclude(patternSplit.Item2);
return new SortedSet<string>(matcher.GetResultsInFullPath(patternSplit.Item1.FullName).Select(Path.GetFullPath), StringComparer.Ordinal);
}
public static Tuple<DirectoryInfo, string> SplitGlobbingPattern(string pattern)
{
var isRooted = IsPathRooted(pattern);
var fullPattern = pattern;
if (!isRooted)
{
// Prefix the current directory if this is a relative path
fullPattern = Directory.GetCurrentDirectory() + "/" + pattern;
}
var parts = fullPattern.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
DirectoryInfo dir = null;
if (parts.Length > 1 && !IsGlobbingPattern(parts[0]))
{
if (Path.DirectorySeparatorChar == '/')
{
// Non-Windows
dir = new DirectoryInfo($"/{parts[0]}/");
}
else
{
// Windows
dir = new DirectoryInfo($"{parts[0]}\\");
}
// Remove the first part
parts = parts.Skip(1).ToArray();
}
else
{
dir = new DirectoryInfo(Directory.GetCurrentDirectory());
}
var relativePattern = string.Empty;
var globbingHit = false;
// Skip the root, it was handled above
for (var i = 0; i < parts.Length; i++)
{
if (globbingHit || IsGlobbingPattern(parts[i]))
{
// Append to pattern
globbingHit = true;
relativePattern = $"{relativePattern}/{parts[i]}";
}
else
{
// Append to root dir
dir = new DirectoryInfo(Path.Combine(dir.FullName, parts[i]));
}
}
return new Tuple<DirectoryInfo, string>(dir, relativePattern);
}
private static bool IsGlobbingPattern(string possiblePattern)
{
return possiblePattern.IndexOf("*") > -1;
}
private static bool IsPathRooted(string possiblePattern)
{
if (Path.DirectorySeparatorChar == '/')
{
// Non-windows, Verify starts with a /
return possiblePattern.StartsWith("/");
}
else
{
// Windows, Verify a : comes before a slash
return possiblePattern.IndexOfAny(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar })
> possiblePattern.IndexOf(':');
}
}
public static PackageIdentity GetIdentityOrNull(string path)
{
try
{
if (File.Exists(path))
{
using (var reader = new PackageArchiveReader(path))
{
return reader.GetIdentity();
}
}
}
catch
{
// Ignore bad packages, these might be only partially written to disk.
Debug.Fail("Failed to get identity");
}
return null;
}
/// <summary>
/// Get a nuspec file
/// </summary>
public static XDocument GetNuspec(string nupkgPath)
{
using (var packageReader = new PackageArchiveReader(nupkgPath))
{
return packageReader.NuspecReader.Xml;
}
}
/// <summary>
/// Replace a nuspec file
/// </summary>
public static void ReplaceNuspec(string nupkgPath, XDocument nuspecXml, ILogger log)
{
// Verify that the nuspec is valid
var nuspecReader = new NuspecReader(nuspecXml);
string nuspecPath;
using (var packageReader = new PackageArchiveReader(nupkgPath))
{
nuspecPath = packageReader.GetNuspecFile();
}
Util.AddOrReplaceZipEntry(nupkgPath, nuspecPath, nuspecXml, log);
}
/// <summary>
/// Build the nupkg file name.
/// </summary>
public static string GetNupkgName(PackageIdentity identity, bool isSymbolPackage)
{
var name = $"{identity.Id}.{identity.Version.ToString()}";
if (isSymbolPackage)
{
name += ".symbols";
}
name += ".nupkg";
return name;
}
/// <summary>
/// True if the package ends with .symbols.nupkg
/// </summary>
public static bool IsSymbolPackage(string path)
{
return path?.EndsWith(".symbols.nupkg", StringComparison.OrdinalIgnoreCase) == true;
}
public static void AddFrameworkAssemblyReferences(XDocument nuspecXml, HashSet<string> assemblyNames, HashSet<NuGetFramework> frameworks)
{
// Read nuspec
var metadata = Util.GetMetadataElement(nuspecXml);
var ns = metadata.Name.NamespaceName;
var assembliesRoot = metadata.Elements()
.Where(e => e.Name.LocalName.Equals("frameworkAssemblies", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault();
if (assembliesRoot == null)
{
assembliesRoot = new XElement(XName.Get("frameworkAssemblies", ns));
metadata.Add(assembliesRoot);
}
foreach (var assemblyName in assemblyNames)
{
AddFrameworkAssemblyReference(frameworks, assembliesRoot, assemblyName);
}
}
public static void AddFrameworkAssemblyReference(HashSet<NuGetFramework> frameworks, XElement assembliesRoot, string assemblyName)
{
var ns = assembliesRoot.Name.NamespaceName;
var assemblyElement = GetAssemblyElement(assembliesRoot, assemblyName);
if (assemblyElement == null)
{
assemblyElement = new XElement(XName.Get("frameworkAssembly", ns), new XAttribute("assemblyName", assemblyName));
assembliesRoot.Add(assemblyElement);
}
var tfmAttribute = assemblyElement.Attributes().FirstOrDefault(e => e.Name.LocalName.Equals("targetFramework", StringComparison.OrdinalIgnoreCase));
if (tfmAttribute == null)
{
tfmAttribute = new XAttribute(XName.Get("targetFramework"), string.Empty);
assemblyElement.Add(tfmAttribute);
}
// Get existing frameworks
var currentFrameworks = new HashSet<NuGetFramework>(tfmAttribute.Value.Split(',')
.Select(e => e.Trim())
.Where(e => !string.IsNullOrEmpty(e))
.Select(NuGetFramework.Parse));
// Add input frameworks
if (frameworks.Any())
{
currentFrameworks.UnionWith(frameworks);
tfmAttribute.SetValue(string.Join(",", currentFrameworks.Select(e => e.GetShortFolderName())));
}
else
{
tfmAttribute.Remove();
}
}
public static XElement GetAssemblyElement(XElement assembliesRoot, string assemblyName)
{
XElement assemblyElement = null;
foreach (var element in assembliesRoot.Elements())
{
var name = element.Attribute(XName.Get("assemblyName"));
if (StringComparer.OrdinalIgnoreCase.Equals(assemblyName, name?.Value))
{
assemblyElement = element;
}
}
return assemblyElement;
}
/// <summary>
/// /usr/home/blah.txt -> /usr/home/blah
/// </summary>
public static string RemoveFileExtensionFromPath(string path)
{
var ext = Path.GetExtension(path);
if (path.Length > ext.Length)
{
return path.Substring(0, path.Length - ext.Length);
}
return path;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcav = Google.Cloud.AssuredWorkloads.V1Beta1;
using sys = System;
namespace Google.Cloud.AssuredWorkloads.V1Beta1
{
/// <summary>Resource name for the <c>Workload</c> resource.</summary>
public sealed partial class WorkloadName : gax::IResourceName, sys::IEquatable<WorkloadName>
{
/// <summary>The possible contents of <see cref="WorkloadName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>
/// .
/// </summary>
OrganizationLocationWorkload = 1,
}
private static gax::PathTemplate s_organizationLocationWorkload = new gax::PathTemplate("organizations/{organization}/locations/{location}/workloads/{workload}");
/// <summary>Creates a <see cref="WorkloadName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="WorkloadName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static WorkloadName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new WorkloadName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="WorkloadName"/> with the pattern
/// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workloadId">The <c>Workload</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="WorkloadName"/> constructed from the provided ids.</returns>
public static WorkloadName FromOrganizationLocationWorkload(string organizationId, string locationId, string workloadId) =>
new WorkloadName(ResourceNameType.OrganizationLocationWorkload, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workloadId: gax::GaxPreconditions.CheckNotNullOrEmpty(workloadId, nameof(workloadId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkloadName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workloadId">The <c>Workload</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkloadName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>.
/// </returns>
public static string Format(string organizationId, string locationId, string workloadId) =>
FormatOrganizationLocationWorkload(organizationId, locationId, workloadId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkloadName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workloadId">The <c>Workload</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkloadName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>.
/// </returns>
public static string FormatOrganizationLocationWorkload(string organizationId, string locationId, string workloadId) =>
s_organizationLocationWorkload.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(workloadId, nameof(workloadId)));
/// <summary>Parses the given resource name string into a new <see cref="WorkloadName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>organizations/{organization}/locations/{location}/workloads/{workload}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="workloadName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="WorkloadName"/> if successful.</returns>
public static WorkloadName Parse(string workloadName) => Parse(workloadName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="WorkloadName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>organizations/{organization}/locations/{location}/workloads/{workload}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workloadName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="WorkloadName"/> if successful.</returns>
public static WorkloadName Parse(string workloadName, bool allowUnparsed) =>
TryParse(workloadName, allowUnparsed, out WorkloadName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkloadName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>organizations/{organization}/locations/{location}/workloads/{workload}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="workloadName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkloadName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string workloadName, out WorkloadName result) => TryParse(workloadName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkloadName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>organizations/{organization}/locations/{location}/workloads/{workload}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workloadName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkloadName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string workloadName, bool allowUnparsed, out WorkloadName result)
{
gax::GaxPreconditions.CheckNotNull(workloadName, nameof(workloadName));
gax::TemplatedResourceName resourceName;
if (s_organizationLocationWorkload.TryParseName(workloadName, out resourceName))
{
result = FromOrganizationLocationWorkload(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(workloadName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private WorkloadName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string organizationId = null, string workloadId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
OrganizationId = organizationId;
WorkloadId = workloadId;
}
/// <summary>
/// Constructs a new instance of a <see cref="WorkloadName"/> class from the component parts of pattern
/// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workloadId">The <c>Workload</c> ID. Must not be <c>null</c> or empty.</param>
public WorkloadName(string organizationId, string locationId, string workloadId) : this(ResourceNameType.OrganizationLocationWorkload, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workloadId: gax::GaxPreconditions.CheckNotNullOrEmpty(workloadId, nameof(workloadId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Organization</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Workload</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string WorkloadId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.OrganizationLocationWorkload: return s_organizationLocationWorkload.Expand(OrganizationId, LocationId, WorkloadId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as WorkloadName);
/// <inheritdoc/>
public bool Equals(WorkloadName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(WorkloadName a, WorkloadName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(WorkloadName a, WorkloadName b) => !(a == b);
}
/// <summary>Resource name for the <c>Location</c> resource.</summary>
public sealed partial class LocationName : gax::IResourceName, sys::IEquatable<LocationName>
{
/// <summary>The possible contents of <see cref="LocationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>organizations/{organization}/locations/{location}</c>.
/// </summary>
OrganizationLocation = 1,
}
private static gax::PathTemplate s_organizationLocation = new gax::PathTemplate("organizations/{organization}/locations/{location}");
/// <summary>Creates a <see cref="LocationName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="LocationName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static LocationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new LocationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="LocationName"/> with the pattern <c>organizations/{organization}/locations/{location}</c>
/// .
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="LocationName"/> constructed from the provided ids.</returns>
public static LocationName FromOrganizationLocation(string organizationId, string locationId) =>
new LocationName(ResourceNameType.OrganizationLocation, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="LocationName"/> with pattern
/// <c>organizations/{organization}/locations/{location}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="LocationName"/> with pattern
/// <c>organizations/{organization}/locations/{location}</c>.
/// </returns>
public static string Format(string organizationId, string locationId) =>
FormatOrganizationLocation(organizationId, locationId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="LocationName"/> with pattern
/// <c>organizations/{organization}/locations/{location}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="LocationName"/> with pattern
/// <c>organizations/{organization}/locations/{location}</c>.
/// </returns>
public static string FormatOrganizationLocation(string organizationId, string locationId) =>
s_organizationLocation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)));
/// <summary>Parses the given resource name string into a new <see cref="LocationName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/locations/{location}</c></description></item>
/// </list>
/// </remarks>
/// <param name="locationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="LocationName"/> if successful.</returns>
public static LocationName Parse(string locationName) => Parse(locationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="LocationName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/locations/{location}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="locationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="LocationName"/> if successful.</returns>
public static LocationName Parse(string locationName, bool allowUnparsed) =>
TryParse(locationName, allowUnparsed, out LocationName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="LocationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/locations/{location}</c></description></item>
/// </list>
/// </remarks>
/// <param name="locationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="LocationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string locationName, out LocationName result) => TryParse(locationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="LocationName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/locations/{location}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="locationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="LocationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string locationName, bool allowUnparsed, out LocationName result)
{
gax::GaxPreconditions.CheckNotNull(locationName, nameof(locationName));
gax::TemplatedResourceName resourceName;
if (s_organizationLocation.TryParseName(locationName, out resourceName))
{
result = FromOrganizationLocation(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(locationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private LocationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string organizationId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
OrganizationId = organizationId;
}
/// <summary>
/// Constructs a new instance of a <see cref="LocationName"/> class from the component parts of pattern
/// <c>organizations/{organization}/locations/{location}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
public LocationName(string organizationId, string locationId) : this(ResourceNameType.OrganizationLocation, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Organization</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string OrganizationId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.OrganizationLocation: return s_organizationLocation.Expand(OrganizationId, LocationId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as LocationName);
/// <inheritdoc/>
public bool Equals(LocationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(LocationName a, LocationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(LocationName a, LocationName b) => !(a == b);
}
public partial class CreateWorkloadRequest
{
/// <summary>
/// <see cref="LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteWorkloadRequest
{
/// <summary>
/// <see cref="gcav::WorkloadName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::WorkloadName WorkloadName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::WorkloadName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetWorkloadRequest
{
/// <summary>
/// <see cref="gcav::WorkloadName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::WorkloadName WorkloadName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::WorkloadName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListWorkloadsRequest
{
/// <summary>
/// <see cref="LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class Workload
{
/// <summary>
/// <see cref="gcav::WorkloadName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::WorkloadName WorkloadName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::WorkloadName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BlendVariableSingle()
{
var test = new SimpleTernaryOpTest__BlendVariableSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__BlendVariableSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Single> _fld2;
public Vector256<Single> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (float)(((i % 2) == 0) ? -0.0 : 1.0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableSingle testClass)
{
var result = Avx.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableSingle testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
fixed (Vector256<Single>* pFld3 = &_fld3)
{
var result = Avx.BlendVariable(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Single[] _data3 = new Single[Op3ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private static Vector256<Single> _clsVar3;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private Vector256<Single> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__BlendVariableSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (float)(((i % 2) == 0) ? -0.0 : 1.0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleTernaryOpTest__BlendVariableSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (float)(((i % 2) == 0) ? -0.0 : 1.0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (float)(((i % 2) == 0) ? -0.0 : 1.0); }
_dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.BlendVariable(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.BlendVariable(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.BlendVariable(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.BlendVariable), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.BlendVariable), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.BlendVariable), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
fixed (Vector256<Single>* pClsVar2 = &_clsVar2)
fixed (Vector256<Single>* pClsVar3 = &_clsVar3)
{
var result = Avx.BlendVariable(
Avx.LoadVector256((Single*)(pClsVar1)),
Avx.LoadVector256((Single*)(pClsVar2)),
Avx.LoadVector256((Single*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr);
var result = Avx.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr));
var result = Avx.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr));
var result = Avx.BlendVariable(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__BlendVariableSingle();
var result = Avx.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__BlendVariableSingle();
fixed (Vector256<Single>* pFld1 = &test._fld1)
fixed (Vector256<Single>* pFld2 = &test._fld2)
fixed (Vector256<Single>* pFld3 = &test._fld3)
{
var result = Avx.BlendVariable(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
fixed (Vector256<Single>* pFld3 = &_fld3)
{
var result = Avx.BlendVariable(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2)),
Avx.LoadVector256((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.BlendVariable(
Avx.LoadVector256((Single*)(&test._fld1)),
Avx.LoadVector256((Single*)(&test._fld2)),
Avx.LoadVector256((Single*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, Vector256<Single> op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (((BitConverter.SingleToInt32Bits(thirdOp[0]) >> 31) & 1) == 1 ? BitConverter.SingleToInt32Bits(secondOp[0]) != BitConverter.SingleToInt32Bits(result[0]) : BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (((BitConverter.SingleToInt32Bits(thirdOp[i]) >> 31) & 1) == 1 ? BitConverter.SingleToInt32Bits(secondOp[i]) != BitConverter.SingleToInt32Bits(result[i]) : BitConverter.SingleToInt32Bits(firstOp[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.BlendVariable)}<Single>(Vector256<Single>, Vector256<Single>, Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="MeshOcclusionUIController.cs" company="Google">
//
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Collections;
using System.IO;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using Tango;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// Occlusion test controller.
/// </summary>
public class MeshOcclusionUIController : MonoBehaviour, ITangoLifecycle, ITangoPose
{
/// <summary>
/// The object that is used to test occlusion.
/// </summary>
[Header("Marker Objects")]
public GameObject m_markerObject;
/// <summary>
/// The canvas panel used during mesh construction.
/// </summary>
[Header("UI Elements")]
public GameObject m_meshBuildPanel;
/// <summary>
/// The canvas panel used for interaction after Area Description and mesh have been loaded.
/// </summary>
public GameObject m_meshInteractionPanel;
/// <summary>
/// The canvas button that changes the mesh to a visible material.
/// </summary>
public GameObject m_viewMeshButton;
/// <summary>
/// The canvas button that change the mesh to depth mask.
/// </summary>
public GameObject m_hideMeshButton;
/// <summary>
/// The image overlay shown while waiting to relocalize to Area Description.
/// </summary>
public Image m_relocalizeImage;
/// <summary>
/// The text overlay that is shown when the Area Description or mesh is being saved.
/// </summary>
public Text m_savingText;
/// <summary>
/// The button to create new mesh with selected Area Description, available only if an Area Description is selected.
/// </summary>
public Button m_createSelectedButton;
/// <summary>
/// The button to begin using an Area Description and mesh. Interactable only when an Area Description with mesh is selected.
/// </summary>
public Button m_startGameButton;
/// <summary>
/// The parent panel that loads the selected Area Description.
/// </summary>
[Header("Area Description Loader")]
public GameObject m_areaDescriptionLoaderPanel;
/// <summary>
/// The prefab of a standard button in the scrolling list.
/// </summary>
public GameObject m_listElement;
/// <summary>
/// The container panel of the Tango space Area Description scrolling list.
/// </summary>
public RectTransform m_listContentParent;
/// <summary>
/// Toggle group for the Area Description list.
///
/// You can only toggle one Area Description at a time. After we get the list of Area Description from Tango,
/// they are all added to this toggle group.
/// </summary>
public ToggleGroup m_toggleGroup;
/// <summary>
/// The reference to the depth mask material to be applied to the mesh.
/// </summary>
[Header("Materials")]
public Material m_depthMaskMat;
/// <summary>
/// The reference to the visible material applied to the mesh.
/// </summary>
public Material m_visibleMat;
/// <summary>
/// The tango dynamic mesh used for occlusion.
/// </summary>
private TangoDynamicMesh m_tangoDynamicMesh;
/// <summary>
/// The loaded mesh reconstructed from the serialized AreaDescriptionMesh file.
/// </summary>
private GameObject m_meshFromFile;
/// <summary>
/// The Area Description currently loaded in the Tango Service.
/// </summary>
private AreaDescription m_curAreaDescription;
/// <summary>
/// The AR pose controller.
/// </summary>
private TangoARPoseController m_arPoseController;
/// <summary>
/// The tango application, to create and clear 3d construction.
/// </summary>
private TangoApplication m_tangoApplication;
/// <summary>
/// The thread used to save the Area Description.
/// </summary>
private Thread m_saveThread;
/// <summary>
/// If the interaction is initialized.
///
/// Note that the initialization is triggered by the relocalization event. We don't want user to place object before
/// the device is relocalized.
/// </summary>
private bool m_initialized = false;
/// <summary>
/// The check whether user has selected to create a new mesh or start the game with an existing one.
/// </summary>
private bool m_3dReconstruction = false;
/// <summary>
/// The check whether the menu is currently open. Determines the back button behavior.
/// </summary>
private bool m_menuOpen = true;
/// <summary>
/// The UUID of the selected Area Description.
/// </summary>
private string m_savedUUID;
/// <summary>
/// The path where the generated meshes are saved.
/// </summary>
private string m_meshSavePath;
/// <summary>
/// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
/// </summary>
public void Start()
{
m_meshSavePath = Application.persistentDataPath + "/meshes";
Directory.CreateDirectory(m_meshSavePath);
m_arPoseController = FindObjectOfType<TangoARPoseController>();
m_tangoDynamicMesh = FindObjectOfType<TangoDynamicMesh>();
m_areaDescriptionLoaderPanel.SetActive(true);
m_meshBuildPanel.SetActive(false);
m_meshInteractionPanel.SetActive(false);
m_relocalizeImage.gameObject.SetActive(false);
// Initialize tango application.
m_tangoApplication = FindObjectOfType<TangoApplication>();
if (m_tangoApplication != null)
{
m_tangoApplication.Register(this);
if (AndroidHelper.IsTangoCorePresent())
{
m_tangoApplication.RequestPermissions();
}
}
}
/// <summary>
/// Update is called once per frame.
/// Return to menu or quit current application when back button is triggered.
/// </summary>
public void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
if (m_menuOpen)
{
Application.Quit();
}
else
{
#pragma warning disable 618
Application.LoadLevel(Application.loadedLevel);
#pragma warning restore 618
}
}
}
/// <summary>
/// Application onPause / onResume callback.
/// </summary>
/// <param name="pauseStatus"><c>true</c> if the application about to pause, otherwise <c>false</c>.</param>
public void OnApplicationPause(bool pauseStatus)
{
if (pauseStatus && m_initialized)
{
// When application is backgrounded, we reload the level because the Tango Service is disconected. All
// learned area and placed marker should be discarded as they are not saved.
#pragma warning disable 618
Application.LoadLevel(Application.loadedLevel);
#pragma warning restore 618
}
}
/// <summary>
/// Unity destroy function.
/// </summary>
public void OnDestroy()
{
if (m_tangoApplication != null)
{
m_tangoApplication.Unregister(this);
}
}
/// <summary>
/// Internal callback when a permissions event happens.
/// </summary>
/// <param name="permissionsGranted">If set to <c>true</c> permissions granted.</param>
public void OnTangoPermissions(bool permissionsGranted)
{
if (permissionsGranted)
{
m_tangoApplication.Set3DReconstructionEnabled(false);
m_arPoseController.gameObject.SetActive(false);
_PopulateAreaDescriptionUIList();
}
else
{
AndroidHelper.ShowAndroidToastMessage("Motion Tracking and Area Learning Permissions Needed");
Application.Quit();
}
}
/// <summary>
/// This is called when successfully connected to the Tango service.
/// </summary>
public void OnTangoServiceConnected()
{
}
/// <summary>
/// This is called when disconnected from the Tango service.
/// </summary>
public void OnTangoServiceDisconnected()
{
}
/// <summary>
/// OnTangoPoseAvailable event from Tango.
///
/// In this function, we only listen to the Start-Of-Service with respect to Area-Description frame pair. This pair
/// indicates a relocalization or loop closure event happened, base on that, we either start the initialize the
/// interaction or begin meshing if applicable.
/// </summary>
/// <param name="poseData">Returned pose data from TangoService.</param>
public void OnTangoPoseAvailable(Tango.TangoPoseData poseData)
{
// This frame pair's callback indicates that a loop closure or relocalization has happened.
//
// When learning mode is off, and an Area Description is loaded, this callback indicates a relocalization event.
// In our case, when the device is relocalized, user interaction is allowed and meshing starts if applicable.
if (poseData.framePair.baseFrame ==
TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION &&
poseData.framePair.targetFrame ==
TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE &&
poseData.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID)
{
// When we get the first loop closure/ relocalization event, we initialized all the in-game interactions.
if (!m_initialized)
{
Debug.Log("First loop closure/relocalization");
m_initialized = true;
m_relocalizeImage.gameObject.SetActive(false);
if (m_3dReconstruction)
{
m_tangoApplication.Set3DReconstructionEnabled(true);
}
else
{
m_tangoApplication.Set3DReconstructionEnabled(false);
}
}
}
}
/// <summary>
/// From button press: start creating a mesh for occlusion.
///
/// If an Area Description has been selected, use it and link it to the dynamic mesh.
/// If no Area Description selected, create one while meshing.
/// </summary>
/// <param name="createNew">If set to <c>true</c> create new mesh and new Area Description.</param>
public void Button_CreateAreaDescriptionMesh(bool createNew)
{
m_3dReconstruction = true;
m_menuOpen = false;
// Enable the pose controller, but disable the AR screen.
m_arPoseController.gameObject.SetActive(true);
m_arPoseController.gameObject.GetComponent<TangoARScreen>().enabled = false;
// Need to enable depth to build the mesh.
m_tangoApplication.m_enableDepth = true;
// Set UI panel to the mesh construction panel.
m_areaDescriptionLoaderPanel.SetActive(false);
m_meshBuildPanel.SetActive(true);
m_meshInteractionPanel.SetActive(false);
// Initialize tango application and pose controller depending on whether Area Description has been selected.
if (createNew)
{
m_curAreaDescription = null;
m_tangoApplication.m_areaDescriptionLearningMode = true;
m_arPoseController.m_useAreaDescriptionPose = false;
m_relocalizeImage.gameObject.SetActive(false);
m_tangoApplication.Startup(null);
}
else
{
if (!string.IsNullOrEmpty(m_savedUUID))
{
m_curAreaDescription = AreaDescription.ForUUID(m_savedUUID);
m_tangoApplication.m_areaDescriptionLearningMode = false;
m_arPoseController.m_useAreaDescriptionPose = true;
m_relocalizeImage.gameObject.SetActive(true);
m_tangoApplication.Startup(m_curAreaDescription);
}
else
{
Debug.LogError("No Area Description loaded.");
}
}
}
/// <summary>
/// From button press: start the game by loading the mesh and the Area Description.
///
/// Generate a new mesh from the saved area definition mesh data linked to the selected Area Description.
/// </summary>
public void Button_StartAreaDescriptionMesh()
{
if (string.IsNullOrEmpty(m_savedUUID))
{
AndroidHelper.ShowAndroidToastMessage("Please choose an Area Description.");
return;
}
if (!File.Exists(m_meshSavePath + "/" + m_savedUUID))
{
AndroidHelper.ShowAndroidToastMessage("Please choose an Area Description with mesh data.");
return;
}
m_3dReconstruction = false;
m_menuOpen = false;
// Enable objects needed to use Area Description and mesh for occlusion.
m_arPoseController.gameObject.SetActive(true);
m_arPoseController.m_useAreaDescriptionPose = true;
// Disable unused components in tango application.
m_tangoApplication.m_areaDescriptionLearningMode = false;
m_tangoApplication.m_enableDepth = false;
// Set UI panel to the mesh interaction panel.
m_relocalizeImage.gameObject.SetActive(true);
m_areaDescriptionLoaderPanel.SetActive(false);
m_meshBuildPanel.SetActive(false);
m_meshInteractionPanel.SetActive(true);
// Load mesh.
AreaDescriptionMesh mesh = _DeserializeAreaDescriptionMesh(m_savedUUID);
if (mesh == null)
{
return;
}
// Create GameObject container with mesh components for the loaded mesh.
m_meshFromFile = new GameObject();
MeshFilter mf = m_meshFromFile.AddComponent<MeshFilter>();
mf.mesh = _AreaDescriptionMeshToUnityMesh(mesh);
MeshRenderer mr = m_meshFromFile.AddComponent<MeshRenderer>();
mr.material = m_depthMaskMat;
m_meshFromFile.AddComponent<MeshCollider>();
m_meshFromFile.layer = LayerMask.NameToLayer("Occlusion");
// Load Area Description file.
m_curAreaDescription = AreaDescription.ForUUID(m_savedUUID);
m_tangoApplication.Startup(m_curAreaDescription);
}
/// <summary>
/// From button press: delete all saved meshes associated with area definitions.
/// </summary>
public void Button_DeleteAllAreaDescriptionMeshes()
{
string[] filePaths = Directory.GetFiles(m_meshSavePath);
foreach (string filePath in filePaths)
{
File.Delete(filePath);
}
AndroidHelper.ShowAndroidToastMessage("All Area Description meshes have been deleted.");
#pragma warning disable 618
Application.LoadLevel(Application.loadedLevel);
#pragma warning restore 618
}
/// <summary>
/// Clear the 3D mesh on canvas button press.
/// </summary>
public void Button_Clear()
{
m_tangoDynamicMesh.Clear();
m_tangoApplication.Tango3DRClear();
AndroidHelper.ShowAndroidToastMessage("Mesh cleared.");
}
/// <summary>
/// Finalize the 3D mesh on canvas button press.
/// </summary>
public void Button_Finalize()
{
m_tangoApplication.Set3DReconstructionEnabled(false);
m_meshBuildPanel.SetActive(false);
m_savingText.gameObject.SetActive(true);
StartCoroutine(_DoSaveAreaDescriptionAndMesh());
}
/// <summary>
/// Set the marker object at the raycast location when the user has interacted with the image overlay.
/// </summary>
/// <param name="data">Event data from canvas event trigger.</param>
public void Image_PlaceMarker(BaseEventData data)
{
PointerEventData pdata = (PointerEventData)data;
// Place marker object at target point hit by raycast.
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(pdata.position), out hit, Mathf.Infinity))
{
m_markerObject.SetActive(true);
m_markerObject.transform.position = hit.point;
m_markerObject.transform.up = hit.normal;
}
}
/// <summary>
/// Show the mesh as visible.
/// </summary>
public void Button_ViewMesh()
{
m_meshFromFile.GetComponent<MeshRenderer>().material = m_visibleMat;
m_viewMeshButton.SetActive(false);
m_hideMeshButton.SetActive(true);
}
/// <summary>
/// Set the mesh as masked.
/// </summary>
public void Button_HideMesh()
{
m_meshFromFile.GetComponent<MeshRenderer>().material = m_depthMaskMat;
m_viewMeshButton.SetActive(true);
m_hideMeshButton.SetActive(false);
}
/// <summary>
/// Exit the game and return to mesh selection.
/// </summary>
public void Button_Exit()
{
#pragma warning disable 618
Application.LoadLevel(Application.loadedLevel);
#pragma warning restore 618
}
/// <summary>
/// Populate a scrolling list with Area Descriptions. Each element will check if there is any associated
/// mesh data tied to the Area Description by UUID. The Area Description file and linked mesh data are
/// loaded when starting the game.
/// </summary>
private void _PopulateAreaDescriptionUIList()
{
// Load Area Descriptions.
foreach (Transform t in m_listContentParent.transform)
{
Destroy(t.gameObject);
}
// Update Tango space Area Description list.
AreaDescription[] areaDescriptionList = AreaDescription.GetList();
if (areaDescriptionList == null)
{
return;
}
foreach (AreaDescription areaDescription in areaDescriptionList)
{
GameObject newElement = Instantiate(m_listElement) as GameObject;
MeshOcclusionAreaDescriptionListElement listElement = newElement.GetComponent<MeshOcclusionAreaDescriptionListElement>();
listElement.m_toggle.group = m_toggleGroup;
listElement.m_areaDescriptionName.text = areaDescription.GetMetadata().m_name;
listElement.m_areaDescriptionUUID.text = areaDescription.m_uuid;
// Check if there is an associated Area Description mesh.
bool hasMeshData = File.Exists(m_meshSavePath + "/" + areaDescription.m_uuid) ? true : false;
listElement.m_hasMeshData.gameObject.SetActive(hasMeshData);
// Ensure the lambda makes a copy of areaDescription.
AreaDescription lambdaParam = areaDescription;
listElement.m_toggle.onValueChanged.AddListener((value) => _OnToggleChanged(lambdaParam, value));
newElement.transform.SetParent(m_listContentParent.transform, false);
}
}
/// <summary>
/// Callback function when toggle button is selected.
/// </summary>
/// <param name="item">Caller item object.</param>
/// <param name="value">Selected value of the toggle button.</param>
private void _OnToggleChanged(AreaDescription item, bool value)
{
if (value)
{
m_savedUUID = item.m_uuid;
m_createSelectedButton.interactable = true;
if (File.Exists(m_meshSavePath + "/" + item.m_uuid))
{
m_startGameButton.interactable = true;
}
else
{
m_startGameButton.interactable = false;
}
}
else
{
m_savedUUID = null;
m_createSelectedButton.interactable = false;
m_startGameButton.interactable = false;
}
}
/// <summary>
/// Actually do the Area Description save.
/// </summary>
/// <returns>Coroutine IEnumerator.</returns>
private IEnumerator _DoSaveAreaDescriptionAndMesh()
{
if (m_saveThread != null)
{
yield break;
}
// Disable interaction before saving.
m_initialized = false;
m_savingText.text = "Saving Area Description...";
if (string.IsNullOrEmpty(m_savedUUID))
{
m_saveThread = new Thread(delegate()
{
// Save the Area Description to file.
m_curAreaDescription = AreaDescription.SaveCurrent();
AreaDescription.Metadata metadata = m_curAreaDescription.GetMetadata();
m_savedUUID = m_curAreaDescription.m_uuid;
metadata.m_name = metadata.m_dateTime.ToLongTimeString();
m_curAreaDescription.SaveMetadata(metadata);
// Save the tango dynamic mesh to file.
StartCoroutine(_DoSaveTangoDynamicMesh());
});
m_saveThread.Start();
}
else
{
StartCoroutine(_DoSaveTangoDynamicMesh());
}
}
/// <summary>
/// Save the tango dynamic mesh.
///
/// Process the mesh in 3 steps.
/// 1. Extract the whole mesh from tango 3D Reconstruction.
/// 2. Convert to a serializable format.
/// 3. Serialize with XML on to the SD card.
/// </summary>
/// <returns>The coroutine IEnumerator.</returns>
private IEnumerator _DoSaveTangoDynamicMesh()
{
m_savingText.gameObject.SetActive(true);
m_savingText.text = "Extracting Whole Mesh...";
Tango3DReconstruction.Status status = Tango3DReconstruction.Status.INVALID;
bool needsToGrow = false;
float growthFactor = 1.5f;
// Each list is filled out with values from extracting the whole mesh.
Vector3[] vertices = new Vector3[100];
int[] triangles = new int[99];
while (status != Tango3DReconstruction.Status.SUCCESS)
{
yield return null;
// Last frame the mesh needed more space. Give it more room now.
if (needsToGrow)
{
int newVertexSize = (int)(vertices.Length * growthFactor);
int newTriangleSize = (int)(triangles.Length * growthFactor);
newTriangleSize -= newTriangleSize % 3;
vertices = new Vector3[newVertexSize];
triangles = new int[newTriangleSize];
needsToGrow = false;
}
int numVertices;
int numTriangles;
status = m_tangoApplication.Tango3DRExtractWholeMesh(vertices, null, null, triangles, out numVertices, out numTriangles);
if (status != Tango3DReconstruction.Status.INSUFFICIENT_SPACE
&& status != Tango3DReconstruction.Status.SUCCESS)
{
Debug.Log("Tango3DRExtractWholeMesh failed, status code = " + status);
break;
}
else if (status == Tango3DReconstruction.Status.INSUFFICIENT_SPACE)
{
// After exceeding allocated space for vertices and triangles, continue extraction next frame.
Debug.Log(string.Format("Tango3DRExtractWholeMesh ran out of space with room for {0} vertexes, {1} indexes.", vertices.Length, triangles.Length));
needsToGrow = true;
}
// Make any leftover triangles degenerate.
for (int triangleIt = numTriangles * 3; triangleIt < triangles.Length; ++triangleIt)
{
triangles[triangleIt] = 0;
}
}
Debug.Log("Tango3DRExtractWholeMesh finished");
Mesh extractedMesh = new Mesh();
extractedMesh.vertices = vertices;
extractedMesh.triangles = triangles;
// Save the generated unity mesh.
m_savingText.text = "Saving Area Description Mesh...";
AreaDescriptionMesh mesh = _UnityMeshToAreaDescriptionMesh(m_savedUUID, extractedMesh);
_SerializeAreaDescriptionMesh(mesh);
// Restart scene after completion.
#pragma warning disable 618
Application.LoadLevel(Application.loadedLevel);
#pragma warning restore 618
}
/// <summary>
/// Convert a unity mesh to an Area Description mesh.
/// </summary>
/// <returns>The Area Description mesh.</returns>
/// <param name="uuid">The Area Description UUID.</param>
/// <param name="mesh">The Unity mesh.</param>
private AreaDescriptionMesh _UnityMeshToAreaDescriptionMesh(string uuid, Mesh mesh)
{
AreaDescriptionMesh saveMesh = new AreaDescriptionMesh();
saveMesh.m_uuid = m_savedUUID;
saveMesh.m_vertices = mesh.vertices;
saveMesh.m_triangles = mesh.triangles;
return saveMesh;
}
/// <summary>
/// Convert an Area Description mesh to a unity mesh.
/// </summary>
/// <returns>The unity mesh.</returns>
/// <param name="saveMesh">The Area Description mesh.</param>
private Mesh _AreaDescriptionMeshToUnityMesh(AreaDescriptionMesh saveMesh)
{
Mesh mesh = new Mesh();
mesh.vertices = saveMesh.m_vertices;
mesh.triangles = saveMesh.m_triangles;
mesh.RecalculateNormals();
return mesh;
}
/// <summary>
/// Serialize an Area Description mesh to file.
/// </summary>
/// <param name="saveMesh">The Area Description mesh to serialize.</param>
private void _SerializeAreaDescriptionMesh(AreaDescriptionMesh saveMesh)
{
XmlSerializer serializer = new XmlSerializer(typeof(AreaDescriptionMesh));
FileStream file = File.Create(m_meshSavePath + "/" + saveMesh.m_uuid);
serializer.Serialize(file, saveMesh);
file.Close();
}
/// <summary>
/// Deserialize an Area Description mesh from file.
/// </summary>
/// <returns>The loaded Area Description mesh.</returns>
/// <param name="uuid">The UUID of the associated Area Description.</param>
private AreaDescriptionMesh _DeserializeAreaDescriptionMesh(string uuid)
{
if (File.Exists(m_meshSavePath + "/" + uuid))
{
XmlSerializer serializer = new XmlSerializer(typeof(AreaDescriptionMesh));
FileStream file = File.Open(m_meshSavePath + "/" + uuid, FileMode.Open);
AreaDescriptionMesh saveMesh = serializer.Deserialize(file) as AreaDescriptionMesh;
file.Close();
return saveMesh;
}
return null;
}
/// <summary>
/// Xml container for vertices and triangles from extracted mesh and linked Area Description.
/// </summary>
[XmlRoot("AreaDescriptionMesh")]
public class AreaDescriptionMesh
{
/// <summary>
/// The UUID of the linked Area Description.
/// </summary>
public string m_uuid;
/// <summary>
/// The mesh vertices.
/// </summary>
public Vector3[] m_vertices;
/// <summary>
/// The mesh triangles.
/// </summary>
public int[] m_triangles;
}
}
| |
//
// 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;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public partial interface IAutomationManagementClient : IDisposable
{
/// <summary>
/// Gets the API version.
/// </summary>
string ApiVersion
{
get;
}
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
Uri BaseUri
{
get;
}
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
SubscriptionCloudCredentials Credentials
{
get;
}
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
int LongRunningOperationInitialTimeout
{
get; set;
}
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
int LongRunningOperationRetryTimeout
{
get; set;
}
/// <summary>
/// Gets or sets the resource namespace.
/// </summary>
string ResourceNamespace
{
get; set;
}
/// <summary>
/// Service operation for automation activities. (see
/// http://aka.ms/azureautomationsdk/activityoperations for more
/// information)
/// </summary>
IActivityOperations Activities
{
get;
}
/// <summary>
/// Service operation for automation agent registration information.
/// (see http://aka.ms/azureautomationsdk/agentregistrationoperations
/// for more information)
/// </summary>
IAgentRegistrationOperation AgentRegistrationInformation
{
get;
}
/// <summary>
/// Service operation for automation accounts. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
IAutomationAccountOperations AutomationAccounts
{
get;
}
/// <summary>
/// Service operation for automation certificates. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
ICertificateOperations Certificates
{
get;
}
/// <summary>
/// Service operation for automation connections. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
IConnectionOperations Connections
{
get;
}
/// <summary>
/// Service operation for automation connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
IConnectionTypeOperations ConnectionTypes
{
get;
}
/// <summary>
/// Service operation for automation credentials. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
ICredentialOperations PsCredentials
{
get;
}
/// <summary>
/// Service operation for automation dsc configuration compile jobs.
/// (see
/// http://aka.ms/azureautomationsdk/dscccompilationjoboperations for
/// more information)
/// </summary>
IDscCompilationJobOperations CompilationJobs
{
get;
}
/// <summary>
/// Service operation for configurations. (see
/// http://aka.ms/azureautomationsdk/configurationoperations for more
/// information)
/// </summary>
IDscConfigurationOperations Configurations
{
get;
}
/// <summary>
/// Service operation for automation dsc node configurations. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
IDscNodeConfigurationOperations NodeConfigurations
{
get;
}
/// <summary>
/// Service operation for dsc nodes. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
IDscNodeOperations Nodes
{
get;
}
/// <summary>
/// Service operation for node reports. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
IDscNodeReportsOperations NodeReports
{
get;
}
/// <summary>
/// Service operation for automation hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
IHybridRunbookWorkerGroupOperations HybridRunbookWorkerGroups
{
get;
}
/// <summary>
/// Service operation for automation jobs. (see
/// http://aka.ms/azureautomationsdk/joboperations for more
/// information)
/// </summary>
IJobOperations Jobs
{
get;
}
/// <summary>
/// Service operation for automation job schedules. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
IJobScheduleOperations JobSchedules
{
get;
}
/// <summary>
/// Service operation for automation job streams. (see
/// http://aka.ms/azureautomationsdk/jobstreamoperations for more
/// information)
/// </summary>
IJobStreamOperations JobStreams
{
get;
}
/// <summary>
/// Service operation for automation linked workspace. (see
/// http://aka.ms/azureautomationsdk/linkedworkspaceoperations for
/// more information)
/// </summary>
ILinkedWorkspaceOperations LinkedWorkspace
{
get;
}
/// <summary>
/// Service operation for automation modules. (see
/// http://aka.ms/azureautomationsdk/moduleoperations for more
/// information)
/// </summary>
IModuleOperations Modules
{
get;
}
/// <summary>
/// Service operation for automation object data types. (see
/// http://aka.ms/azureautomationsdk/objectdatatypeoperations for more
/// information)
/// </summary>
IObjectDataTypeOperations ObjectDataTypes
{
get;
}
/// <summary>
/// Service operation for automation runbook draft. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
IRunbookDraftOperations RunbookDraft
{
get;
}
/// <summary>
/// Service operation for automation runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
IRunbookOperations Runbooks
{
get;
}
/// <summary>
/// Service operation for automation schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
IScheduleOperations Schedules
{
get;
}
/// <summary>
/// Service operation for automation variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
ISoftwareUpdateConfigurationOperations SoftwareUpdateConfigurations
{
get;
}
/// <summary>
/// Service operation for automation statistics. (see
/// http://aka.ms/azureautomationsdk/statisticsoperations for more
/// information)
/// </summary>
IStatisticsOperations Statistics
{
get;
}
/// <summary>
/// Service operation for automation test jobs. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
ITestJobOperations TestJobs
{
get;
}
/// <summary>
/// Service operation for automation type fields. (see
/// http://aka.ms/azureautomationsdk/typefieldoperations for more
/// information)
/// </summary>
ITypeFieldOperations TypeFields
{
get;
}
/// <summary>
/// Service operation for automation usages. (see
/// http://aka.ms/azureautomationsdk/usageoperations for more
/// information)
/// </summary>
IUsageOperations Usages
{
get;
}
/// <summary>
/// Service operation for automation variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
IVariableOperations Variables
{
get;
}
/// <summary>
/// Service operation for automation watcher actions. (see
/// http://aka.ms/azureautomationsdk/watcheractionoperations for more
/// information)
/// </summary>
IWatcherActionOperations WatcherActions
{
get;
}
/// <summary>
/// Service operation for automation watchers. (see
/// http://aka.ms/azureautomationsdk/watcheroperations for more
/// information)
/// </summary>
IWatcherOperations Watchers
{
get;
}
/// <summary>
/// Service operation for automation watcher streams. (see
/// http://aka.ms/azureautomationsdk/watcherstreamoperations for more
/// information)
/// </summary>
IWatcherStreamOperations WatcherStreams
{
get;
}
/// <summary>
/// Service operation for automation webhook. (see
/// http://aka.ms/azureautomationsdk/webhookoperations for more
/// information)
/// </summary>
IWebhookOperations Webhooks
{
get;
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResultResponse> GetOperationResultStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of
/// thespecified operation. After calling an asynchronous operation,
/// you can call Get Operation Status to determine whether the
/// operation has succeeded, failed, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// The request ID for the request you wish to track. The request ID is
/// returned in the x-ms-request-id response header for every request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
Task<LongRunningOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken);
}
}
| |
/// <summary>
/// The inspector for the GA prefab.
/// </summary>
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Reflection;
using System;
[CustomEditor(typeof(GA_Settings))]
public class GA_Inspector : Editor
{
private GUIContent _myPageLink = new GUIContent("My Page", "Opens your home on the GameAnalytics web page");
private GUIContent _documentationLink = new GUIContent("Help", "Opens the GameAnalytics Unity3D package documentation page in your browser.");
private GUIContent _checkForUpdates = new GUIContent("Download", "Opens the GameAnalytics Unity3D SDK downloads page.");
private GUIContent _publicKeyLabel = new GUIContent("Game Key", "Your GameAnalytics Game Key - copy/paste from the GA website.");
private GUIContent _privateKeyLabel = new GUIContent("Secret Key", "Your GameAnalytics Secret Key - copy/paste from the GA website.");
private GUIContent _apiKeyLabel = new GUIContent("API Key", "Your GameAnalytics API Key - copy/paste from the GA website. This key is used for retrieving data from the GA servers, f.x. when you want to generate heatmaps.");
private GUIContent _heatmapSizeLabel = new GUIContent("Heatmap Grid Size", "The size in Unity units of each heatmap grid space. Data visualized as a heatmap must use the same grid size as was used when the data was collected, otherwise the visualization will be wrong.");
private GUIContent _build = new GUIContent("Build", "The current version of the game. Updating the build name for each test version of the game will allow you to filter by build when viewing your data on the GA website.");
//private GUIContent _useBundleVersion = new GUIContent("Use Bundle Version", "Uses the Bundle Version from Player Settings instead of the Build field above (only works for iOS, Android, and Blackberry).");
private GUIContent _debugMode = new GUIContent("Debug Mode", "Show additional debug messages from GA in the unity editor console when submitting data.");
private GUIContent _debugAddEvent = new GUIContent("Debug Add Event", "Shows additional debug information every time an event is added to the queue.");
private GUIContent _sendExampleToMyGame = new GUIContent("Get Example Game Data", "If enabled data collected while playing the example tutorial game will be sent to your game (using your game key and secret key). Otherwise data will be sent to a premade GA test game, to prevent it from polluting your data.");
private GUIContent _runInEditor = new GUIContent("Run In Editor Play Mode", "Submit data to the GameAnalytics server while playing your game in the Unity editor.");
private GUIContent _customUserID = new GUIContent("Custom User ID", "If enabled no data will be submitted until a custom user ID is provided. This is useful if you have your own log-in system, which ensures you have a unique user ID.");
private GUIContent _interval = new GUIContent("Data Submit Interval", "This option determines how often (in seconds) data is sent to GameAnalytics.");
private GUIContent _allowRoaming = new GUIContent("Submit While Roaming", "If enabled and using a mobile device (iOS or Android), data will be submitted to the GameAnalytics servers while the mobile device is roaming (internet connection via carrier data network).");
private GUIContent _archiveData = new GUIContent("Archive Data", "If enabled data will be archived when an internet connection is not available. When an internet connection is established again, any archived data will be sent. Not supported on: Webplayer, Google Native Client, Flash, Windows Store Apps.");
private GUIContent _archiveMaxSize = new GUIContent("Size<", "Indicates the maximum disk space used for archiving data in bytes.");
private GUIContent _newSessionOnResume = new GUIContent("New Session On Resume", "If enabled and using a mobile device (iOS or Android), a new play session ID will be generated whenever the game is resumed from background.");
private GUIContent _basic = new GUIContent("Basic", "This tab shows general options which are relevant for a wide variety of messages sent to GameAnalytics.");
private GUIContent _debug = new GUIContent("Debug", "This tab shows options which determine how the GameAnalytics SDK behaves in the Unity3D editor.");
private GUIContent _preferences = new GUIContent("Advanced", "This tab shows advanced and misc. options for the GameAnalytics SDK.");
private GUIContent _autoSubmitUserInfo = new GUIContent("Auto Submit User Info", "If enabled information about platform, device, os, and os version is automatically submitted at the start of each session.");
private GUIStyle _orangeUpdateLabelStyle;
private GUIStyle _orangeUpdateIconStyle;
void OnEnable()
{
GA_Settings ga = target as GA_Settings;
if(ga.UpdateIcon == null)
{
ga.UpdateIcon = (Texture2D)Resources.LoadAssetAtPath("Assets/GameAnalytics/Plugins/Examples/update_orange.png", typeof(Texture2D));
if (ga.UpdateIcon == null)
ga.UpdateIcon = (Texture2D)Resources.LoadAssetAtPath("Assets/Plugins/GameAnalytics/Examples/update_orange.png", typeof(Texture2D));
}
if(ga.Logo == null)
{
ga.Logo = (Texture2D)Resources.LoadAssetAtPath("Assets/GameAnalytics/Plugins/Examples/gaLogo.png", typeof(Texture2D));
if (ga.Logo == null)
ga.Logo = (Texture2D)Resources.LoadAssetAtPath("Assets/Plugins/GameAnalytics/Examples/gaLogo.png", typeof(Texture2D));
//http://www.base64-image.de
/*String d = "";
d += "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABmJLR0QA/wD/AP+gvaeTAAAA";
d += "CXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH3AcFDBE3zqglrQAACQdJREFUeNrtW2tIVGsXf";
d += "mY7jcp4m+yoTdqYKWqFQtnlR2lFJGVxpEwIoThIHPDX15+v/oQdoiCC/DoQQSUxENSh7PJDHM";
d += "wL6lEY00Og2dV7U15GHXHUue71/WjPsGf2zDR7nE7ZtGDjOPPenudda73vu961Jfh6IuEeBYC";
d += "dADYDyAKQBiCJ+z6CK2sCMANgDMAAgNcA/gHwN/c9cc93L2EAwjmwFwG84A0+0OcF19Zmru2w";
d += "7xG4DIAcQAWA524A2CWAd6/7nOtDzvX5zWUFgFgA/wUwHiTQ/pAxzvUZy43hm0g0gHIAg0Gcc";
d += "bEaMciNIfrfBC4FsB1Azb8I/EtE1HBjkn5t8BEAfuO89bcA7ouIMW5sEV8LfAyASgBGXuffEj";
d += "x5GIeRG2NMsMH/AuBPANbvYNa/pA1Wbqy/BBP8re9E5cWYxK1gkBDDsbkcwHsa459LMYcIzp6";
d += "sywi8J3OoDMQxSjmPalyG4N1JMHJYRC2R23lL3XIE707CGIfJ7x1ezQ8A3p2EGn92jCu4rSX9";
d += "gAQQh83n2SGWt7f/EcC7kzDIYXRxdvwj7e8AUnkBDdGiVCpx6NAh5OfnY+3atUhOTgYRQSKRY";
d += "HZ2Fl1dXdDpdKirq4NWq3Wpu2bNGlRUVGDr1q1QqVSQSqVgGAY9PT0wGAy4desW2traAg3OgM";
d += "P2O4D/AbC4F5LzjrSiZz8jI4PUajVNTk6S0Wgki8VCLMuSu5jNZlpcXKTZ2VkaGBigkpISZxt";
d += "Hjx6l4eFhQR2bzUZWq5WqqqqCoQXjHFZBJKci0MYvX75M09PTZLVaBYN3kOCJDCKiM2fOONu5";
d += "fv062Ww2l7r8eh8+fAiWSVS4R5bCeZEcUbN/9+5dMplMFIjMz8/TyZMnCQBFR0dTS0uLz/IWi";
d += "4X27t0bDC14zmEGwxGwEUAe96Pftq9Wq1FaWorw8HAQiY9Z9vf3o7+/HwBQWFiItLQ0n+UZhs";
d += "GePXuWGqglDutG/pcXxbJ57tw5MhqNAvXmq7zVaiWz2ezyWCwWstvtRERUXV1NERERBICqqqo";
d += "8tuPeZm9vb7DM4CIAiZQjoEgMjenp6SgpKYFcLnd6eADOz3a7HUNDQ3j48CFqa2uxsLDweZmR";
d += "ybBp0yYUFhYiPT0djY2NMJlMCA8PR0ZGBiQSibMNx2cAzvYlEgnWrVuHzMxMvHnzZqkHvSIA5";
d += "wAgXqztX7t2zcVZuXvsuro6v9oJCwsjALR7927q6+sTzPjo6KigH7PZTGfPng3WviAeAH4VUz";
d += "k9PZ06Ozu9qml9fb3oAZ0/f94joeXl5QIzs9vt1N7eHiwz+BUA/hBT6dSpU6TX673Ofmpqqqh";
d += "ByOVyevTokYDQ1tZWSkhIoImJCQHJMzMzlJycHAwC/mC46yq/ZePGjYiPj/f4W11dHYaGhkQZ";
d += "Yl5eHrKyspw27rB7jUaDiYkJ9Pb2gmVZF18gk8lw5MiRYES7shjurs6/CElEBFQqldPhuUttb";
d += "a1zkP7KypUrYbPZoNfrwbKss357ezsAoLGx0UkAfxxFRUXBICBNyl1U+iWrV69GXFycy2zw5d";
d += "WrVwJiJBIJFAoFEhMTBUCsVitYlsWTJ0+gUCiQnZ2NjIwMyGQyvH//HgDQ1NSEyspKZx0iAsM";
d += "wyMnJQXx8PKamppZCQJKUu6X1r3RSEhQK78UHBgaEl4YyGUpLS1FWVgaz2Swgx2q1wmKxgGVZ";
d += "6PV6rFq1Ct3d3VhcXAQAdHZ2Ym5uDgqFwrk8AkBkZCSKi4tRXV29FAIUAGDz12ns2rWLenp6v";
d += "G5V5XK5oE5UVBTduXNH1Ba5vLycpFKps436+nrBWcJqtdK9e/eW6gRtjBi6GIbxaePetsMWi0";
d += "XUtHR1dcFmszn/b2hoEAYtpVLk5OQgOnpp14IMl5zgl0xNTWFubs7r7ykpKZ434CIcY0dHh8C";
d += "uGxoaXFYIx9+EhAQcPHhwKfhNDJeB4ZfMzMz4JCAzM1MAlr9V9qUx/OVvenrapdyLFy8wMzPj";
d += "siUGgJiYGBQUFCyFgBmGi5j6JTqdDpOTk17VPS8vTwDWZDLh6tWrKC4uxuHDh1FUVITjx49Do";
d += "9G4lHV81mq1zrODQ1iWRUdHh0cHm5ubC4ZhAiVgDAD+EuM4Ll265DW48fLlS7/aWL9+PTU1NQ";
d += "nqv337lrKzsz3WOX36tMdAy+joKB04cCBQJ/gXg88JSX5LW1ubx+UOADZs2IBjx459sY3MzEz";
d += "k5+cLvtdqtQL1d8izZ89cNM+hMfHx8di5c2egGvCawedsLL+ltbUVIyMjXm345s2b2L9/v/e4";
d += "+4oV2LJlC8LCwgR1m5ubMT4+7rFeX18fBgcHBSYWGRmJvLy8QAn4h8HnVDTAzzS0+fl5PH36F";
d += "AaDQXBmJyLExcXh/v37uHDhApKShJvM3Nxc7Nu3TzCbCwsLzuiQJ2FZFs3NzR6daEpKCrZt2y";
d += "YGuAPr346lUFQ6W1RUFDU2Nnr0Aw7bNJvNNDs7S58+faIHDx6QRqOhjx8/ktFo9Bg87ejooKy";
d += "sLJ/9lpWVeexzYWGBKisrA0m/YwIOieXn59PIyIjPiK9D7Ha7MwzmLVp85coVio6O9tlnYmKi";
d += "1/5qamoCCok5VGJzIBHhgoIC0ul0HuN43gbqjSz+/YC3RyqVklar9dhed3c35eTkiIkGbeZHh";
d += "V8C6OJFTf2SlpYWlJWV4fXr1y5HWV8bIL7fcMi7d++g0+m+2B/LsmhqavK4kVKpVNixY4c/ti";
d += "/hsL4M2sVIZGQkqdVqMhgMZDabv2gS/KixIzqclJTkV1/bt2/3qkm3b98WfTEicbsaGwCQIPZ";
d += "+gH+3d+LECRQXFyMtLQ1hYWHOBwDsdjvsdjsAYHx8HFqtFmq1WuDdfYlMJsPjx4+hVCqhVCpB";
d += "RDCZTBgeHoZGo8GNGzdgMBh8zf4EFwSadydABuA/AC4HI9QSGxsLlUqF1NRUKJVK2Gw2jI2NY";
d += "WBgAHq9HhMTE/hGcsbb5WhIXo//TJD4mSLzM0nKo4R8mhwQ4omSDgnpVFmHhHSyNJ+EkE2X55";
d += "tDyL4wwXeMIfvKDH+JDNmXptx3jCH52pz72SFkX5yE21E6JF+ddZdl9/K05CuSsSxen/8/Sd3";
d += "GJdqpTWgAAAAASUVORK5CYII=";
ga.Logo = new Texture2D(1,1);
ga.Logo.LoadImage(System.Convert.FromBase64String(d));*/
}
/*if (ga.UseBundleVersion)
{
ga.Build = PlayerSettings.bundleVersion;
}*/
}
override public void OnInspectorGUI ()
{
GA_Settings ga = target as GA_Settings;
EditorGUI.indentLevel = 1;
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label(ga.Logo);
GUILayout.BeginVertical();
GUILayout.Label("GameAnalytics Unity SDK v." + GA_Settings.VERSION);
GUILayout.BeginHorizontal();
if (GUILayout.Button(_myPageLink, GUILayout.MaxWidth(75)))
{
Application.OpenURL("http://easy.gameanalytics.com/LoginGA");
}
if (GUILayout.Button(_documentationLink, GUILayout.MaxWidth(75)))
{
Application.OpenURL("http://easy.gameanalytics.com/SupportDocu");
}
if (GUILayout.Button(_checkForUpdates, GUILayout.MaxWidth(75)))
{
Application.OpenURL("http://easy.gameanalytics.com/DownloadSetup");
}
GUILayout.EndHorizontal();
string updateStatus = GA_UpdateWindow.UpdateStatus(GA_Settings.VERSION);
GUILayout.Space(5);
GUILayout.BeginHorizontal();
if (!updateStatus.Equals(string.Empty))
{
if (_orangeUpdateLabelStyle == null)
{
_orangeUpdateLabelStyle = new GUIStyle(EditorStyles.wordWrappedLabel);
_orangeUpdateLabelStyle.normal.textColor = new Color(0.875f, 0.309f, 0.094f);
}
if (_orangeUpdateIconStyle == null)
{
_orangeUpdateIconStyle = new GUIStyle(EditorStyles.wordWrappedLabel);
}
if (GUILayout.Button(ga.UpdateIcon, _orangeUpdateIconStyle, GUILayout.MaxWidth(17)))
{
OpenUpdateWindow();
}
GUILayout.Label(updateStatus, _orangeUpdateLabelStyle);
}
else
GUILayout.Label("");
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
//Hints
/*ga.DisplayHints = EditorGUILayout.Foldout(ga.DisplayHints,"Show Hints");
if (ga.DisplayHints)
{
ga.DisplayHintsScrollState = GUILayout.BeginScrollView(ga.DisplayHintsScrollState, GUILayout.Height (100));
List<GA_Settings.HelpInfo> helpInfos = ga.GetHelpMessageList();
foreach(GA_Settings.HelpInfo info in helpInfos)
{
MessageType msgType = ConvertMessageType(info.MsgType);
EditorGUILayout.HelpBox(info.Message, msgType);
}
GUILayout.EndScrollView();
}*/
//Tabs
GUILayout.BeginHorizontal();
GUIStyle activeTabStyle = new GUIStyle(EditorStyles.miniButtonMid);
GUIStyle activeTabStyleLeft = new GUIStyle(EditorStyles.miniButtonLeft);
GUIStyle activeTabStyleRight = new GUIStyle(EditorStyles.miniButtonRight);
activeTabStyle.normal = EditorStyles.miniButtonMid.active;
activeTabStyleLeft.normal = EditorStyles.miniButtonLeft.active;
activeTabStyleRight.normal = EditorStyles.miniButtonRight.active;
GUIStyle inactiveTabStyle = new GUIStyle(EditorStyles.miniButtonMid);
GUIStyle inactiveTabStyleLeft = new GUIStyle(EditorStyles.miniButtonLeft);
GUIStyle inactiveTabStyleRight = new GUIStyle(EditorStyles.miniButtonRight);
if (GUILayout.Button(_basic, ga.CurrentInspectorState==GA_Settings.InspectorStates.Basic?activeTabStyleLeft:inactiveTabStyleLeft))
{
ga.CurrentInspectorState = GA_Settings.InspectorStates.Basic;
}
if (GUILayout.Button(_debug, ga.CurrentInspectorState==GA_Settings.InspectorStates.Debugging?activeTabStyle:inactiveTabStyle))
{
ga.CurrentInspectorState = GA_Settings.InspectorStates.Debugging;
}
if (GUILayout.Button(_preferences,ga.CurrentInspectorState==GA_Settings.InspectorStates.Pref?activeTabStyleRight:inactiveTabStyleRight))
{
ga.CurrentInspectorState = GA_Settings.InspectorStates.Pref;
}
GUILayout.EndHorizontal();
if(ga.CurrentInspectorState == GA_Settings.InspectorStates.Basic)
{
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_publicKeyLabel, GUILayout.Width(75));
ga.GameKey = EditorGUILayout.TextField("", ga.GameKey);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_privateKeyLabel, GUILayout.Width(75));
ga.SecretKey = EditorGUILayout.TextField("", ga.SecretKey);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_build, GUILayout.Width(75));
ga.Build = EditorGUILayout.TextField("", ga.Build);
GUILayout.EndHorizontal();
/*GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_useBundleVersion, GUILayout.Width(150));
ga.UseBundleVersion = EditorGUILayout.Toggle("", ga.UseBundleVersion);
GUILayout.EndHorizontal();*/
}
if(ga.CurrentInspectorState == GA_Settings.InspectorStates.Debugging)
{
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_debugMode, GUILayout.Width(150));
ga.DebugMode = EditorGUILayout.Toggle("", ga.DebugMode);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_debugAddEvent, GUILayout.Width(150));
ga.DebugAddEvent = EditorGUILayout.Toggle("", ga.DebugAddEvent);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_runInEditor, GUILayout.Width(150));
ga.RunInEditorPlayMode = EditorGUILayout.Toggle("", ga.RunInEditorPlayMode);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_sendExampleToMyGame, GUILayout.Width(150));
ga.SendExampleGameDataToMyGame = EditorGUILayout.Toggle("", ga.SendExampleGameDataToMyGame);
GUILayout.EndHorizontal();
}
if(ga.CurrentInspectorState == GA_Settings.InspectorStates.Pref)
{
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_apiKeyLabel, GUILayout.Width(75));
ga.ApiKey = EditorGUILayout.TextField("", ga.ApiKey);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_heatmapSizeLabel, GUILayout.Width(150));
GUILayout.EndHorizontal();
#if UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0
GUILayout.Space(-15);
#endif
ga.HeatmapGridSize = EditorGUILayout.Vector3Field("", ga.HeatmapGridSize);
if (ga.HeatmapGridSize != Vector3.one)
{
EditorGUILayout.HelpBox("Editing the heatmap grid size must be done BEFORE data is submitted, and you must use the same grid size when setting up your heatmaps. Otherwise the heatmap data will be incorrectly displayed.", MessageType.Warning);
}
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_interval, GUILayout.Width(150));
int tmpTimer = 0;
if (int.TryParse(EditorGUILayout.TextField(ga.SubmitInterval.ToString(), GUILayout.Width(38)), out tmpTimer))
{
ga.SubmitInterval = Mathf.Max(Mathf.Min(tmpTimer, 999), 1);
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_customUserID, GUILayout.Width(150));
ga.CustomUserID = EditorGUILayout.Toggle("", ga.CustomUserID);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_archiveData, GUILayout.Width(150));
ga.ArchiveData = EditorGUILayout.Toggle("", ga.ArchiveData, GUILayout.Width(36));
GUI.enabled = ga.ArchiveData;
GUILayout.Label(_archiveMaxSize, GUILayout.Width(40));
int tmpMaxArchiveSize = 0;
if (int.TryParse(EditorGUILayout.TextField(ga.ArchiveMaxFileSize.ToString(), GUILayout.Width(48)), out tmpMaxArchiveSize))
{
ga.ArchiveMaxFileSize = Mathf.Max(Mathf.Min(tmpMaxArchiveSize, 2000), 0);
}
GUI.enabled = true;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_allowRoaming, GUILayout.Width(150));
ga.AllowRoaming = EditorGUILayout.Toggle("", ga.AllowRoaming);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_newSessionOnResume, GUILayout.Width(150));
ga.NewSessionOnResume = EditorGUILayout.Toggle("", ga.NewSessionOnResume);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("", GUILayout.Width(7));
GUILayout.Label(_autoSubmitUserInfo, GUILayout.Width(150));
ga.AutoSubmitUserInfo = EditorGUILayout.Toggle("", ga.AutoSubmitUserInfo);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
}
if (GUI.changed)
{
EditorUtility.SetDirty(ga);
}
}
private MessageType ConvertMessageType(GA_Settings.MessageTypes msgType)
{
switch (msgType)
{
case GA_Settings.MessageTypes.Error:
return MessageType.Error;
case GA_Settings.MessageTypes.Info:
return MessageType.Info;
case GA_Settings.MessageTypes.Warning:
return MessageType.Warning;
default:
return MessageType.None;
}
}
public static void CheckForUpdates ()
{
WWW www = new WWW("https://s3.amazonaws.com/public.gameanalytics.com/sdk_status/current.json");
GA_ContinuationManager.StartCoroutine(CheckWebUpdate(www), () => www.isDone);
}
private static void GetUpdateChanges ()
{
WWW www = new WWW("https://s3.amazonaws.com/public.gameanalytics.com/sdk_status/change_logs.json");
GA_ContinuationManager.StartCoroutine(CheckWebChanges(www), () => www.isDone);
}
private static IEnumerator<WWW> CheckWebUpdate (WWW www)
{
yield return www;
try {
Hashtable returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
string newVersion = ((Hashtable)returnParam["unity"])["version"].ToString();
GA_UpdateWindow.SetNewVersion(newVersion);
if (newVersion != GA_Settings.VERSION)
{
GetUpdateChanges();
}
}
catch {}
}
private static IEnumerator<WWW> CheckWebChanges (WWW www)
{
yield return www;
try {
Hashtable returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
ArrayList unity = ((ArrayList)returnParam["unity"]);
for (int i = 0; i < unity.Count; i++)
{
Hashtable unityHash = (Hashtable)unity[i];
if (unityHash["version"].ToString() == GA_UpdateWindow.GetNewVersion())
{
i = unity.Count;
ArrayList changes = ((ArrayList)unityHash["changes"]);
string newChanges = "";
for (int u = 0; u < changes.Count; u++)
{
if (string.IsNullOrEmpty(newChanges))
newChanges = "- " + changes[u].ToString();
else
newChanges += "\n- " + changes[u].ToString();
}
GA_UpdateWindow.SetChanges(newChanges);
string skippedVersion = EditorPrefs.GetString("ga_skip_version", "");
if (!skippedVersion.Equals(GA_UpdateWindow.GetNewVersion()))
{
OpenUpdateWindow();
}
}
}
}
catch {}
}
private static void OpenUpdateWindow ()
{
GA_UpdateWindow updateWindow = ScriptableObject.CreateInstance<GA_UpdateWindow> ();
updateWindow.ShowUtility ();
updateWindow.position = new Rect (150, 150, 420, 340);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using PcapDotNet.Base;
using PcapDotNet.Packets.Ip;
using PcapDotNet.Packets.IpV4;
namespace PcapDotNet.Packets.IpV6
{
/// <summary>
/// RFC 2460.
/// Represents an IPv6 datagram.
/// <pre>
/// +-----+---------+---------------+-------+-------------+-----------+
/// | Bit | 0-3 | 4-11 | 12-15 | 16-23 | 24-31 |
/// +-----+---------+---------------+-------+-------------+-----------+
/// | 0 | Version | Traffic Class | Flow Label |
/// +-----+---------+---------------+-------+-------------+-----------+
/// | 32 | Payload Length | Next Header | Hop Limit |
/// +-----+---------------------------------+-------------+-----------+
/// | 64 | Source Address |
/// | | |
/// | | |
/// | | |
/// +-----+-----------------------------------------------------------+
/// | 192 | Destination Address |
/// | | |
/// | | |
/// | | |
/// +-----+-----------------------------------------------------------+
/// | 320 | Extension Headers (optional) |
/// | ... | |
/// +-----+-----------------------------------------------------------+
/// </pre>
/// </summary>
public sealed class IpV6Datagram : IpDatagram
{
/// <summary>
/// The number of bytes the header takes in bytes (not including extension headers).
/// </summary>
public const int HeaderLength = 40;
/// <summary>
/// Maximum flow label value.
/// </summary>
public const int MaxFlowLabel = 0xFFFFF;
private static class Offset
{
public const int Version = 0;
public const int TrafficClass = Version;
public const int FlowLabel = TrafficClass + 1;
public const int PayloadLength = FlowLabel + 3;
public const int NextHeader = PayloadLength + sizeof(ushort);
public const int HopLimit = NextHeader + sizeof(byte);
public const int SourceAddress = HopLimit + sizeof(byte);
public const int DestinationAddress = SourceAddress + IpV6Address.SizeOf;
}
private static class Mask
{
public const byte Version = 0xF0;
public const ushort TrafficClass = 0x0FF0;
public static readonly UInt24 FlowLabel = (UInt24)0x0FFFFF;
}
private static class Shift
{
public const int Version = 4;
public const int TrafficClass = 4;
}
/// <summary>
/// The version (6).
/// </summary>
public const int DefaultVersion = 0x6;
/// <summary>
/// Available for use by originating nodes and/or forwarding routers to identify and distinguish between different classes or priorities of
/// IPv6 packets.
/// </summary>
public byte TrafficClass
{
get { return (byte)((ReadUShort(Offset.TrafficClass, Endianity.Big) & Mask.TrafficClass) >> Shift.TrafficClass); }
}
/// <summary>
/// May be used by a source to label sequences of packets for which it requests special handling by the IPv6 routers,
/// such as non-default quality of service or "real-time" service.
/// Hosts or routers that do not support the functions of the Flow Label field are required to set the field to zero when originating a packet,
/// pass the field on unchanged when forwarding a packet, and ignore the field when receiving a packet.
/// </summary>
public int FlowLabel
{
get { return ReadUInt24(Offset.FlowLabel, Endianity.Big) & Mask.FlowLabel; }
}
/// <summary>
/// Length of the IPv6 payload, i.e., the rest of the packet following this IPv6 header, in octets.
/// Note that any extension headers present are considered part of the payload, i.e., included in the length count.
/// </summary>
public ushort PayloadLength
{
get { return ReadUShort(Offset.PayloadLength, Endianity.Big); }
}
/// <summary>
/// The actual payload length
/// </summary>
public ushort RealPayloadLength
{
get
{
if (Length < HeaderLength)
return 0;
return (ushort)Math.Min(PayloadLength, Length - HeaderLength);
}
}
/// <summary>
/// Identifies the type of header immediately following the IPv6 header.
/// Uses the same values as the IPv4 Protocol field.
/// </summary>
public IpV4Protocol NextHeader
{
get { return (IpV4Protocol)this[Offset.NextHeader]; }
}
/// <summary>
/// Decremented by 1 by each node that forwards the packet.
/// The packet is discarded if Hop Limit is decremented to zero.
/// </summary>
public byte HopLimit
{
get { return this[Offset.HopLimit]; }
}
/// <summary>
/// Address of the originator of the packet.
/// </summary>
public IpV6Address Source
{
get { return ReadIpV6Address(Offset.SourceAddress, Endianity.Big); }
}
/// <summary>
/// Address of the intended recipient of the packet (possibly not the ultimate recipient, if a Routing header is present).
/// </summary>
public IpV6Address CurrentDestination
{
get { return ReadIpV6Address(Offset.DestinationAddress, Endianity.Big); }
}
/// <summary>
/// The IPv6 extension headers.
/// </summary>
public IpV6ExtensionHeaders ExtensionHeaders
{
get
{
ParseExtensionHeaders();
return _extensionHeaders;
}
}
/// <summary>
/// The total length - header and payload according to the IP header.
/// </summary>
public override int TotalLength
{
get { return HeaderLength + PayloadLength; }
}
/// <summary>
/// Creates a Layer that represents the datagram to be used with PacketBuilder.
/// </summary>
public override ILayer ExtractLayer()
{
return new IpV6Layer
{
TrafficClass = TrafficClass,
FlowLabel = FlowLabel,
NextHeader = NextHeader,
HopLimit = HopLimit,
Source = Source,
CurrentDestination = CurrentDestination,
ExtensionHeaders = ExtensionHeaders,
};
}
/// <summary>
/// Valid if all extension headers are valid and payload is valid.
/// </summary>
protected override bool CalculateIsValid()
{
ParseExtensionHeaders();
if (!_isValidExtensionHeaders)
return false;
return IsPayloadValid;
}
/// <summary>
/// Calculates the Transport checksum field value.
/// </summary>
/// <returns>The calculated checksum value.</returns>
protected override ushort CalculateTransportChecksum()
{
return CalculateTransportChecksum(Buffer, StartOffset, HeaderLength + ExtensionHeaders.BytesLength, (uint)Transport.Length, Transport.ChecksumOffset,
Transport.IsChecksumOptional, CurrentDestination);
}
internal IpV6Datagram(byte[] buffer, int offset, int length)
: base(buffer, offset, length)
{
}
internal override IpV4Protocol PayloadProtocol
{
get
{
IpV4Protocol? extensionHeadersNextHeader = ExtensionHeaders.NextHeader;
if (extensionHeadersNextHeader != null)
return extensionHeadersNextHeader.Value;
return NextHeader;
}
}
internal static int GetTotalLength(Datagram payload)
{
if (payload.Length <= HeaderLength)
return payload.Length;
return Math.Min(payload.Length, HeaderLength + payload.ReadUShort(Offset.PayloadLength, Endianity.Big));
}
internal override DataSegment GetPayload()
{
if (Length < HeaderLength)
return null;
return Subsegment(HeaderLength + ExtensionHeaders.BytesLength, Length - HeaderLength - ExtensionHeaders.BytesLength);
}
internal static void WriteHeader(byte[] buffer, int offset,
byte trafficClass, int flowLabel, ushort payloadLength, IpV4Protocol? nextHeader, IpV4Protocol? nextLayerProtocol,
byte hopLimit, IpV6Address source, IpV6Address currentDestination, IpV6ExtensionHeaders extensionHeaders)
{
buffer.Write(offset + Offset.Version, (uint)((((DefaultVersion << 8) | trafficClass) << 20) | flowLabel), Endianity.Big);
buffer.Write(offset + Offset.PayloadLength, payloadLength, Endianity.Big);
IpV4Protocol actualNextHeader;
if (nextHeader.HasValue)
actualNextHeader = nextHeader.Value;
else if (extensionHeaders.Any())
actualNextHeader = extensionHeaders.FirstHeader.Value;
else if (nextLayerProtocol.HasValue)
actualNextHeader = nextLayerProtocol.Value;
else
throw new InvalidOperationException("Can't determine next header. No extension headers and no known next layer protocol.");
buffer.Write(offset + Offset.NextHeader, (byte)actualNextHeader);
buffer.Write(offset + Offset.HopLimit, hopLimit);
buffer.Write(offset + Offset.SourceAddress, source, Endianity.Big);
buffer.Write(offset + Offset.DestinationAddress, currentDestination, Endianity.Big);
extensionHeaders.Write(buffer, offset + HeaderLength, nextLayerProtocol);
}
internal static void WriteTransportChecksum(byte[] buffer, int offset, int headerLength, uint transportLength, int transportChecksumOffset,
bool isChecksumOptional, ushort? checksum, IpV6Address destination)
{
ushort checksumValue =
checksum ?? CalculateTransportChecksum(buffer, offset, headerLength, transportLength, transportChecksumOffset, isChecksumOptional, destination);
buffer.Write(offset + headerLength + transportChecksumOffset, checksumValue, Endianity.Big);
}
private void ParseExtensionHeaders()
{
if (_extensionHeaders != null)
return;
if (Length < HeaderLength)
{
_isValidExtensionHeaders = false;
_extensionHeaders = IpV6ExtensionHeaders.Empty;
return;
}
_extensionHeaders = new IpV6ExtensionHeaders(Subsegment(HeaderLength, RealPayloadLength), NextHeader);
_isValidExtensionHeaders = _isValidExtensionHeaders && _extensionHeaders.IsValid;
}
private static ushort CalculateTransportChecksum(byte[] buffer, int offset, int fullHeaderLength, uint transportLength, int transportChecksumOffset, bool isChecksumOptional, IpV6Address destination)
{
int offsetAfterChecksum = offset + fullHeaderLength + transportChecksumOffset + sizeof(ushort);
uint sum = Sum16Bits(buffer, offset + Offset.SourceAddress, IpV6Address.SizeOf) +
Sum16Bits(destination) +
Sum16Bits(transportLength) + buffer[offset + Offset.NextHeader] +
Sum16Bits(buffer, offset + fullHeaderLength, transportChecksumOffset) +
Sum16Bits(buffer, offsetAfterChecksum, (int)(transportLength - transportChecksumOffset - sizeof(ushort)));
ushort checksumResult = Sum16BitsToChecksum(sum);
if (checksumResult == 0 && isChecksumOptional)
return 0xFFFF;
return checksumResult;
}
private IpV6ExtensionHeaders _extensionHeaders;
private bool _isValidExtensionHeaders = true;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.InteropServices
{
/// <summary>
/// Native buffer that deals in char size increments. Dispose to free memory. Allows buffers larger
/// than a maximum size string to enable working with very large string arrays. Always makes ordinal
/// comparisons.
///
/// A more performant replacement for StringBuilder when performing native interop.
/// </summary>
/// <remarks>
/// Suggested use through P/Invoke: define DllImport arguments that take a character buffer as IntPtr.
/// NativeStringBuffer has an implicit conversion to IntPtr.
/// </remarks>
internal class StringBuffer : NativeBuffer
{
private ulong _length;
/// <summary>
/// Instantiate the buffer with capacity for at least the specified number of characters. Capacity
/// includes the trailing null character.
/// </summary>
public StringBuffer(ulong initialCapacity = 0)
: base(initialCapacity)
{
}
/// <summary>
/// Instantiate the buffer with a copy of the specified string.
/// </summary>
public unsafe StringBuffer(string initialContents)
: base(0)
{
// We don't pass the count of bytes to the base constructor, appending will
// initialize to the correct size for the specified initial contents.
if (initialContents != null)
{
Append(initialContents);
}
}
/// <summary>
/// Get/set the character at the given index.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to index outside of the buffer length.</exception>
public new unsafe char this[ulong index]
{
get
{
if (index >= _length) throw new ArgumentOutOfRangeException(nameof(index));
return CharPointer[index];
}
set
{
if (index >= _length) throw new ArgumentOutOfRangeException(nameof(index));
CharPointer[index] = value;
}
}
/// <summary>
/// Character capacity of the buffer. Includes the count for the trailing null character.
/// </summary>
public ulong CharCapacity
{
get
{
ulong byteCapacity = ByteCapacity;
return byteCapacity == 0 ? 0 : byteCapacity / sizeof(char);
}
}
/// <summary>
/// Ensure capacity in characters is at least the given minimum.
/// </summary>
/// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception>
public void EnsureCharCapacity(ulong minCapacity)
{
EnsureByteCapacity(minCapacity * sizeof(char));
}
/// <summary>
/// The logical length of the buffer in characters. (Does not include the final null.) Will automatically attempt to increase capacity.
/// This is where the usable data ends.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to set <paramref name="nameof(Length)"/> to a value that is larger than the maximum addressable memory.</exception>
/// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception>
public unsafe ulong Length
{
get { return _length; }
set
{
// Null terminate
EnsureCharCapacity(value + 1);
CharPointer[value] = '\0';
_length = value;
}
}
/// <summary>
/// For use when the native api null terminates but doesn't return a length.
/// If no null is found, the length will not be changed.
/// </summary>
public unsafe void SetLengthToFirstNull()
{
char* buffer = CharPointer;
ulong capacity = CharCapacity;
for (ulong i = 0; i < capacity; i++)
{
if (buffer[i] == '\0')
{
_length = i;
break;
}
}
}
internal unsafe char* CharPointer
{
get
{
return (char*)VoidPointer;
}
}
/// <summary>
/// Returns true if the buffer starts with the given string.
/// </summary>
public bool StartsWith(string value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (_length < (ulong)value.Length) return false;
return SubstringEquals(value, startIndex: 0, count: value.Length);
}
/// <summary>
/// Returns true if the specified StringBuffer substring equals the given value.
/// </summary>
/// <param name="value">The value to compare against the specified substring.</param>
/// <param name="startIndex">Start index of the sub string.</param>
/// <param name="count">Length of the substring, or -1 to check all remaining.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
/// of the buffer's length.
/// </exception>
public unsafe bool SubstringEquals(string value, ulong startIndex = 0, int count = -1)
{
if (value == null) return false;
if (count < -1) throw new ArgumentOutOfRangeException(nameof(count));
ulong realCount = count == -1 ? _length - startIndex : (ulong)count;
if (startIndex + realCount > _length) throw new ArgumentOutOfRangeException(nameof(count));
int length = value.Length;
// Check the substring length against the input length
if (realCount != (ulong)length) return false;
fixed (char* valueStart = value)
{
char* bufferStart = CharPointer + startIndex;
for (int i = 0; i < length; i++)
{
// Note that indexing in this case generates faster code than trying to copy the pointer and increment it
if (*bufferStart++ != valueStart[i]) return false;
}
}
return true;
}
/// <summary>
/// Append the given string.
/// </summary>
/// <param name="value">The string to append.</param>
/// <param name="startIndex">The index in the input string to start appending from.</param>
/// <param name="count">The count of characters to copy from the input string, or -1 for all remaining.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
/// of <paramref name="value"/> characters.
/// </exception>
public void Append(string value, int startIndex = 0, int count = -1)
{
CopyFrom(
bufferIndex: _length,
source: value,
sourceIndex: startIndex,
count: count);
}
/// <summary>
/// Append the given buffer.
/// </summary>
/// <param name="value">The buffer to append.</param>
/// <param name="startIndex">The index in the input buffer to start appending from.</param>
/// <param name="count">The count of characters to copy from the buffer string.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range
/// of <paramref name="value"/> characters.
/// </exception>
public void Append(StringBuffer value, ulong startIndex = 0, ulong count = 0)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (count == 0) return;
value.CopyTo(
bufferIndex: startIndex,
destination: this,
destinationIndex: _length,
count: count);
}
/// <summary>
/// Copy contents to the specified buffer. Destination index must be within current destination length.
/// Will grow the destination buffer if needed.
/// </summary>
public unsafe void CopyTo(ulong bufferIndex, StringBuffer destination, ulong destinationIndex, ulong count)
{
if (destination == null) throw new ArgumentNullException(nameof(destination));
if (destinationIndex > destination._length) throw new ArgumentOutOfRangeException(nameof(destinationIndex));
if (_length < bufferIndex + count) throw new ArgumentOutOfRangeException(nameof(count));
if (count == 0) return;
ulong lastIndex = destinationIndex + (ulong)count;
if (destination._length < lastIndex) destination.Length = lastIndex;
Buffer.MemoryCopy(
source: CharPointer + bufferIndex,
destination: destination.CharPointer + destinationIndex,
destinationSizeInBytes: checked((long)(destination.ByteCapacity - (destinationIndex * sizeof(char)))),
sourceBytesToCopy: checked((long)count * sizeof(char)));
}
/// <summary>
/// Copy contents from the specified string into the buffer at the given index. Start index must be within the current length of
/// the buffer, will grow as necessary.
/// </summary>
public unsafe void CopyFrom(ulong bufferIndex, string source, int sourceIndex = 0, int count = -1)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (bufferIndex > _length) throw new ArgumentOutOfRangeException(nameof(bufferIndex));
if (sourceIndex < 0 || sourceIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(sourceIndex));
if (count < 0) count = source.Length - sourceIndex;
if (source.Length - count < sourceIndex) throw new ArgumentOutOfRangeException(nameof(count));
if (count == 0) return;
ulong lastIndex = bufferIndex + (ulong)count;
if (_length < lastIndex) Length = lastIndex;
fixed (char* content = source)
{
Buffer.MemoryCopy(
source: content + sourceIndex,
destination: CharPointer + bufferIndex,
destinationSizeInBytes: checked((long)(ByteCapacity - (bufferIndex * sizeof(char)))),
sourceBytesToCopy: (long)count * sizeof(char));
}
}
/// <summary>
/// Trim the specified values from the end of the buffer. If nothing is specified, nothing is trimmed.
/// </summary>
public unsafe void TrimEnd(char[] values)
{
if (values == null || values.Length == 0 || _length == 0) return;
char* end = CharPointer + _length - 1;
while (_length > 0 && Array.IndexOf(values, *end) >= 0)
{
Length = _length - 1;
end--;
}
}
/// <summary>
/// String representation of the entire buffer. If the buffer is larger than the maximum size string (int.MaxValue) this will throw.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the buffer is too big to fit into a string.</exception>
public unsafe override string ToString()
{
if (_length == 0) return string.Empty;
if (_length > int.MaxValue) throw new InvalidOperationException();
return new string(CharPointer, startIndex: 0, length: (int)_length);
}
/// <summary>
/// Get the given substring in the buffer.
/// </summary>
/// <param name="count">Count of characters to take, or remaining characters from <paramref name="startIndex"/> if -1.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range of the buffer's length
/// or count is greater than the maximum string size (int.MaxValue).
/// </exception>
public unsafe string Substring(ulong startIndex, int count = -1)
{
if (_length > 0 && startIndex > _length - 1) throw new ArgumentOutOfRangeException(nameof(startIndex));
if (count < -1) throw new ArgumentOutOfRangeException(nameof(count));
ulong realCount = count == -1 ? _length - startIndex : (ulong)count;
if (realCount > int.MaxValue || startIndex + realCount > _length) throw new ArgumentOutOfRangeException(nameof(count));
if (realCount == 0) return string.Empty;
// The buffer could be bigger than will fit into a string, but the substring might fit. As the starting
// index might be bigger than int we need to index ourselves.
return new string(value: CharPointer + startIndex, startIndex: 0, length: (int)realCount);
}
public override void Free()
{
base.Free();
_length = 0;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AccountOperations operations.
/// </summary>
public partial interface IAccountOperations
{
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to retrieve.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Attempts to enable a user managed Key Vault for encryption of the
/// specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to attempt to enable the
/// Key Vault for.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> EnableKeyVaultWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource
/// group. The response includes a link to the next page of results, if
/// any.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account(s).
/// </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'>
/// A 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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListWithHttpMessagesAsync(ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<DataLakeStoreAccount>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource
/// group. 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'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. 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'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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.KeyVault
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for VaultsOperations.
/// </summary>
public static partial class VaultsOperationsExtensions
{
/// <summary>
/// Create or update a key vault in the specified subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='vaultName'>
/// Name of the vault
/// </param>
/// <param name='parameters'>
/// Parameters to create or update the vault
/// </param>
public static Vault CreateOrUpdate(this IVaultsOperations operations, string resourceGroupName, string vaultName, VaultCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).CreateOrUpdateAsync(resourceGroupName, vaultName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a key vault in the specified subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the server belongs.
/// </param>
/// <param name='vaultName'>
/// Name of the vault
/// </param>
/// <param name='parameters'>
/// Parameters to create or update the vault
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Vault> CreateOrUpdateAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, VaultCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vaultName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Azure key vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='vaultName'>
/// The name of the vault to delete
/// </param>
public static void Delete(this IVaultsOperations operations, string resourceGroupName, string vaultName)
{
Task.Factory.StartNew(s => ((IVaultsOperations)s).DeleteAsync(resourceGroupName, vaultName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Azure key vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='vaultName'>
/// The name of the vault to delete
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vaultName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified Azure key vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='vaultName'>
/// The name of the vault.
/// </param>
public static Vault Get(this IVaultsOperations operations, string resourceGroupName, string vaultName)
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).GetAsync(resourceGroupName, vaultName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified Azure key vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='vaultName'>
/// The name of the vault.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Vault> GetAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vaultName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List operation gets information about the vaults associated with the
/// subscription and within the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='top'>
/// Maximum number of results to return.
/// </param>
public static IPage<Vault> ListByResourceGroup(this IVaultsOperations operations, string resourceGroupName, int? top = default(int?))
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).ListByResourceGroupAsync(resourceGroupName, top), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List operation gets information about the vaults associated with the
/// subscription and within the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='top'>
/// Maximum number of results to return.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Vault>> ListByResourceGroupAsync(this IVaultsOperations operations, string resourceGroupName, int? top = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about the deleted vaults in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<DeletedVault> ListDeleted(this IVaultsOperations operations)
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).ListDeletedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the deleted vaults in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DeletedVault>> ListDeletedAsync(this IVaultsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListDeletedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the deleted Azure key vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the vault.
/// </param>
/// <param name='location'>
/// The location of the deleted vault.
/// </param>
public static DeletedVault GetDeleted(this IVaultsOperations operations, string vaultName, string location)
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).GetDeletedAsync(vaultName, location), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the deleted Azure key vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the vault.
/// </param>
/// <param name='location'>
/// The location of the deleted vault.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DeletedVault> GetDeletedAsync(this IVaultsOperations operations, string vaultName, string location, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDeletedWithHttpMessagesAsync(vaultName, location, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified vault forever. aka Purges the deleted Azure key
/// vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the soft-deleted vault.
/// </param>
/// <param name='location'>
/// The location of the soft-deleted vault.
/// </param>
public static void PurgeDeleted(this IVaultsOperations operations, string vaultName, string location)
{
Task.Factory.StartNew(s => ((IVaultsOperations)s).PurgeDeletedAsync(vaultName, location), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified vault forever. aka Purges the deleted Azure key
/// vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the soft-deleted vault.
/// </param>
/// <param name='location'>
/// The location of the soft-deleted vault.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PurgeDeletedAsync(this IVaultsOperations operations, string vaultName, string location, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PurgeDeletedWithHttpMessagesAsync(vaultName, location, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the specified vault forever. aka Purges the deleted Azure key
/// vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the soft-deleted vault.
/// </param>
/// <param name='location'>
/// The location of the soft-deleted vault.
/// </param>
public static void BeginPurgeDeleted(this IVaultsOperations operations, string vaultName, string location)
{
Task.Factory.StartNew(s => ((IVaultsOperations)s).BeginPurgeDeletedAsync(vaultName, location), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified vault forever. aka Purges the deleted Azure key
/// vault.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the soft-deleted vault.
/// </param>
/// <param name='location'>
/// The location of the soft-deleted vault.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginPurgeDeletedAsync(this IVaultsOperations operations, string vaultName, string location, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginPurgeDeletedWithHttpMessagesAsync(vaultName, location, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The List operation gets information about the vaults associated with the
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// Maximum number of results to return.
/// </param>
public static IPage<Resource> List(this IVaultsOperations operations, int? top = default(int?))
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).ListAsync(top), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List operation gets information about the vaults associated with the
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// Maximum number of results to return.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Resource>> ListAsync(this IVaultsOperations operations, int? top = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List operation gets information about the vaults associated with the
/// subscription and within the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Vault> ListByResourceGroupNext(this IVaultsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List operation gets information about the vaults associated with the
/// subscription and within the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Vault>> ListByResourceGroupNextAsync(this IVaultsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about the deleted vaults in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<DeletedVault> ListDeletedNext(this IVaultsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).ListDeletedNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the deleted vaults in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DeletedVault>> ListDeletedNextAsync(this IVaultsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListDeletedNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List operation gets information about the vaults associated with the
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Resource> ListNext(this IVaultsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IVaultsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List operation gets information about the vaults associated with the
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Resource>> ListNextAsync(this IVaultsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.RecommendationEngine.V1Beta1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedPredictionApiKeyRegistryClientSnippets
{
/// <summary>Snippet for CreatePredictionApiKeyRegistration</summary>
public void CreatePredictionApiKeyRegistrationRequestObject()
{
// Snippet: CreatePredictionApiKeyRegistration(CreatePredictionApiKeyRegistrationRequest, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
CreatePredictionApiKeyRegistrationRequest request = new CreatePredictionApiKeyRegistrationRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
PredictionApiKeyRegistration = new PredictionApiKeyRegistration(),
};
// Make the request
PredictionApiKeyRegistration response = predictionApiKeyRegistryClient.CreatePredictionApiKeyRegistration(request);
// End snippet
}
/// <summary>Snippet for CreatePredictionApiKeyRegistrationAsync</summary>
public async Task CreatePredictionApiKeyRegistrationRequestObjectAsync()
{
// Snippet: CreatePredictionApiKeyRegistrationAsync(CreatePredictionApiKeyRegistrationRequest, CallSettings)
// Additional: CreatePredictionApiKeyRegistrationAsync(CreatePredictionApiKeyRegistrationRequest, CancellationToken)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
CreatePredictionApiKeyRegistrationRequest request = new CreatePredictionApiKeyRegistrationRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
PredictionApiKeyRegistration = new PredictionApiKeyRegistration(),
};
// Make the request
PredictionApiKeyRegistration response = await predictionApiKeyRegistryClient.CreatePredictionApiKeyRegistrationAsync(request);
// End snippet
}
/// <summary>Snippet for CreatePredictionApiKeyRegistration</summary>
public void CreatePredictionApiKeyRegistration()
{
// Snippet: CreatePredictionApiKeyRegistration(string, PredictionApiKeyRegistration, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
PredictionApiKeyRegistration predictionApiKeyRegistration = new PredictionApiKeyRegistration();
// Make the request
PredictionApiKeyRegistration response = predictionApiKeyRegistryClient.CreatePredictionApiKeyRegistration(parent, predictionApiKeyRegistration);
// End snippet
}
/// <summary>Snippet for CreatePredictionApiKeyRegistrationAsync</summary>
public async Task CreatePredictionApiKeyRegistrationAsync()
{
// Snippet: CreatePredictionApiKeyRegistrationAsync(string, PredictionApiKeyRegistration, CallSettings)
// Additional: CreatePredictionApiKeyRegistrationAsync(string, PredictionApiKeyRegistration, CancellationToken)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
PredictionApiKeyRegistration predictionApiKeyRegistration = new PredictionApiKeyRegistration();
// Make the request
PredictionApiKeyRegistration response = await predictionApiKeyRegistryClient.CreatePredictionApiKeyRegistrationAsync(parent, predictionApiKeyRegistration);
// End snippet
}
/// <summary>Snippet for CreatePredictionApiKeyRegistration</summary>
public void CreatePredictionApiKeyRegistrationResourceNames()
{
// Snippet: CreatePredictionApiKeyRegistration(EventStoreName, PredictionApiKeyRegistration, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
PredictionApiKeyRegistration predictionApiKeyRegistration = new PredictionApiKeyRegistration();
// Make the request
PredictionApiKeyRegistration response = predictionApiKeyRegistryClient.CreatePredictionApiKeyRegistration(parent, predictionApiKeyRegistration);
// End snippet
}
/// <summary>Snippet for CreatePredictionApiKeyRegistrationAsync</summary>
public async Task CreatePredictionApiKeyRegistrationResourceNamesAsync()
{
// Snippet: CreatePredictionApiKeyRegistrationAsync(EventStoreName, PredictionApiKeyRegistration, CallSettings)
// Additional: CreatePredictionApiKeyRegistrationAsync(EventStoreName, PredictionApiKeyRegistration, CancellationToken)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
PredictionApiKeyRegistration predictionApiKeyRegistration = new PredictionApiKeyRegistration();
// Make the request
PredictionApiKeyRegistration response = await predictionApiKeyRegistryClient.CreatePredictionApiKeyRegistrationAsync(parent, predictionApiKeyRegistration);
// End snippet
}
/// <summary>Snippet for ListPredictionApiKeyRegistrations</summary>
public void ListPredictionApiKeyRegistrationsRequestObject()
{
// Snippet: ListPredictionApiKeyRegistrations(ListPredictionApiKeyRegistrationsRequest, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
ListPredictionApiKeyRegistrationsRequest request = new ListPredictionApiKeyRegistrationsRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
};
// Make the request
PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> response = predictionApiKeyRegistryClient.ListPredictionApiKeyRegistrations(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (PredictionApiKeyRegistration item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPredictionApiKeyRegistrationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PredictionApiKeyRegistration item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PredictionApiKeyRegistration> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PredictionApiKeyRegistration item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPredictionApiKeyRegistrationsAsync</summary>
public async Task ListPredictionApiKeyRegistrationsRequestObjectAsync()
{
// Snippet: ListPredictionApiKeyRegistrationsAsync(ListPredictionApiKeyRegistrationsRequest, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
ListPredictionApiKeyRegistrationsRequest request = new ListPredictionApiKeyRegistrationsRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
};
// Make the request
PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> response = predictionApiKeyRegistryClient.ListPredictionApiKeyRegistrationsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PredictionApiKeyRegistration item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPredictionApiKeyRegistrationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PredictionApiKeyRegistration item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PredictionApiKeyRegistration> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PredictionApiKeyRegistration item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPredictionApiKeyRegistrations</summary>
public void ListPredictionApiKeyRegistrations()
{
// Snippet: ListPredictionApiKeyRegistrations(string, string, int?, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
// Make the request
PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> response = predictionApiKeyRegistryClient.ListPredictionApiKeyRegistrations(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PredictionApiKeyRegistration item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPredictionApiKeyRegistrationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PredictionApiKeyRegistration item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PredictionApiKeyRegistration> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PredictionApiKeyRegistration item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPredictionApiKeyRegistrationsAsync</summary>
public async Task ListPredictionApiKeyRegistrationsAsync()
{
// Snippet: ListPredictionApiKeyRegistrationsAsync(string, string, int?, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
// Make the request
PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> response = predictionApiKeyRegistryClient.ListPredictionApiKeyRegistrationsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PredictionApiKeyRegistration item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPredictionApiKeyRegistrationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PredictionApiKeyRegistration item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PredictionApiKeyRegistration> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PredictionApiKeyRegistration item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPredictionApiKeyRegistrations</summary>
public void ListPredictionApiKeyRegistrationsResourceNames()
{
// Snippet: ListPredictionApiKeyRegistrations(EventStoreName, string, int?, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
// Make the request
PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> response = predictionApiKeyRegistryClient.ListPredictionApiKeyRegistrations(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PredictionApiKeyRegistration item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPredictionApiKeyRegistrationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PredictionApiKeyRegistration item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PredictionApiKeyRegistration> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PredictionApiKeyRegistration item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPredictionApiKeyRegistrationsAsync</summary>
public async Task ListPredictionApiKeyRegistrationsResourceNamesAsync()
{
// Snippet: ListPredictionApiKeyRegistrationsAsync(EventStoreName, string, int?, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
// Make the request
PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> response = predictionApiKeyRegistryClient.ListPredictionApiKeyRegistrationsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PredictionApiKeyRegistration item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPredictionApiKeyRegistrationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PredictionApiKeyRegistration item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PredictionApiKeyRegistration> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PredictionApiKeyRegistration item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeletePredictionApiKeyRegistration</summary>
public void DeletePredictionApiKeyRegistrationRequestObject()
{
// Snippet: DeletePredictionApiKeyRegistration(DeletePredictionApiKeyRegistrationRequest, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
DeletePredictionApiKeyRegistrationRequest request = new DeletePredictionApiKeyRegistrationRequest
{
PredictionApiKeyRegistrationName = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]"),
};
// Make the request
predictionApiKeyRegistryClient.DeletePredictionApiKeyRegistration(request);
// End snippet
}
/// <summary>Snippet for DeletePredictionApiKeyRegistrationAsync</summary>
public async Task DeletePredictionApiKeyRegistrationRequestObjectAsync()
{
// Snippet: DeletePredictionApiKeyRegistrationAsync(DeletePredictionApiKeyRegistrationRequest, CallSettings)
// Additional: DeletePredictionApiKeyRegistrationAsync(DeletePredictionApiKeyRegistrationRequest, CancellationToken)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
DeletePredictionApiKeyRegistrationRequest request = new DeletePredictionApiKeyRegistrationRequest
{
PredictionApiKeyRegistrationName = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]"),
};
// Make the request
await predictionApiKeyRegistryClient.DeletePredictionApiKeyRegistrationAsync(request);
// End snippet
}
/// <summary>Snippet for DeletePredictionApiKeyRegistration</summary>
public void DeletePredictionApiKeyRegistration()
{
// Snippet: DeletePredictionApiKeyRegistration(string, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]/predictionApiKeyRegistrations/[PREDICTION_API_KEY_REGISTRATION]";
// Make the request
predictionApiKeyRegistryClient.DeletePredictionApiKeyRegistration(name);
// End snippet
}
/// <summary>Snippet for DeletePredictionApiKeyRegistrationAsync</summary>
public async Task DeletePredictionApiKeyRegistrationAsync()
{
// Snippet: DeletePredictionApiKeyRegistrationAsync(string, CallSettings)
// Additional: DeletePredictionApiKeyRegistrationAsync(string, CancellationToken)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]/predictionApiKeyRegistrations/[PREDICTION_API_KEY_REGISTRATION]";
// Make the request
await predictionApiKeyRegistryClient.DeletePredictionApiKeyRegistrationAsync(name);
// End snippet
}
/// <summary>Snippet for DeletePredictionApiKeyRegistration</summary>
public void DeletePredictionApiKeyRegistrationResourceNames()
{
// Snippet: DeletePredictionApiKeyRegistration(PredictionApiKeyRegistrationName, CallSettings)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = PredictionApiKeyRegistryClient.Create();
// Initialize request argument(s)
PredictionApiKeyRegistrationName name = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]");
// Make the request
predictionApiKeyRegistryClient.DeletePredictionApiKeyRegistration(name);
// End snippet
}
/// <summary>Snippet for DeletePredictionApiKeyRegistrationAsync</summary>
public async Task DeletePredictionApiKeyRegistrationResourceNamesAsync()
{
// Snippet: DeletePredictionApiKeyRegistrationAsync(PredictionApiKeyRegistrationName, CallSettings)
// Additional: DeletePredictionApiKeyRegistrationAsync(PredictionApiKeyRegistrationName, CancellationToken)
// Create client
PredictionApiKeyRegistryClient predictionApiKeyRegistryClient = await PredictionApiKeyRegistryClient.CreateAsync();
// Initialize request argument(s)
PredictionApiKeyRegistrationName name = PredictionApiKeyRegistrationName.FromProjectLocationCatalogEventStorePredictionApiKeyRegistration("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PREDICTION_API_KEY_REGISTRATION]");
// Make the request
await predictionApiKeyRegistryClient.DeletePredictionApiKeyRegistrationAsync(name);
// End snippet
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text;
using System.Globalization;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// writer class to handle Complex Object formatting
/// </summary>
internal sealed class ComplexWriter
{
/// <summary>
/// initalization method to be called before any other operation
/// </summary>
/// <param name="lineOutput">LineOutput interfaces to write to</param>
/// <param name="numberOfTextColumns">number of columns used to write out</param>
internal void Initialize(LineOutput lineOutput, int numberOfTextColumns)
{
_lo = lineOutput;
_textColumns = numberOfTextColumns;
}
/// <summary>
/// Writes a string
/// </summary>
/// <param name="s"></param>
internal void WriteString(string s)
{
_indentationManager.Clear();
AddToBuffer(s);
WriteToScreen();
}
/// <summary>
/// it interprets a list of format value tokens and outputs it
/// </summary>
/// <param name="formatValueList">list of FormatValue tokens to interpret</param>
internal void WriteObject(List<FormatValue> formatValueList)
{
// we always start with no identation
_indentationManager.Clear();
foreach (FormatEntry fe in formatValueList)
{
// operate on each directive inside the list,
// carrying the identation from invocation to invocation
GenerateFormatEntryDisplay(fe, 0);
}
// make sure that, if we have pending text in the buffer it gets flushed
WriteToScreen();
}
/// <summary>
/// operate on a single entry
/// </summary>
/// <param name="fe">entry to process</param>
/// <param name="currentDepth">current depth of recursion</param>
private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth)
{
foreach (object obj in fe.formatValueList)
{
FormatEntry feChild = obj as FormatEntry;
if (feChild != null)
{
if (currentDepth < maxRecursionDepth)
{
if (feChild.frameInfo != null)
{
// if we have frame information, we need to push it on the
// indentation stack
using (_indentationManager.StackFrame(feChild.frameInfo))
{
GenerateFormatEntryDisplay(feChild, currentDepth + 1);
}
}
else
{
// no need here of activating an indentation stack frame
GenerateFormatEntryDisplay(feChild, currentDepth + 1);
}
}
continue;
}
if (obj is FormatNewLine)
{
this.WriteToScreen();
continue;
}
FormatTextField ftf = obj as FormatTextField;
if (ftf != null)
{
this.AddToBuffer(ftf.text);
continue;
}
FormatPropertyField fpf = obj as FormatPropertyField;
if (fpf != null)
{
this.AddToBuffer(fpf.propertyValue);
}
}
}
/// <summary>
/// add a string to the current buffer, waiting for a FlushBuffer()
/// </summary>
/// <param name="s">string to add to buffer</param>
private void AddToBuffer(string s)
{
_stringBuffer.Append(s);
}
/// <summary>
/// write to the output interface
/// </summary>
private void WriteToScreen()
{
int leftIndentation = _indentationManager.LeftIndentation;
int rightIndentation = _indentationManager.RightIndentation;
int firstLineIndentation = _indentationManager.FirstLineIndentation;
// VALIDITY CHECKS:
// check the useful ("active") witdth
int usefulWidth = _textColumns - rightIndentation - leftIndentation;
if (usefulWidth <= 0)
{
// fatal error, there is nothing to write to the device
// just clear the buffer and return
_stringBuffer = new StringBuilder();
}
// check indentation or hanging is not larger than the active width
int indentationAbsoluteValue = (firstLineIndentation > 0) ? firstLineIndentation : -firstLineIndentation;
if (indentationAbsoluteValue >= usefulWidth)
{
// valu too big, we reset it to zero
firstLineIndentation = 0;
}
// compute the first line indentation or hanging
int firstLineWidth = _textColumns - rightIndentation - leftIndentation;
int followingLinesWidth = firstLineWidth;
if (firstLineIndentation >= 0)
{
// the first line has an indentation
firstLineWidth -= firstLineIndentation;
}
else
{
// the first line is hanging
followingLinesWidth += firstLineIndentation;
}
//error checking on invalid values
// generate the lines using the computed widths
StringCollection sc = StringManipulationHelper.GenerateLines(_lo.DisplayCells, _stringBuffer.ToString(),
firstLineWidth, followingLinesWidth);
// compute padding
int firstLinePadding = leftIndentation;
int followingLinesPadding = leftIndentation;
if (firstLineIndentation >= 0)
{
// the first line has an indentation
firstLinePadding += firstLineIndentation;
}
else
{
// the first line is hanging
followingLinesPadding -= firstLineIndentation;
}
// now write the lines on the screen
bool firstLine = true;
foreach (string s in sc)
{
if (firstLine)
{
firstLine = false;
_lo.WriteLine(StringManipulationHelper.PadLeft(s, firstLinePadding));
}
else
{
_lo.WriteLine(StringManipulationHelper.PadLeft(s, followingLinesPadding));
}
}
_stringBuffer = new StringBuilder();
}
/// <summary>
/// helper object to manage the frame-based indentation and margins
/// </summary>
private IndentationManager _indentationManager = new IndentationManager();
/// <summary>
/// buffer to accumulate partially constructed text
/// </summary>
private StringBuilder _stringBuffer = new StringBuilder();
/// <summary>
/// interface to write to
/// </summary>
private LineOutput _lo;
/// <summary>
/// nomber of columns for the output device
/// </summary>
private int _textColumns;
private const int maxRecursionDepth = 50;
}
internal sealed class IndentationManager
{
private sealed class IndentationStackFrame : IDisposable
{
internal IndentationStackFrame(IndentationManager mgr)
{
_mgr = mgr;
}
public void Dispose()
{
if (_mgr != null)
{
_mgr.RemoveStackFrame();
}
}
private IndentationManager _mgr;
}
internal void Clear()
{
_frameInfoStack.Clear();
}
internal IDisposable StackFrame(FrameInfo frameInfo)
{
IndentationStackFrame frame = new IndentationStackFrame(this);
_frameInfoStack.Push(frameInfo);
return frame;
}
private void RemoveStackFrame()
{
_frameInfoStack.Pop();
}
internal int RightIndentation
{
get
{
return ComputeRightIndentation();
}
}
internal int LeftIndentation
{
get
{
return ComputeLeftIndentation();
}
}
internal int FirstLineIndentation
{
get
{
if (_frameInfoStack.Count == 0)
return 0;
return _frameInfoStack.Peek().firstLine;
}
}
private int ComputeRightIndentation()
{
int val = 0;
foreach (FrameInfo fi in _frameInfoStack)
{
val += fi.rightIndentation;
}
return val;
}
private int ComputeLeftIndentation()
{
int val = 0;
foreach (FrameInfo fi in _frameInfoStack)
{
val += fi.leftIndentation;
}
return val;
}
private Stack<FrameInfo> _frameInfoStack = new Stack<FrameInfo>();
}
/// <summary>
/// Result of GetWords
/// </summary>
internal struct GetWordsResult
{
internal string Word;
internal string Delim;
}
/// <summary>
/// collection of helper functions for string formatting
/// </summary>
internal sealed class StringManipulationHelper
{
private static readonly char s_softHyphen = '\u00AD';
private static readonly char s_hardHyphen = '\u2011';
private static readonly char s_nonBreakingSpace = '\u00A0';
private static Collection<string> s_cultureCollection = new Collection<string>();
static StringManipulationHelper()
{
s_cultureCollection.Add("en"); // English
s_cultureCollection.Add("fr"); // French
s_cultureCollection.Add("de"); // German
s_cultureCollection.Add("it"); // Italian
s_cultureCollection.Add("pt"); // Portuguese
s_cultureCollection.Add("es"); // Spanish
}
/// <summary>
/// Breaks a string into a collection of words
/// TODO: we might be able to improve this function in the future
/// so that we do not break paths etc.
/// </summary>
/// <param name="s">input string</param>
/// <returns>a collection of words</returns>
private static IEnumerable<GetWordsResult> GetWords(string s)
{
StringBuilder sb = new StringBuilder();
GetWordsResult result = new GetWordsResult();
for (int i = 0; i < s.Length; i++)
{
// Soft hyphen = \u00AD - Should break, and add a hyphen if needed. If not needed for a break, hyphen should be absent
if (s[i] == ' ' || s[i] == '\t' || s[i] == s_softHyphen)
{
result.Word = sb.ToString();
sb.Clear();
result.Delim = new String(s[i], 1);
yield return result;
}
// Non-breaking space = \u00A0 - ideally shouldn't wrap
// Hard hyphen = \u2011 - Should not break
else if (s[i] == s_hardHyphen || s[i] == s_nonBreakingSpace)
{
result.Word = sb.ToString();
sb.Clear();
result.Delim = String.Empty;
yield return result;
}
else
{
sb.Append(s[i]);
}
}
result.Word = sb.ToString();
result.Delim = String.Empty;
yield return result;
}
internal static StringCollection GenerateLines(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen)
{
if (s_cultureCollection.Contains(CultureInfo.CurrentCulture.TwoLetterISOLanguageName))
{
return GenerateLinesWithWordWrap(displayCells, val, firstLineLen, followingLinesLen);
}
else
{
return GenerateLinesWithoutWordWrap(displayCells, val, firstLineLen, followingLinesLen);
}
}
private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen)
{
StringCollection retVal = new StringCollection();
if (string.IsNullOrEmpty(val))
{
// if null or empty, just add and we are done
retVal.Add(val);
return retVal;
}
// break string on newlines and process each line separately
string[] lines = SplitLines(val);
for (int k = 0; k < lines.Length; k++)
{
if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen)
{
// we do not need to split further, just add
retVal.Add(lines[k]);
continue;
}
// the string does not fit, so we have to wrap around on multiple lines
// for each of these lines in the string, the first line will have
// a (potentially) different length (indentation or hanging)
// for each line, start a new state
SplitLinesAccumulator accumulator = new SplitLinesAccumulator(retVal, firstLineLen, followingLinesLen);
int offset = 0; // offset into the line we are splitting
while (true)
{
// acquire the current active display line length (it can very from call to call)
int currentDisplayLen = accumulator.ActiveLen;
// determine if the current tail would fit or not
// for the remaining part of the string, determine its display cell count
int currentCellsToFit = displayCells.Length(lines[k], offset);
// determine if we fit into the line
int excessCells = currentCellsToFit - currentDisplayLen;
if (excessCells > 0)
{
// we are not at the end of the string, select a sub string
// that would fit in the remaining display length
int charactersToAdd = displayCells.GetHeadSplitLength(lines[k], offset, currentDisplayLen);
if (charactersToAdd <= 0)
{
// corner case: we have a two cell character and the current
// display length is one.
// add a single cell arbitrary character instead of the original
// one and keep going
charactersToAdd = 1;
accumulator.AddLine("?");
}
else
{
// of the given lenght, add it to the accumulator
accumulator.AddLine(lines[k].Substring(offset, charactersToAdd));
}
// increase the offest by the # of characters added
offset += charactersToAdd;
}
else
{
// we reached the last (partial) line, we add it all
accumulator.AddLine(lines[k].Substring(offset));
break;
}
}
}
return retVal;
}
private sealed class SplitLinesAccumulator
{
internal SplitLinesAccumulator(StringCollection retVal, int firstLineLen, int followingLinesLen)
{
_retVal = retVal;
_firstLineLen = firstLineLen;
_followingLinesLen = followingLinesLen;
}
internal void AddLine(string s)
{
if (!_addedFirstLine)
{
_addedFirstLine = true;
}
_retVal.Add(s);
}
internal int ActiveLen
{
get
{
if (_addedFirstLine)
return _followingLinesLen;
return _firstLineLen;
}
}
private StringCollection _retVal;
private bool _addedFirstLine;
private int _firstLineLen;
private int _followingLinesLen;
}
private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen)
{
StringCollection retVal = new StringCollection();
if (string.IsNullOrEmpty(val))
{
// if null or empty, just add and we are done
retVal.Add(val);
return retVal;
}
// break string on newlines and process each line separately
string[] lines = SplitLines(val);
for (int k = 0; k < lines.Length; k++)
{
if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen)
{
// we do not need to split further, just add
retVal.Add(lines[k]);
continue;
}
int spacesLeft = firstLineLen;
int lineWidth = firstLineLen;
bool firstLine = true;
StringBuilder singleLine = new StringBuilder();
foreach (GetWordsResult word in GetWords(lines[k]))
{
string wordToAdd = word.Word;
// Handle soft hyphen
if (word.Delim == s_softHyphen.ToString())
{
int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(s_softHyphen.ToString());
// Add hyphen only if necessary
if (wordWidthWithHyphen == spacesLeft)
{
wordToAdd += "-";
}
}
else
{
if (!String.IsNullOrEmpty(word.Delim))
{
wordToAdd += word.Delim;
}
}
int wordWidth = displayCells.Length(wordToAdd);
// Handle zero width
if (lineWidth == 0)
{
if (firstLine)
{
firstLine = false;
lineWidth = followingLinesLen;
}
if (lineWidth == 0)
{
break;
}
spacesLeft = lineWidth;
}
// Word is wider than a single line
if (wordWidth > lineWidth)
{
foreach (char c in wordToAdd)
{
char charToAdd = c;
int charWidth = displayCells.Length(c);
// corner case: we have a two cell character and the current
// display length is one.
// add a single cell arbitrary character instead of the original
// one and keep going
if (charWidth > lineWidth)
{
charToAdd = '?';
charWidth = 1;
}
if (charWidth > spacesLeft)
{
retVal.Add(singleLine.ToString());
singleLine.Clear();
singleLine.Append(charToAdd);
if (firstLine)
{
firstLine = false;
lineWidth = followingLinesLen;
}
spacesLeft = lineWidth - charWidth;
}
else
{
singleLine.Append(charToAdd);
spacesLeft -= charWidth;
}
}
}
else
{
if (wordWidth > spacesLeft)
{
retVal.Add(singleLine.ToString());
singleLine.Clear();
singleLine.Append(wordToAdd);
if (firstLine)
{
firstLine = false;
lineWidth = followingLinesLen;
}
spacesLeft = lineWidth - wordWidth;
}
else
{
singleLine.Append(wordToAdd);
spacesLeft -= wordWidth;
}
}
}
retVal.Add(singleLine.ToString());
}
return retVal;
}
/// <summary>
/// split a multiline string into an array of strings
/// by honoring both \n and \r\n
/// </summary>
/// <param name="s">string to split</param>
/// <returns>string array with the values</returns>
internal static string[] SplitLines(string s)
{
if (string.IsNullOrEmpty(s))
return new string[1] { s };
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
if (c != '\r')
sb.Append(c);
}
return sb.ToString().Split(s_newLineChar);
}
#if false
internal static string StripNewLines (string s)
{
if (string.IsNullOrEmpty (s))
return s;
string[] lines = SplitLines (s);
if (lines.Length == 0)
return null;
if (lines.Length == 1)
return lines[0];
StringBuilder sb = new StringBuilder ();
for (int k = 0; k < lines.Length; k++)
{
if (k == 0)
sb.Append (lines[k]);
else
sb.Append (" " + lines[k]);
}
return sb.ToString ();
}
#endif
internal static string TruncateAtNewLine(string s)
{
if (string.IsNullOrEmpty(s))
return s;
int lineBreak = s.IndexOfAny(s_lineBreakChars);
if (lineBreak < 0)
return s;
return s.Substring(0, lineBreak) + PSObjectHelper.ellipses;
}
internal static string PadLeft(string val, int count)
{
return new string(' ', count) + val;
}
private static readonly char[] s_newLineChar = new char[] { '\n' };
private static readonly char[] s_lineBreakChars = new char[] { '\n', '\r' };
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal class ExpressionTreeRewriter : ExprVisitorBase
{
public static EXPR Rewrite(EXPR expr, ExprFactory expressionFactory, SymbolLoader symbolLoader)
{
ExpressionTreeRewriter rewriter = new ExpressionTreeRewriter(expressionFactory, symbolLoader);
rewriter.alwaysRewrite = true;
return rewriter.Visit(expr);
}
protected ExprFactory expressionFactory;
protected SymbolLoader symbolLoader;
protected EXPRBOUNDLAMBDA currentAnonMeth;
protected bool alwaysRewrite;
protected ExprFactory GetExprFactory() { return expressionFactory; }
protected SymbolLoader GetSymbolLoader() { return symbolLoader; }
protected ExpressionTreeRewriter(ExprFactory expressionFactory, SymbolLoader symbolLoader)
{
this.expressionFactory = expressionFactory;
this.symbolLoader = symbolLoader;
this.alwaysRewrite = false;
}
protected override EXPR Dispatch(EXPR expr)
{
Debug.Assert(expr != null);
EXPR result;
result = base.Dispatch(expr);
if (result == expr)
{
throw Error.InternalCompilerError();
}
return result;
}
/////////////////////////////////////////////////////////////////////////////////
// Statement types.
protected override EXPR VisitASSIGNMENT(EXPRASSIGNMENT assignment)
{
Debug.Assert(assignment != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
// For assignments, we either have a member assignment or an indexed assignment.
//Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL());
EXPR lhs;
if (assignment.GetLHS().isPROP())
{
EXPRPROP prop = assignment.GetLHS().asPROP();
if (prop.GetOptionalArguments() == null)
{
// Regular property.
lhs = Visit(prop);
}
else
{
// Indexed assignment. Here we need to find the instance of the object, create the
// PropInfo for the thing, and get the array of expressions that make up the index arguments.
//
// The LHS becomes Expression.Property(instance, indexerInfo, arguments).
EXPR instance = Visit(prop.GetMemberGroup().GetOptionalObject());
EXPR propInfo = GetExprFactory().CreatePropertyInfo(prop.pwtSlot.Prop(), prop.pwtSlot.Ats);
EXPR arguments = GenerateParamsArray(
GenerateArgsList(prop.GetOptionalArguments()),
PredefinedType.PT_EXPRESSION);
lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments);
}
}
else
{
lhs = Visit(assignment.GetLHS());
}
EXPR rhs = Visit(assignment.GetRHS());
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
}
protected override EXPR VisitMULTIGET(EXPRMULTIGET pExpr)
{
return Visit(pExpr.GetOptionalMulti().Left);
}
protected override EXPR VisitMULTI(EXPRMULTI pExpr)
{
EXPR rhs = Visit(pExpr.Operator);
EXPR lhs = Visit(pExpr.Left);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
}
/////////////////////////////////////////////////////////////////////////////////
// Expression types.
protected override EXPR VisitBOUNDLAMBDA(EXPRBOUNDLAMBDA anonmeth)
{
Debug.Assert(anonmeth != null);
EXPRBOUNDLAMBDA prevAnonMeth = currentAnonMeth;
currentAnonMeth = anonmeth;
MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA);
CType delegateType = anonmeth.DelegateType();
TypeArray lambdaTypeParams = GetSymbolLoader().getBSymmgr().AllocParams(1, new CType[] { delegateType });
AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true);
MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams);
EXPR createParameters = CreateWraps(anonmeth);
EXPR body = RewriteLambdaBody(anonmeth);
EXPR parameters = RewriteLambdaParameters(anonmeth);
EXPR args = GetExprFactory().CreateList(body, parameters);
CType typeRet = GetSymbolLoader().GetTypeManager().SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs);
EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
EXPR callLambda = GetExprFactory().CreateCall(0, typeRet, args, pMemGroup, mwi);
callLambda.asCALL().PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA;
currentAnonMeth = prevAnonMeth;
if (createParameters != null)
{
callLambda = GetExprFactory().CreateSequence(createParameters, callLambda);
}
EXPR expr = DestroyWraps(anonmeth, callLambda);
// If we are already inside an expression tree rewrite and this is an expression tree lambda
// then it needs to be quoted.
if (currentAnonMeth != null)
{
expr = GenerateCall(PREDEFMETH.PM_EXPRESSION_QUOTE, expr);
}
return expr;
}
protected override EXPR VisitCONSTANT(EXPRCONSTANT expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
return GenerateConstant(expr);
}
protected override EXPR VisitLOCAL(EXPRLOCAL local)
{
Debug.Assert(local != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
Debug.Assert(!local.local.isThis);
// this is true for all parameters of an expression lambda
if (local.local.wrap != null)
{
return local.local.wrap;
}
Debug.Assert(local.local.fUsedInAnonMeth);
return GetExprFactory().CreateHoistedLocalInExpression(local);
}
protected override EXPR VisitTHISPOINTER(EXPRTHISPOINTER expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
Debug.Assert(expr.local.isThis);
return GenerateConstant(expr);
}
protected override EXPR VisitFIELD(EXPRFIELD expr)
{
Debug.Assert(expr != null);
EXPR pObject;
if (expr.GetOptionalObject() == null)
{
pObject = GetExprFactory().CreateNull();
}
else
{
pObject = Visit(expr.GetOptionalObject());
}
EXPRFIELDINFO pFieldInfo = GetExprFactory().CreateFieldInfo(expr.fwt.Field(), expr.fwt.GetType());
return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo);
}
protected override EXPR VisitUSERDEFINEDCONVERSION(EXPRUSERDEFINEDCONVERSION expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
return GenerateUserDefinedConversion(expr, expr.Argument);
}
protected override EXPR VisitCAST(EXPRCAST pExpr)
{
Debug.Assert(pExpr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
EXPR pArgument = pExpr.GetArgument();
// If we have generated an identity cast or reference cast to a base class
// we can omit the cast.
if (pArgument.type == pExpr.type ||
GetSymbolLoader().IsBaseClassOfClass(pArgument.type, pExpr.type) ||
CConversions.FImpRefConv(GetSymbolLoader(), pArgument.type, pExpr.type))
{
return Visit(pArgument);
}
// If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is
// a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree.
if (pExpr.type != null &&
pExpr.type.isPredefType(PredefinedType.PT_G_EXPRESSION) &&
pArgument.isBOUNDLAMBDA())
{
return Visit(pArgument);
}
EXPR result = GenerateConversion(pArgument, pExpr.type, pExpr.isChecked());
if ((pExpr.flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0)
{
// Propagate the unbox flag to the call for the ExpressionTreeCallRewriter.
result.flags |= EXPRFLAG.EXF_UNBOXRUNTIME;
}
return result;
}
protected override EXPR VisitCONCAT(EXPRCONCAT expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
if (expr.GetFirstArgument().type.isPredefType(PredefinedType.PT_STRING) && expr.GetSecondArgument().type.isPredefType(PredefinedType.PT_STRING))
{
pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2;
}
else
{
pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2;
}
EXPR p1 = Visit(expr.GetFirstArgument());
EXPR p2 = Visit(expr.GetSecondArgument());
MethodSymbol method = GetPreDefMethod(pdm);
EXPR methodInfo = GetExprFactory().CreateMethodInfo(method, GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING), null);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo);
}
protected override EXPR VisitBINOP(EXPRBINOP expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
if (expr.GetUserDefinedCallMethod() != null)
{
return GenerateUserDefinedBinaryOperator(expr);
}
else
{
return GenerateBuiltInBinaryOperator(expr);
}
}
protected override EXPR VisitUNARYOP(EXPRUNARYOP pExpr)
{
Debug.Assert(pExpr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
if (pExpr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedUnaryOperator(pExpr);
}
else
{
return GenerateBuiltInUnaryOperator(pExpr);
}
}
protected override EXPR VisitARRAYINDEX(EXPRARRAYINDEX pExpr)
{
Debug.Assert(pExpr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
EXPR arr = Visit(pExpr.GetArray());
EXPR args = GenerateIndexList(pExpr.GetIndex());
if (args.isLIST())
{
EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params);
}
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args);
}
protected override EXPR VisitARRAYLENGTH(EXPRARRAYLENGTH pExpr)
{
return GenerateBuiltInUnaryOperator(PREDEFMETH.PM_EXPRESSION_ARRAYLENGTH, pExpr.GetArray(), pExpr);
}
protected override EXPR VisitQUESTIONMARK(EXPRQUESTIONMARK pExpr)
{
Debug.Assert(pExpr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
EXPR p1 = Visit(pExpr.GetTestExpression());
EXPR p2 = GenerateQuestionMarkOperand(pExpr.GetConsequence().asBINOP().GetOptionalLeftChild());
EXPR p3 = GenerateQuestionMarkOperand(pExpr.GetConsequence().asBINOP().GetOptionalRightChild());
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONDITION, p1, p2, p3);
}
protected override EXPR VisitCALL(EXPRCALL expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
switch (expr.nubLiftKind)
{
default:
break;
case NullableCallLiftKind.NullableIntermediateConversion:
case NullableCallLiftKind.NullableConversion:
case NullableCallLiftKind.NullableConversionConstructor:
return GenerateConversion(expr.GetOptionalArguments(), expr.type, expr.isChecked());
case NullableCallLiftKind.NotLiftedIntermediateConversion:
case NullableCallLiftKind.UserDefinedConversion:
return GenerateUserDefinedConversion(expr.GetOptionalArguments(), expr.type, expr.mwi);
}
if (expr.mwi.Meth().IsConstructor())
{
return GenerateConstructor(expr);
}
EXPRMEMGRP memberGroup = expr.GetMemberGroup();
if (memberGroup.isDelegate())
{
return GenerateDelegateInvoke(expr);
}
EXPR pObject;
if (expr.mwi.Meth().isStatic || expr.GetMemberGroup().GetOptionalObject() == null)
{
pObject = GetExprFactory().CreateNull();
}
else
{
pObject = expr.GetMemberGroup().GetOptionalObject();
// If we have, say, an int? which is the object of a call to ToString
// then we do NOT want to generate ((object)i).ToString() because that
// will convert a null-valued int? to a null object. Rather what we want
// to do is box it to a ValueType and call ValueType.ToString.
//
// To implement this we say that if the object of the call is an implicit boxing cast
// then just generate the object, not the cast. If the cast is explicit in the
// source code then it will be an EXPLICITCAST and we will visit it normally.
//
// It might be better to rewrite the expression tree API so that it
// can handle in the general case all implicit boxing conversions. Right now it
// requires that all arguments to a call that need to be boxed be explicitly boxed.
if (pObject != null && pObject.isCAST() && pObject.asCAST().IsBoxingCast())
{
pObject = pObject.asCAST().GetArgument();
}
pObject = Visit(pObject);
}
EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.mwi);
EXPR args = GenerateArgsList(expr.GetOptionalArguments());
EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL;
Debug.Assert(!expr.mwi.Meth().isVirtual || expr.GetMemberGroup().GetOptionalObject() != null);
return GenerateCall(pdm, pObject, methodInfo, Params);
}
protected override EXPR VisitPROP(EXPRPROP expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
EXPR pObject;
if (expr.pwtSlot.Prop().isStatic || expr.GetMemberGroup().GetOptionalObject() == null)
{
pObject = GetExprFactory().CreateNull();
}
else
{
pObject = Visit(expr.GetMemberGroup().GetOptionalObject());
}
EXPR propInfo = GetExprFactory().CreatePropertyInfo(expr.pwtSlot.Prop(), expr.pwtSlot.GetType());
if (expr.GetOptionalArguments() != null)
{
// It is an indexer property. Turn it into a virtual method call.
EXPR args = GenerateArgsList(expr.GetOptionalArguments());
EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params);
}
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo);
}
protected override EXPR VisitARRINIT(EXPRARRINIT expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
// POSSIBLE ERROR: Multi-d should be an error?
EXPR pTypeOf = CreateTypeOf(expr.type.AsArrayType().GetElementType());
EXPR args = GenerateArgsList(expr.GetOptionalArguments());
EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params);
}
protected override EXPR VisitZEROINIT(EXPRZEROINIT expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
Debug.Assert(expr.OptionalArgument == null);
if (expr.IsConstructor)
{
// We have a parameterless "new MyStruct()" which has been realized as a zero init.
EXPRTYPEOF pTypeOf = CreateTypeOf(expr.type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW_TYPE, pTypeOf);
}
return GenerateConstant(expr);
}
protected override EXPR VisitTYPEOF(EXPRTYPEOF expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
return GenerateConstant(expr);
}
protected virtual EXPR GenerateQuestionMarkOperand(EXPR pExpr)
{
Debug.Assert(pExpr != null);
// We must not optimize away compiler-generated reference casts because
// the expression tree API insists that the CType of both sides be identical.
if (pExpr.isCAST())
{
return GenerateConversion(pExpr.asCAST().GetArgument(), pExpr.type, pExpr.isChecked());
}
return Visit(pExpr);
}
protected virtual EXPR GenerateDelegateInvoke(EXPRCALL expr)
{
Debug.Assert(expr != null);
EXPRMEMGRP memberGroup = expr.GetMemberGroup();
Debug.Assert(memberGroup.isDelegate());
EXPR oldObject = memberGroup.GetOptionalObject();
Debug.Assert(oldObject != null);
EXPR pObject = Visit(oldObject);
EXPR args = GenerateArgsList(expr.GetOptionalArguments());
EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params);
}
protected virtual EXPR GenerateBuiltInBinaryOperator(EXPRBINOP expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
switch (expr.kind)
{
case ExpressionKind.EK_LSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT; break;
case ExpressionKind.EK_RSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT; break;
case ExpressionKind.EK_BITXOR: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR; break;
case ExpressionKind.EK_BITOR: pdm = PREDEFMETH.PM_EXPRESSION_OR; break;
case ExpressionKind.EK_BITAND: pdm = PREDEFMETH.PM_EXPRESSION_AND; break;
case ExpressionKind.EK_LOGAND: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO; break;
case ExpressionKind.EK_LOGOR: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE; break;
case ExpressionKind.EK_STRINGEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break;
case ExpressionKind.EK_EQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break;
case ExpressionKind.EK_STRINGNE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break;
case ExpressionKind.EK_NE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break;
case ExpressionKind.EK_GE: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL; break;
case ExpressionKind.EK_LE: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL; break;
case ExpressionKind.EK_LT: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN; break;
case ExpressionKind.EK_GT: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN; break;
case ExpressionKind.EK_MOD: pdm = PREDEFMETH.PM_EXPRESSION_MODULO; break;
case ExpressionKind.EK_DIV: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE; break;
case ExpressionKind.EK_MUL:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY;
break;
case ExpressionKind.EK_SUB:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT;
break;
case ExpressionKind.EK_ADD:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD;
break;
default:
throw Error.InternalCompilerError();
}
EXPR origL = expr.GetOptionalLeftChild();
EXPR origR = expr.GetOptionalRightChild();
Debug.Assert(origL != null);
Debug.Assert(origR != null);
CType typeL = origL.type;
CType typeR = origR.type;
EXPR newL = Visit(origL);
EXPR newR = Visit(origR);
bool didEnumConversion = false;
CType convertL = null;
CType convertR = null;
if (typeL.isEnumType())
{
// We have already inserted casts if not lifted, so we should never see an enum.
Debug.Assert(expr.isLifted);
convertL = GetSymbolLoader().GetTypeManager().GetNullable(typeL.underlyingEnumType());
typeL = convertL;
didEnumConversion = true;
}
else if (typeL.IsNullableType() && typeL.StripNubs().isEnumType())
{
Debug.Assert(expr.isLifted);
convertL = GetSymbolLoader().GetTypeManager().GetNullable(typeL.StripNubs().underlyingEnumType());
typeL = convertL;
didEnumConversion = true;
}
if (typeR.isEnumType())
{
Debug.Assert(expr.isLifted);
convertR = GetSymbolLoader().GetTypeManager().GetNullable(typeR.underlyingEnumType());
typeR = convertR;
didEnumConversion = true;
}
else if (typeR.IsNullableType() && typeR.StripNubs().isEnumType())
{
Debug.Assert(expr.isLifted);
convertR = GetSymbolLoader().GetTypeManager().GetNullable(typeR.StripNubs().underlyingEnumType());
typeR = convertR;
didEnumConversion = true;
}
if (typeL.IsNullableType() && typeL.StripNubs() == typeR)
{
convertR = typeL;
}
if (typeR.IsNullableType() && typeR.StripNubs() == typeL)
{
convertL = typeR;
}
if (convertL != null)
{
newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL));
}
if (convertR != null)
{
newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR));
}
EXPR call = GenerateCall(pdm, newL, newR);
if (didEnumConversion && expr.type.StripNubs().isEnumType())
{
call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.type));
}
return call;
}
protected virtual EXPR GenerateBuiltInUnaryOperator(EXPRUNARYOP expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
switch (expr.kind)
{
case ExpressionKind.EK_UPLUS:
return Visit(expr.Child);
case ExpressionKind.EK_BITNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
case ExpressionKind.EK_LOGNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
case ExpressionKind.EK_NEG:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE;
break;
default:
throw Error.InternalCompilerError();
}
EXPR origOp = expr.Child;
return GenerateBuiltInUnaryOperator(pdm, origOp, expr);
}
protected virtual EXPR GenerateBuiltInUnaryOperator(PREDEFMETH pdm, EXPR pOriginalOperator, EXPR pOperator)
{
EXPR op = Visit(pOriginalOperator);
if (pOriginalOperator.type.IsNullableType() && pOriginalOperator.type.StripNubs().isEnumType())
{
Debug.Assert(pOperator.kind == ExpressionKind.EK_BITNOT); // The only built-in unary operator defined on nullable enum.
CType underlyingType = pOriginalOperator.type.StripNubs().underlyingEnumType();
CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType);
op = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, op, CreateTypeOf(nullableType));
}
EXPR call = GenerateCall(pdm, op);
if (pOriginalOperator.type.IsNullableType() && pOriginalOperator.type.StripNubs().isEnumType())
{
call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(pOperator.type));
}
return call;
}
protected virtual EXPR GenerateUserDefinedBinaryOperator(EXPRBINOP expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
switch (expr.kind)
{
case ExpressionKind.EK_LOGOR: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break;
case ExpressionKind.EK_LOGAND: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break;
case ExpressionKind.EK_LSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break;
case ExpressionKind.EK_RSHIFT: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break;
case ExpressionKind.EK_BITXOR: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break;
case ExpressionKind.EK_BITOR: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break;
case ExpressionKind.EK_BITAND: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break;
case ExpressionKind.EK_MOD: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break;
case ExpressionKind.EK_DIV: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break;
case ExpressionKind.EK_STRINGEQ:
case ExpressionKind.EK_STRINGNE:
case ExpressionKind.EK_DELEGATEEQ:
case ExpressionKind.EK_DELEGATENE:
case ExpressionKind.EK_EQ:
case ExpressionKind.EK_NE:
case ExpressionKind.EK_GE:
case ExpressionKind.EK_GT:
case ExpressionKind.EK_LE:
case ExpressionKind.EK_LT:
return GenerateUserDefinedComparisonOperator(expr);
case ExpressionKind.EK_DELEGATESUB:
case ExpressionKind.EK_SUB:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED;
break;
case ExpressionKind.EK_DELEGATEADD:
case ExpressionKind.EK_ADD:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED;
break;
case ExpressionKind.EK_MUL:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED;
break;
default:
throw Error.InternalCompilerError();
}
EXPR p1 = expr.GetOptionalLeftChild();
EXPR p2 = expr.GetOptionalRightChild();
EXPR udcall = expr.GetOptionalUserDefinedCall();
if (udcall != null)
{
Debug.Assert(udcall.kind == ExpressionKind.EK_CALL || udcall.kind == ExpressionKind.EK_USERLOGOP);
if (udcall.kind == ExpressionKind.EK_CALL)
{
EXPRLIST args = udcall.asCALL().GetOptionalArguments().asLIST();
Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST);
p1 = args.GetOptionalElement();
p2 = args.GetOptionalNextListNode();
}
else
{
EXPRLIST args = udcall.asUSERLOGOP().OperatorCall.GetOptionalArguments().asLIST();
Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST);
p1 = args.GetOptionalElement().asWRAP().GetOptionalExpression();
p2 = args.GetOptionalNextListNode();
}
}
p1 = Visit(p1);
p2 = Visit(p2);
FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.GetUserDefinedCallMethod());
EXPR call = GenerateCall(pdm, p1, p2, methodInfo);
// Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate,
// not the operand delegate CType. We must cast to the delegate CType.
if (expr.kind == ExpressionKind.EK_DELEGATESUB || expr.kind == ExpressionKind.EK_DELEGATEADD)
{
EXPR pTypeOf = CreateTypeOf(expr.type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf);
}
return call;
}
protected virtual EXPR GenerateUserDefinedUnaryOperator(EXPRUNARYOP expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
EXPR arg = expr.Child;
EXPRCALL call = expr.OptionalUserDefinedCall.asCALL();
if (call != null)
{
// Use the actual argument of the call; it may contain user-defined
// conversions or be a bound lambda, and that will not be in the original
// argument stashed away in the left child of the operator.
arg = call.GetOptionalArguments();
}
Debug.Assert(arg != null && arg.kind != ExpressionKind.EK_LIST);
switch (expr.kind)
{
case ExpressionKind.EK_TRUE:
case ExpressionKind.EK_FALSE:
return Visit(call);
case ExpressionKind.EK_UPLUS:
pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED;
break;
case ExpressionKind.EK_BITNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
case ExpressionKind.EK_LOGNOT: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
case ExpressionKind.EK_DECIMALNEG:
case ExpressionKind.EK_NEG:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED;
break;
case ExpressionKind.EK_INC:
case ExpressionKind.EK_DEC:
case ExpressionKind.EK_DECIMALINC:
case ExpressionKind.EK_DECIMALDEC:
pdm = PREDEFMETH.PM_EXPRESSION_CALL;
break;
default:
throw Error.InternalCompilerError();
}
EXPR op = Visit(arg);
EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.UserDefinedCallMethod);
if (expr.kind == ExpressionKind.EK_INC || expr.kind == ExpressionKind.EK_DEC ||
expr.kind == ExpressionKind.EK_DECIMALINC || expr.kind == ExpressionKind.EK_DECIMALDEC)
{
return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION));
}
return GenerateCall(pdm, op, methodInfo);
}
protected virtual EXPR GenerateUserDefinedComparisonOperator(EXPRBINOP expr)
{
Debug.Assert(expr != null);
Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
switch (expr.kind)
{
case ExpressionKind.EK_STRINGEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
case ExpressionKind.EK_STRINGNE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
case ExpressionKind.EK_DELEGATEEQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
case ExpressionKind.EK_DELEGATENE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
case ExpressionKind.EK_EQ: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
case ExpressionKind.EK_NE: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
case ExpressionKind.EK_LE: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED; break;
case ExpressionKind.EK_LT: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED; break;
case ExpressionKind.EK_GE: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED; break;
case ExpressionKind.EK_GT: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED; break;
default:
throw Error.InternalCompilerError();
}
EXPR p1 = expr.GetOptionalLeftChild();
EXPR p2 = expr.GetOptionalRightChild();
if (expr.GetOptionalUserDefinedCall() != null)
{
EXPRCALL udcall = expr.GetOptionalUserDefinedCall().asCALL();
EXPRLIST args = udcall.GetOptionalArguments().asLIST();
Debug.Assert(args.GetOptionalNextListNode().kind != ExpressionKind.EK_LIST);
p1 = args.GetOptionalElement();
p2 = args.GetOptionalNextListNode();
}
p1 = Visit(p1);
p2 = Visit(p2);
FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
EXPR lift = GetExprFactory().CreateBoolConstant(false); // We never lift to null in C#.
EXPR methodInfo = GetExprFactory().CreateMethodInfo(expr.GetUserDefinedCallMethod());
return GenerateCall(pdm, p1, p2, lift, methodInfo);
}
protected EXPR RewriteLambdaBody(EXPRBOUNDLAMBDA anonmeth)
{
Debug.Assert(anonmeth != null);
Debug.Assert(anonmeth.OptionalBody != null);
Debug.Assert(anonmeth.OptionalBody.GetOptionalStatements() != null);
// There ought to be no way to get an empty statement block successfully converted into an expression tree.
Debug.Assert(anonmeth.OptionalBody.GetOptionalStatements().GetOptionalNextStatement() == null);
EXPRBLOCK body = anonmeth.OptionalBody;
// The most likely case:
if (body.GetOptionalStatements().isRETURN())
{
Debug.Assert(body.GetOptionalStatements().asRETURN().GetOptionalObject() != null);
return Visit(body.GetOptionalStatements().asRETURN().GetOptionalObject());
}
// This can only if it is a void delegate and this is a void expression, such as a call to a void method
// or something like Expression<Action<Foo>> e = (Foo f) => f.MyEvent += MyDelegate;
throw Error.InternalCompilerError();
}
protected EXPR RewriteLambdaParameters(EXPRBOUNDLAMBDA anonmeth)
{
Debug.Assert(anonmeth != null);
// new ParameterExpression[2] {Parameter(typeof(type1), name1), Parameter(typeof(type2), name2)}
EXPR paramArrayInitializerArgs = null;
EXPR paramArrayInitializerArgsTail = paramArrayInitializerArgs;
for (Symbol sym = anonmeth.ArgumentScope(); sym != null; sym = sym.nextChild)
{
if (!sym.IsLocalVariableSymbol())
{
continue;
}
LocalVariableSymbol local = sym.AsLocalVariableSymbol();
if (local.isThis)
{
continue;
}
GetExprFactory().AppendItemToList(local.wrap, ref paramArrayInitializerArgs, ref paramArrayInitializerArgsTail);
}
return GenerateParamsArray(paramArrayInitializerArgs, PredefinedType.PT_PARAMETEREXPRESSION);
}
protected virtual EXPR GenerateConversion(EXPR arg, CType CType, bool bChecked)
{
return GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked());
}
protected virtual EXPR GenerateConversionWithSource(EXPR pTarget, CType pType, bool bChecked)
{
PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
EXPR pTypeOf = CreateTypeOf(pType);
return GenerateCall(pdm, pTarget, pTypeOf);
}
protected virtual EXPR GenerateValueAccessConversion(EXPR pArgument)
{
Debug.Assert(pArgument != null);
CType pStrippedTypeOfArgument = pArgument.type.StripNubs();
EXPR pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr);
}
protected virtual EXPR GenerateUserDefinedConversion(EXPR arg, CType type, MethWithInst method)
{
EXPR target = Visit(arg);
return GenerateUserDefinedConversion(arg, type, target, method);
}
protected virtual EXPR GenerateUserDefinedConversion(EXPR arg, CType CType, EXPR target, MethWithInst method)
{
// The user-defined explicit conversion from enum? to decimal or decimal? requires
// that we convert the enum? to its nullable underlying CType.
if (isEnumToDecimalConversion(arg.type, CType))
{
// Special case: If we have enum? to decimal? then we need to emit
// a conversion from enum? to its nullable underlying CType first.
// This is unfortunate; we ought to reorganize how conversions are
// represented in the EXPR tree so that this is more transparent.
// converting an enum to its underlying CType never fails, so no need to check it.
CType underlyingType = arg.type.StripNubs().underlyingEnumType();
CType nullableType = GetSymbolLoader().GetTypeManager().GetNullable(underlyingType);
EXPR typeofNubEnum = CreateTypeOf(nullableType);
target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum);
}
// If the methodinfo does not return the target CType AND this is not a lifted conversion
// from one value CType to another, then we need to wrap the whole thing in another conversion,
// e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate
// Convert(Convert(myint, typeof(S?), op_implicit), typeof(S))
CType pMethodReturnType = GetSymbolLoader().GetTypeManager().SubstType(method.Meth().RetType,
method.GetType(), method.TypeArgs);
bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.type) && IsNullableValueType(CType)));
EXPR typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType);
EXPR methodInfo = GetExprFactory().CreateMethodInfo(method);
PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED;
EXPR callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo);
if (fDontLiftReturnType)
{
return callUserDefinedConversion;
}
PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
EXPR typeofOuter = CreateTypeOf(CType);
return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter);
}
protected virtual EXPR GenerateUserDefinedConversion(EXPRUSERDEFINEDCONVERSION pExpr, EXPR pArgument)
{
EXPR pCastCall = pExpr.UserDefinedCall;
EXPR pCastArgument = pExpr.Argument;
EXPR pConversionSource = null;
if (!isEnumToDecimalConversion(pArgument.type, pExpr.type) && IsNullableValueAccess(pCastArgument, pArgument))
{
// We have an implicit conversion of nullable CType to the value CType, generate a convert node for it.
pConversionSource = GenerateValueAccessConversion(pArgument);
}
else if (pCastCall.isCALL() && pCastCall.asCALL().pConversions != null)
{
EXPR pUDConversion = pCastCall.asCALL().pConversions;
if (pUDConversion.isCALL())
{
EXPR pUDConversionArgument = pUDConversion.asCALL().GetOptionalArguments();
if (IsNullableValueAccess(pUDConversionArgument, pArgument))
{
pConversionSource = GenerateValueAccessConversion(pArgument);
}
else
{
pConversionSource = Visit(pUDConversionArgument);
}
return GenerateConversionWithSource(pConversionSource, pCastCall.type, pCastCall.asCALL().isChecked());
}
else
{
// This can happen if we have a UD conversion from C to, say, int,
// and we have an explicit cast to decimal?. The conversion should
// then be bound as two chained user-defined conversions.
Debug.Assert(pUDConversion.isUSERDEFINEDCONVERSION());
// Just recurse.
return GenerateUserDefinedConversion(pUDConversion.asUSERDEFINEDCONVERSION(), pArgument);
}
}
else
{
pConversionSource = Visit(pCastArgument);
}
return GenerateUserDefinedConversion(pCastArgument, pExpr.type, pConversionSource, pExpr.UserDefinedCallMethod);
}
protected virtual EXPR GenerateParameter(string name, CType CType)
{
GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING); // force an ensure state
EXPRCONSTANT nameString = GetExprFactory().CreateStringConstant(name);
EXPRTYPEOF pTypeOf = CreateTypeOf(CType);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString);
}
protected MethodSymbol GetPreDefMethod(PREDEFMETH pdm)
{
return GetSymbolLoader().getPredefinedMembers().GetMethod(pdm);
}
protected EXPRTYPEOF CreateTypeOf(CType CType)
{
return GetExprFactory().CreateTypeOf(CType);
}
protected EXPR CreateWraps(EXPRBOUNDLAMBDA anonmeth)
{
EXPR sequence = null;
for (Symbol sym = anonmeth.ArgumentScope().firstChild; sym != null; sym = sym.nextChild)
{
if (!sym.IsLocalVariableSymbol())
{
continue;
}
LocalVariableSymbol local = sym.AsLocalVariableSymbol();
if (local.isThis)
{
continue;
}
Debug.Assert(anonmeth.OptionalBody != null);
EXPR create = GenerateParameter(local.name.Text, local.GetType());
local.wrap = GetExprFactory().CreateWrapNoAutoFree(anonmeth.OptionalBody.OptionalScopeSymbol, create);
EXPR save = GetExprFactory().CreateSave(local.wrap);
if (sequence == null)
{
sequence = save;
}
else
{
sequence = GetExprFactory().CreateSequence(sequence, save);
}
}
return sequence;
}
protected EXPR DestroyWraps(EXPRBOUNDLAMBDA anonmeth, EXPR sequence)
{
for (Symbol sym = anonmeth.ArgumentScope(); sym != null; sym = sym.nextChild)
{
if (!sym.IsLocalVariableSymbol())
{
continue;
}
LocalVariableSymbol local = sym.AsLocalVariableSymbol();
if (local.isThis)
{
continue;
}
Debug.Assert(local.wrap != null);
Debug.Assert(anonmeth.OptionalBody != null);
EXPR freeWrap = GetExprFactory().CreateWrap(anonmeth.OptionalBody.OptionalScopeSymbol, local.wrap);
sequence = GetExprFactory().CreateReverseSequence(sequence, freeWrap);
}
return sequence;
}
protected virtual EXPR GenerateConstructor(EXPRCALL expr)
{
Debug.Assert(expr != null);
Debug.Assert(expr.mwi.Meth().IsConstructor());
// Realize a call to new DELEGATE(obj, FUNCPTR) as though it actually was
// (DELEGATE)CreateDelegate(typeof(DELEGATE), obj, GetMethInfoFromHandle(FUNCPTR))
if (IsDelegateConstructorCall(expr))
{
return GenerateDelegateConstructor(expr);
}
EXPR constructorInfo = GetExprFactory().CreateMethodInfo(expr.mwi);
EXPR args = GenerateArgsList(expr.GetOptionalArguments());
EXPR Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
if (expr.type.IsAggregateType() && expr.type.AsAggregateType().getAggregate().IsAnonymousType())
{
EXPR members = GenerateMembersArray(expr.type.AsAggregateType(), PredefinedType.PT_METHODINFO);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW_MEMBERS, constructorInfo, Params, members);
}
else
{
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params);
}
}
protected virtual EXPR GenerateDelegateConstructor(EXPRCALL expr)
{
// In:
//
// new DELEGATE(obj, &FUNC)
//
// Out:
//
// Cast(
// Call(
// null,
// (MethodInfo)GetMethodFromHandle(&CreateDelegate),
// new Expression[3]{
// Constant(typeof(DELEGATE)),
// transformed-object,
// Constant((MethodInfo)GetMethodFromHandle(&FUNC)}),
// typeof(DELEGATE))
//
Debug.Assert(expr != null);
Debug.Assert(expr.mwi.Meth().IsConstructor());
Debug.Assert(expr.type.isDelegateType());
Debug.Assert(expr.GetOptionalArguments() != null);
Debug.Assert(expr.GetOptionalArguments().isLIST());
EXPRLIST origArgs = expr.GetOptionalArguments().asLIST();
EXPR target = origArgs.GetOptionalElement();
Debug.Assert(origArgs.GetOptionalNextListNode().kind == ExpressionKind.EK_FUNCPTR);
EXPRFUNCPTR funcptr = origArgs.GetOptionalNextListNode().asFUNCPTR();
MethodSymbol createDelegateMethod = GetPreDefMethod(PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT);
AggregateType delegateType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_DELEGATE, true);
MethWithInst mwi = new MethWithInst(createDelegateMethod, delegateType);
EXPR instance = GenerateConstant(GetExprFactory().CreateMethodInfo(funcptr.mwi));
EXPR methinfo = GetExprFactory().CreateMethodInfo(mwi);
EXPR param1 = GenerateConstant(CreateTypeOf(expr.type));
EXPR param2 = Visit(target);
EXPR paramsList = GetExprFactory().CreateList(param1, param2);
EXPR Params = GenerateParamsArray(paramsList, PredefinedType.PT_EXPRESSION);
EXPR call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CALL, instance, methinfo, Params);
EXPR pTypeOf = CreateTypeOf(expr.type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf);
}
protected virtual EXPR GenerateArgsList(EXPR oldArgs)
{
EXPR newArgs = null;
EXPR newArgsTail = newArgs;
for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext())
{
EXPR oldArg = it.Current();
GetExprFactory().AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail);
}
return newArgs;
}
protected virtual EXPR GenerateIndexList(EXPR oldIndices)
{
CType intType = symbolLoader.GetReqPredefType(PredefinedType.PT_INT, true);
EXPR newIndices = null;
EXPR newIndicesTail = newIndices;
for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext())
{
EXPR newIndex = it.Current();
if (newIndex.type != intType)
{
EXPRCLASS exprType = expressionFactory.CreateClass(intType, null, null);
newIndex = expressionFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, exprType, newIndex);
newIndex.flags |= EXPRFLAG.EXF_CHECKOVERFLOW;
}
EXPR rewrittenIndex = Visit(newIndex);
expressionFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail);
}
return newIndices;
}
protected virtual EXPR GenerateConstant(EXPR expr)
{
EXPRFLAG flags = 0;
AggregateType pObject = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT, true);
if (expr.type.IsNullType())
{
EXPRTYPEOF pTypeOf = CreateTypeOf(pObject);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf);
}
AggregateType stringType = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_STRING, true);
if (expr.type != stringType)
{
flags = EXPRFLAG.EXF_BOX;
}
EXPRCLASS objectType = GetExprFactory().MakeClass(pObject);
EXPRCAST cast = GetExprFactory().CreateCast(flags, objectType, expr);
EXPRTYPEOF pTypeOf2 = CreateTypeOf(expr.type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2);
}
protected EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1)
{
MethodSymbol method = GetPreDefMethod(pdm);
// this should be enforced in an earlier pass and the tranform pass should not
// be handeling this error
if (method == null)
return null;
AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true);
MethWithInst mwi = new MethWithInst(method, expressionType);
EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
protected EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true);
EXPR args = GetExprFactory().CreateList(arg1, arg2);
MethWithInst mwi = new MethWithInst(method, expressionType);
EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
protected EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2, EXPR arg3)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true);
EXPR args = GetExprFactory().CreateList(arg1, arg2, arg3);
MethWithInst mwi = new MethWithInst(method, expressionType);
EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
protected EXPRCALL GenerateCall(PREDEFMETH pdm, EXPR arg1, EXPR arg2, EXPR arg3, EXPR arg4)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = GetSymbolLoader().GetOptPredefTypeErr(PredefinedType.PT_EXPRESSION, true);
EXPR args = GetExprFactory().CreateList(arg1, arg2, arg3, arg4);
MethWithInst mwi = new MethWithInst(method, expressionType);
EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
EXPRCALL call = GetExprFactory().CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
protected virtual EXPRARRINIT GenerateParamsArray(EXPR args, PredefinedType pt)
{
int parameterCount = ExpressionIterator.Count(args);
AggregateType paramsArrayElementType = GetSymbolLoader().GetOptPredefTypeErr(pt, true);
ArrayType paramsArrayType = GetSymbolLoader().GetTypeManager().GetArray(paramsArrayElementType, 1);
EXPRCONSTANT paramsArrayArg = GetExprFactory().CreateIntegerConstant(parameterCount);
EXPRARRINIT arrayInit = GetExprFactory().CreateArrayInit(EXPRFLAG.EXF_CANTBENULL, paramsArrayType, args, paramsArrayArg, null);
arrayInit.dimSize = parameterCount;
arrayInit.dimSizes = new int[] { arrayInit.dimSize }; // CLEANUP: Why isn't this done by the factory?
return arrayInit;
}
protected virtual EXPRARRINIT GenerateMembersArray(AggregateType anonymousType, PredefinedType pt)
{
EXPR newArgs = null;
EXPR newArgsTail = newArgs;
int methodCount = 0;
AggregateSymbol aggSym = anonymousType.getAggregate();
for (Symbol member = aggSym.firstChild; member != null; member = member.nextChild)
{
if (member.IsMethodSymbol())
{
MethodSymbol method = member.AsMethodSymbol();
if (method.MethKind() == MethodKindEnum.PropAccessor)
{
EXPRMETHODINFO methodInfo = GetExprFactory().CreateMethodInfo(method, anonymousType, method.Params);
GetExprFactory().AppendItemToList(methodInfo, ref newArgs, ref newArgsTail);
methodCount++;
}
}
}
AggregateType paramsArrayElementType = GetSymbolLoader().GetOptPredefTypeErr(pt, true);
ArrayType paramsArrayType = GetSymbolLoader().GetTypeManager().GetArray(paramsArrayElementType, 1);
EXPRCONSTANT paramsArrayArg = GetExprFactory().CreateIntegerConstant(methodCount);
EXPRARRINIT arrayInit = GetExprFactory().CreateArrayInit(EXPRFLAG.EXF_CANTBENULL, paramsArrayType, newArgs, paramsArrayArg, null);
arrayInit.dimSize = methodCount;
arrayInit.dimSizes = new int[] { arrayInit.dimSize }; // CLEANUP: Why isn't this done by the factory?
return arrayInit;
}
protected void FixLiftedUserDefinedBinaryOperators(EXPRBINOP expr, ref EXPR pp1, ref EXPR pp2)
{
// If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then
// we need to ensure that the unlifted actual arguments are promoted to their nullable CType.
Debug.Assert(expr != null);
Debug.Assert(pp1 != null);
Debug.Assert(pp1 != null);
Debug.Assert(pp2 != null);
Debug.Assert(pp2 != null);
MethodSymbol method = expr.GetUserDefinedCallMethod().Meth();
EXPR orig1 = expr.GetOptionalLeftChild();
EXPR orig2 = expr.GetOptionalRightChild();
Debug.Assert(orig1 != null && orig2 != null);
EXPR new1 = pp1;
EXPR new2 = pp2;
CType fptype1 = method.Params.Item(0);
CType fptype2 = method.Params.Item(1);
CType aatype1 = orig1.type;
CType aatype2 = orig2.type;
// Is the operator even a candidate for lifting?
if (fptype1.IsNullableType() || fptype2.IsNullableType() ||
!fptype1.IsAggregateType() || !fptype2.IsAggregateType() ||
!fptype1.AsAggregateType().getAggregate().IsValueType() ||
!fptype2.AsAggregateType().getAggregate().IsValueType())
{
return;
}
CType nubfptype1 = GetSymbolLoader().GetTypeManager().GetNullable(fptype1);
CType nubfptype2 = GetSymbolLoader().GetTypeManager().GetNullable(fptype2);
// If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1?
if (aatype1.IsNullType() || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2.IsNullType()))
{
new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1));
}
// If we have X op null, or T1? op T2, or null op T2, lift second arg to T2?
if (aatype2.IsNullType() || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1.IsNullType()))
{
new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2));
}
pp1 = new1;
pp2 = new2;
}
protected bool IsNullableValueType(CType pType)
{
if (pType.IsNullableType())
{
CType pStrippedType = pType.StripNubs();
return pStrippedType.IsAggregateType() && pStrippedType.AsAggregateType().getAggregate().IsValueType();
}
return false;
}
protected bool IsNullableValueAccess(EXPR pExpr, EXPR pObject)
{
Debug.Assert(pExpr != null);
return pExpr.isPROP() && (pExpr.asPROP().GetMemberGroup().GetOptionalObject() == pObject) && pObject.type.IsNullableType();
}
protected bool IsDelegateConstructorCall(EXPR pExpr)
{
Debug.Assert(pExpr != null);
if (!pExpr.isCALL())
{
return false;
}
EXPRCALL pCall = pExpr.asCALL();
return pCall.mwi.Meth() != null &&
pCall.mwi.Meth().IsConstructor() &&
pCall.type.isDelegateType() &&
pCall.GetOptionalArguments() != null &&
pCall.GetOptionalArguments().isLIST() &&
pCall.GetOptionalArguments().asLIST().GetOptionalNextListNode().kind == ExpressionKind.EK_FUNCPTR;
}
private static bool isEnumToDecimalConversion(CType argtype, CType desttype)
{
CType strippedArgType = argtype.IsNullableType() ? argtype.StripNubs() : argtype;
CType strippedDestType = desttype.IsNullableType() ? desttype.StripNubs() : desttype;
return strippedArgType.isEnumType() && strippedDestType.isPredefType(PredefinedType.PT_DECIMAL);
}
}
}
| |
// ****************************************************************
// Copyright 2008, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
#if !NETCF_1_0
using System;
using System.Runtime.InteropServices;
namespace NUnit.Framework.Constraints
{
/// <summary>Helper routines for working with floating point numbers</summary>
/// <remarks>
/// <para>
/// The floating point comparison code is based on this excellent article:
/// http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
/// </para>
/// <para>
/// "ULP" means Unit in the Last Place and in the context of this library refers to
/// the distance between two adjacent floating point numbers. IEEE floating point
/// numbers can only represent a finite subset of natural numbers, with greater
/// accuracy for smaller numbers and lower accuracy for very large numbers.
/// </para>
/// <para>
/// If a comparison is allowed "2 ulps" of deviation, that means the values are
/// allowed to deviate by up to 2 adjacent floating point values, which might be
/// as low as 0.0000001 for small numbers or as high as 10.0 for large numbers.
/// </para>
/// </remarks>
public class FloatingPointNumerics
{
#region struct FloatIntUnion
/// <summary>Union of a floating point variable and an integer</summary>
[StructLayout(LayoutKind.Explicit)]
private struct FloatIntUnion
{
/// <summary>The union's value as a floating point variable</summary>
[FieldOffset(0)]
public float Float;
/// <summary>The union's value as an integer</summary>
[FieldOffset(0)]
public int Int;
/// <summary>The union's value as an unsigned integer</summary>
[FieldOffset(0)]
public uint UInt;
}
#endregion // struct FloatIntUnion
#region struct DoubleLongUnion
/// <summary>Union of a double precision floating point variable and a long</summary>
[StructLayout(LayoutKind.Explicit)]
private struct DoubleLongUnion
{
/// <summary>The union's value as a double precision floating point variable</summary>
[FieldOffset(0)]
public double Double;
/// <summary>The union's value as a long</summary>
[FieldOffset(0)]
public long Long;
/// <summary>The union's value as an unsigned long</summary>
[FieldOffset(0)]
public ulong ULong;
}
#endregion // struct DoubleLongUnion
/// <summary>Compares two floating point values for equality</summary>
/// <param name="left">First floating point value to be compared</param>
/// <param name="right">Second floating point value t be compared</param>
/// <param name="maxUlps">
/// Maximum number of representable floating point values that are allowed to
/// be between the left and the right floating point values
/// </param>
/// <returns>True if both numbers are equal or close to being equal</returns>
/// <remarks>
/// <para>
/// Floating point values can only represent a finite subset of natural numbers.
/// For example, the values 2.00000000 and 2.00000024 can be stored in a float,
/// but nothing inbetween them.
/// </para>
/// <para>
/// This comparison will count how many possible floating point values are between
/// the left and the right number. If the number of possible values between both
/// numbers is less than or equal to maxUlps, then the numbers are considered as
/// being equal.
/// </para>
/// <para>
/// Implementation partially follows the code outlined here:
/// http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/
/// </para>
/// </remarks>
public static bool AreAlmostEqualUlps(float left, float right, int maxUlps)
{
FloatIntUnion leftUnion = new FloatIntUnion();
FloatIntUnion rightUnion = new FloatIntUnion();
leftUnion.Float = left;
rightUnion.Float = right;
uint leftSignMask = (leftUnion.UInt >> 31);
uint rightSignMask = (rightUnion.UInt >> 31);
uint leftTemp = ((0x80000000 - leftUnion.UInt) & leftSignMask);
leftUnion.UInt = leftTemp | (leftUnion.UInt & ~leftSignMask);
uint rightTemp = ((0x80000000 - rightUnion.UInt) & rightSignMask);
rightUnion.UInt = rightTemp | (rightUnion.UInt & ~rightSignMask);
return (Math.Abs(leftUnion.Int - rightUnion.Int) <= maxUlps);
}
/// <summary>Compares two double precision floating point values for equality</summary>
/// <param name="left">First double precision floating point value to be compared</param>
/// <param name="right">Second double precision floating point value t be compared</param>
/// <param name="maxUlps">
/// Maximum number of representable double precision floating point values that are
/// allowed to be between the left and the right double precision floating point values
/// </param>
/// <returns>True if both numbers are equal or close to being equal</returns>
/// <remarks>
/// <para>
/// Double precision floating point values can only represent a limited series of
/// natural numbers. For example, the values 2.0000000000000000 and 2.0000000000000004
/// can be stored in a double, but nothing inbetween them.
/// </para>
/// <para>
/// This comparison will count how many possible double precision floating point
/// values are between the left and the right number. If the number of possible
/// values between both numbers is less than or equal to maxUlps, then the numbers
/// are considered as being equal.
/// </para>
/// <para>
/// Implementation partially follows the code outlined here:
/// http://www.anttirt.net/2007/08/19/proper-floating-point-comparisons/
/// </para>
/// </remarks>
public static bool AreAlmostEqualUlps(double left, double right, long maxUlps)
{
DoubleLongUnion leftUnion = new DoubleLongUnion();
DoubleLongUnion rightUnion = new DoubleLongUnion();
leftUnion.Double = left;
rightUnion.Double = right;
ulong leftSignMask = (leftUnion.ULong >> 63);
ulong rightSignMask = (rightUnion.ULong >> 63);
ulong leftTemp = ((0x8000000000000000 - leftUnion.ULong) & leftSignMask);
leftUnion.ULong = leftTemp | (leftUnion.ULong & ~leftSignMask);
ulong rightTemp = ((0x8000000000000000 - rightUnion.ULong) & rightSignMask);
rightUnion.ULong = rightTemp | (rightUnion.ULong & ~rightSignMask);
return (Math.Abs(leftUnion.Long - rightUnion.Long) <= maxUlps);
}
/// <summary>
/// Reinterprets the memory contents of a floating point value as an integer value
/// </summary>
/// <param name="value">
/// Floating point value whose memory contents to reinterpret
/// </param>
/// <returns>
/// The memory contents of the floating point value interpreted as an integer
/// </returns>
public static int ReinterpretAsInt(float value)
{
FloatIntUnion union = new FloatIntUnion();
union.Float = value;
return union.Int;
}
/// <summary>
/// Reinterprets the memory contents of a double precision floating point
/// value as an integer value
/// </summary>
/// <param name="value">
/// Double precision floating point value whose memory contents to reinterpret
/// </param>
/// <returns>
/// The memory contents of the double precision floating point value
/// interpreted as an integer
/// </returns>
public static long ReinterpretAsLong(double value)
{
DoubleLongUnion union = new DoubleLongUnion();
union.Double = value;
return union.Long;
}
/// <summary>
/// Reinterprets the memory contents of an integer as a floating point value
/// </summary>
/// <param name="value">Integer value whose memory contents to reinterpret</param>
/// <returns>
/// The memory contents of the integer value interpreted as a floating point value
/// </returns>
public static float ReinterpretAsFloat(int value)
{
FloatIntUnion union = new FloatIntUnion();
union.Int = value;
return union.Float;
}
/// <summary>
/// Reinterprets the memory contents of an integer value as a double precision
/// floating point value
/// </summary>
/// <param name="value">Integer whose memory contents to reinterpret</param>
/// <returns>
/// The memory contents of the integer interpreted as a double precision
/// floating point value
/// </returns>
public static double ReinterpretAsDouble(long value)
{
DoubleLongUnion union = new DoubleLongUnion();
union.Long = value;
return union.Double;
}
private FloatingPointNumerics()
{
}
}
}
#endif
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Volume Status
/// </summary>
public class VolumeStatus
{
private string volumeIdField;
private string availabilityZoneField;
private VolumeStatusInfo volumeStatusInfoField;
private List<VolumeStatusEvent> volumeStatusEventField;
private List<VolumeStatusAction> volumeStatusActionField;
/// <summary>
/// The volume ID
/// </summary>
public string VolumeId
{
get { return this.volumeIdField; }
set { this.volumeIdField = value; }
}
/// <summary>
/// Checks if VolumeId property is set
/// </summary>
/// <returns>true if VolumeId property is set</returns>
public bool IsSetVolumeId()
{
return this.volumeIdField != null;
}
/// <summary>
/// Sets the volume ID
/// </summary>
/// <param name="volumeId">The new volume id</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public VolumeStatus WithVolumeId(string volumeId)
{
this.volumeIdField = volumeId;
return this;
}
/// <summary>
/// Availability Zone of the volume
/// </summary>
public string AvailabilityZone
{
get { return this.availabilityZoneField; }
set { this.availabilityZoneField = value; }
}
/// <summary>
/// Checks if AvailabilityZone property is set
/// </summary>
/// <returns>true if AvailabilityZone property is set</returns>
public bool IsSetAvailabilityZone()
{
return this.availabilityZoneField != null;
}
/// <summary>
/// Sets the Availability Zone of the volume
/// </summary>
/// <param name="availabilityZone">The new availability zone</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public VolumeStatus WithAvailabilityZone(string availabilityZone)
{
this.availabilityZoneField = availabilityZone;
return this;
}
/// <summary>
/// Status of the volume
/// </summary>
public VolumeStatusInfo VolumeStatusInfo
{
get { return this.volumeStatusInfoField; }
set { this.volumeStatusInfoField = value; }
}
/// <summary>
/// Checks if VolumeStatusInfo property is set
/// </summary>
/// <returns>true if VolumeStatusInfo property is set</returns>
public bool IsSetVolumeStatusInfo()
{
return this.volumeStatusInfoField != null;
}
/// <summary>
/// Sets the status of the volume
/// </summary>
/// <param name="volumeStatusInfo">The new VolumeStatusInfo</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public VolumeStatus WithVolumeStatusInfo(VolumeStatusInfo volumeStatusInfo)
{
this.volumeStatusInfoField = volumeStatusInfo;
return this;
}
/// <summary>
/// A list of events associated with the volume
/// </summary>
[XmlElementAttribute(ElementName = "VolumeStatusEvent")]
public List<VolumeStatusEvent> VolumeStatusEvent
{
get
{
if (this.volumeStatusEventField == null)
{
this.volumeStatusEventField = new List<VolumeStatusEvent>();
}
return this.volumeStatusEventField;
}
set { this.volumeStatusEventField = value; }
}
/// <summary>
/// Checks if VolumeStatusEvent property is set
/// </summary>
/// <returns>true if VolumeStatusEvent property is set</returns>
public bool IsSetVolumeStatusEvent()
{
return this.volumeStatusEventField != null;
}
/// <summary>
/// Sets a list of events associated with the volume
/// </summary>
/// <param name="list">The new VolumeStatusEvent</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public VolumeStatus WithVolumeStatusEvent(params VolumeStatusEvent[] list)
{
foreach (VolumeStatusEvent item in list)
{
this.volumeStatusEventField.Add(item);
}
return this;
}
/// <summary>
/// A list of actions associated with the volume
/// </summary>
[XmlElementAttribute(ElementName = "VolumeStatusAction")]
public List<VolumeStatusAction> VolumeStatusAction
{
get
{
if (this.volumeStatusActionField == null)
{
this.volumeStatusActionField = new List<VolumeStatusAction>();
}
return this.volumeStatusActionField;
}
set { this.volumeStatusActionField = value; }
}
/// <summary>
/// Checks if VolumeStatusAction property is set
/// </summary>
/// <returns>true if VolumeStatusAction property is set</returns>
public bool IsSetVolumeStatusAction()
{
return this.volumeStatusActionField != null;
}
/// <summary>
/// Sets a list of actions associated with the volume
/// </summary>
/// <param name="list">The new VolumeStatusAction</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public VolumeStatus WithVolumeStatusAction(params VolumeStatusAction[] list)
{
foreach (VolumeStatusAction item in list)
{
this.volumeStatusActionField.Add(item);
}
return this;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Kappa.RestServices.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/* Josip Medved <jmedved@jmedved.com> * www.medo64.com * MIT License */
//2021-11-25: Refactored to use pattern matching
//2021-10-04: Refactored for .NET 5
//2017-09-17: Initial version
namespace Medo.Net;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Simple NTP client.
/// </summary>
/// <example>
/// <code>
/// using var client = new TrivialNtpClient("time.medo64.com");
/// var time = client.RetrieveTime();
/// </code>
/// </example>
/// <remarks>RFC 5905</remarks>
public class TrivialNtpClient : IDisposable {
/// <summary>
/// Create a new instance.
/// </summary>
/// <param name="hostName">NTP server host name.</param>
/// <exception cref="ArgumentNullException">Host name cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Host name cannot be empty.</exception>
public TrivialNtpClient(string hostName)
: this(hostName, DefaultNtpPort) {
}
/// <summary>
/// Create a new instance.
/// </summary>
/// <param name="hostName">NTP server host name.</param>
/// <param name="port">NTP server port.</param>
/// <exception cref="ArgumentNullException">Host name cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Host name cannot be empty. -or- Port must be between 1 and 65535.</exception>
public TrivialNtpClient(string hostName, int port) {
if (hostName == null) { throw new ArgumentNullException(nameof(hostName), "Host name cannot be null."); }
if (string.IsNullOrWhiteSpace(hostName)) { throw new ArgumentOutOfRangeException(nameof(hostName), "Host name cannot be empty."); }
if (port is < 1 or > 65535) { throw new ArgumentOutOfRangeException(nameof(port), "Port must be between 1 and 65535."); }
HostName = hostName;
Port = port;
}
private const int DefaultNtpPort = 123;
private const int DefaultTimeout = 500;
/// <summary>
/// Gets NTP server host name.
/// </summary>
public string HostName { get; }
/// <summary>
/// Gets NTP server port.
/// </summary>
public int Port { get; }
private int _timeout = DefaultTimeout;
/// <summary>
/// Gets/sets timeout in milliseconds.
/// </summary>
public int Timeout {
get { return _timeout; }
set {
if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), "Value cannot be 0 or negative."); }
_timeout = value;
}
}
/// <summary>
/// Returns the current time as received from NTP server.
/// </summary>
/// <exception cref="InvalidOperationException">Cannot retrieve time from NTP server.</exception>
public DateTime RetrieveTime() {
var requestPacket = NtpPacket.GetClientPacket();
var requestBytes = requestPacket.GetBytes();
try {
using var udp = new UdpClient();
udp.Client.ReceiveTimeout = Timeout;
udp.Client.SendTimeout = Timeout;
udp.Send(requestBytes, requestBytes.Length, HostName, Port);
IPEndPoint? remoteEP = null;
var responseBytes = udp.Receive(ref remoteEP);
var responsePacket = NtpPacket.ParsePacket(responseBytes);
if (responsePacket.TransmitTimestamp.HasValue) {
return responsePacket.TransmitTimestamp.Value;
} else {
throw new InvalidOperationException("Cannot retrieve time from NTP server.");
}
} catch (SocketException ex) {
throw new InvalidOperationException("Cannot retrieve time from NTP server.", ex);
}
}
/// <summary>
/// Returns time retrieved from NTP server.
/// </summary>
/// <exception cref="InvalidOperationException">Cannot retrieve time from NTP server.</exception>
public async Task<DateTime> RetrieveTimeAsync() {
var requestPacket = NtpPacket.GetClientPacket();
var requestBytes = requestPacket.GetBytes();
try {
using var udp = new UdpClient();
udp.Client.ReceiveTimeout = Timeout;
udp.Client.SendTimeout = Timeout;
await udp.SendAsync(requestBytes, requestBytes.Length, HostName, Port);
var receiveTask = udp.ReceiveAsync();
using (var timeoutCancellationToken = new CancellationTokenSource()) {
var completedTask = await Task.WhenAny(receiveTask, Task.Delay(Timeout, timeoutCancellationToken.Token));
if (completedTask == receiveTask) {
timeoutCancellationToken.Cancel();
await receiveTask;
} else {
throw new InvalidOperationException("Cannot retrieve time from NTP server.", new TimeoutException());
}
}
var responsePacket = NtpPacket.ParsePacket(receiveTask.Result.Buffer);
if (responsePacket.TransmitTimestamp.HasValue) {
return responsePacket.TransmitTimestamp.Value;
} else {
throw new InvalidOperationException("Cannot retrieve time from NTP server.");
}
} catch (SocketException ex) {
throw new InvalidOperationException("Cannot retrieve time from NTP server.", ex);
}
}
/// <summary>
/// Returns if time retrieval has been successful with time given as output parameter.
/// </summary>
/// <param name="time">Time if successful.</param>
public bool TryRetrieveTime(out DateTime time) {
try {
time = RetrieveTime();
return true;
} catch (InvalidOperationException) {
time = DateTime.MinValue;
return false;
}
}
#region Static
/// <summary>
/// Returns the current time as received from NTP server.
/// </summary>
/// <param name="hostName">NTP server host name.</param>
/// <exception cref="ArgumentNullException">Host name cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Host name cannot be empty.</exception>
/// <exception cref="InvalidOperationException">Cannot retrieve time from NTP server.</exception>
public static DateTime RetrieveTime(string hostName) {
using var client = new TrivialNtpClient(hostName);
return client.RetrieveTime();
}
/// <summary>
/// Returns time retrieved from NTP server.
/// </summary>
/// <param name="hostName">NTP server host name.</param>
/// <exception cref="ArgumentNullException">Host name cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Host name cannot be empty.</exception>
/// <exception cref="InvalidOperationException">Cannot retrieve time from NTP server.</exception>
public static async Task<DateTime> RetrieveTimeAsync(string hostName) {
using var client = new TrivialNtpClient(hostName);
return await client.RetrieveTimeAsync();
}
/// <summary>
/// Returns if time retrieval has been successful with time given as output parameter.
/// </summary>
/// <param name="hostName">NTP server host name.</param>
/// <param name="time">Time if successful.</param>
/// <exception cref="ArgumentNullException">Host name cannot be null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Host name cannot be empty.</exception>
public static bool TryRetrieveTime(string hostName, out DateTime time) {
using var client = new TrivialNtpClient(hostName);
return client.TryRetrieveTime(out time);
}
#endregion Static
#region NtpPacket
private class NtpPacket {
private NtpPacket() { }
/// <summary>
/// This is a warning of an impending leap second to be inserted in the NTP timescale. The bits are set before 23:59 on the day of insertion and reset after 00:00 on the following day. This causes the number of seconds (rollover interval) in the day of insertion to be increased or decreased by one. In the case of primary servers the bits are set by operator intervention, while in the case of secondary servers the bits are set by the protocol.
/// </summary>
public NtpPacketLeapIndicator LeapIndicator { get; private set; }
/// <summary>
/// NTP version. Must be 4 (as per RFC 5905).
/// </summary>
public int VersionNumber { get; private set; }
/// <summary>
/// This is a number indicating the association mode.
/// </summary>
public NtpPacketMode Mode { get; private set; }
/// <summary>
/// This is a number indicating the stratum of the local clock.
/// </summary>
public NtpPacketStratum Stratum { get; private set; }
/// <summary>
/// This is a number indicating the minimum interval between transmitted messages, in seconds as a power of two. For instance, a value of six indicates a minimum interval of 64 seconds.
/// </summary>
public int PollAsLog2 { get; private set; }
/// <summary>
/// This is a number indicating the precision of the various clocks, in seconds to the nearest power of two. The value must be rounded to the next larger power of two; for instance, a 50-Hz (20 ms) or 60-Hz (16.67 ms) power-frequency clock would be assigned the value -5 (31.25 ms), while a 1000-Hz (1 ms) crystal-controlled clock would be assigned the value -9 (1.95 ms).
/// </summary>
public int PrecisionAsLog2 { get; private set; }
/// <summary>
/// This is a signed fixed-point number indicating the total roundtrip delay to the primary reference source at the root of the synchronization subnet, in seconds. Note that this variable can take on both positive and negative values, depending on clock precision and skew.
/// </summary>
public int RootDelay { get; private set; }
/// <summary>
/// This is a signed fixed-point number indicating the maximum error relative to the primary reference source at the root of the synchronization subnet, in seconds. Only positive values greater than zero are possible.
/// </summary>
public int RootDispersion { get; private set; }
/// <summary>
/// This is a 32-bit code identifying the particular reference clock. In the case of stratum 0 (unspecified) or stratum 1 (primary reference source), this is a four-octet, left-justified, zero-padded ASCII string. In the case of stratum 2 and greater (secondary reference) this is the four-octet Internet address of the primary reference host.
/// </summary>
public int ReferenceIdentifier { get; private set; }
/// <summary>
/// This field is the time the system clock was last set or corrected.
/// </summary>
public DateTime? ReferenceTimestamp { get; private set; }
/// <summary>
/// This is the time at which the request departed the client for the server.
/// </summary>
public DateTime? OriginTimestamp { get; private set; }
/// <summary>
/// This is the time at which the request arrived at the server or the reply arrived at the client.
/// </summary>
public DateTime? ReceiveTimestamp { get; private set; }
/// <summary>
/// This is the time at which the request departed the client or the reply departed the server.
/// </summary>
public DateTime? TransmitTimestamp { get; private set; }
/// <summary>
/// Returns packet bytes.
/// </summary>
public byte[] GetBytes() {
var bytes = new List<byte>();
var li = (int)LeapIndicator;
var vn = (int)VersionNumber;
var mode = (int)Mode;
bytes.Add((byte)((li << 6) | (vn << 3) | (mode)));
bytes.Add((byte)Stratum);
bytes.Add((byte)PollAsLog2);
bytes.Add((byte)PrecisionAsLog2);
var rootDelay = BitConverter.GetBytes(RootDelay);
bytes.AddRange(new byte[] { rootDelay[3], rootDelay[2], rootDelay[1], rootDelay[0] });
var rootDispersion = BitConverter.GetBytes(RootDispersion);
bytes.AddRange(new byte[] { rootDispersion[3], rootDispersion[2], rootDispersion[1], rootDispersion[0] });
var referenceID = BitConverter.GetBytes(ReferenceIdentifier);
bytes.AddRange(new byte[] { referenceID[3], referenceID[2], referenceID[1], referenceID[0] });
bytes.AddRange(GetTimestamp(ReferenceTimestamp));
bytes.AddRange(GetTimestamp(OriginTimestamp));
bytes.AddRange(GetTimestamp(ReceiveTimestamp));
bytes.AddRange(GetTimestamp(TransmitTimestamp));
return bytes.ToArray();
}
#region Static
public static NtpPacket GetClientPacket() {
return new NtpPacket {
VersionNumber = 4,
Mode = NtpPacketMode.Client,
OriginTimestamp = DateTime.UtcNow
};
}
public static NtpPacket ParsePacket(byte[] bytes) {
return new NtpPacket {
LeapIndicator = (NtpPacketLeapIndicator)(bytes[0] >> 6),
VersionNumber = (bytes[0] >> 3) & 0x07,
Mode = (NtpPacketMode)(bytes[0] & 0x07),
Stratum = (NtpPacketStratum)bytes[1],
PollAsLog2 = bytes[2],
PrecisionAsLog2 = bytes[3],
RootDelay = BitConverter.ToInt32(new byte[] { bytes[7], bytes[6], bytes[5], bytes[4] }, 0),
RootDispersion = BitConverter.ToInt32(new byte[] { bytes[11], bytes[10], bytes[9], bytes[8] }, 0),
ReferenceIdentifier = BitConverter.ToInt32(new byte[] { bytes[15], bytes[14], bytes[13], bytes[12] }, 0),
ReferenceTimestamp = GetTimestamp(bytes, 16),
OriginTimestamp = GetTimestamp(bytes, 24),
ReceiveTimestamp = GetTimestamp(bytes, 32),
TransmitTimestamp = GetTimestamp(bytes, 40)
};
}
#endregion Static
private static DateTime? GetTimestamp(byte[] bytes, int offset) {
long n1 = BitConverter.ToUInt32(new byte[] { bytes[offset + 3], bytes[offset + 2], bytes[offset + 1], bytes[offset + 0] }, 0);
long n2 = BitConverter.ToUInt32(new byte[] { bytes[offset + 7], bytes[offset + 6], bytes[offset + 5], bytes[offset + 4] }, 0);
if ((n1 == 0) && (n2 == 0)) { return null; }
var time = new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
time = time.AddTicks(n1 * 10000000);
time = time.AddTicks((long)(n2 / 4294967296.0 * 10000000));
return time;
}
private static byte[] GetTimestamp(DateTime? timestamp) {
if (timestamp == null) { return new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }; }
var time = timestamp.Value;
if (time.Kind == DateTimeKind.Local) { time = time.ToUniversalTime(); }
var eraTime = new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var ts = time - eraTime;
var n1 = (uint)ts.TotalSeconds;
var buffer1LE = BitConverter.GetBytes(n1);
var timeSec = eraTime.AddSeconds(n1);
var n2 = (uint)System.Math.Min(System.Math.Max((time.Ticks - timeSec.Ticks) / 10000000.0 * 4294967296, 0), 4294967296);
var buffer2LE = BitConverter.GetBytes(n2);
return new byte[] { buffer1LE[3], buffer1LE[2], buffer1LE[1], buffer1LE[0], buffer2LE[3], buffer2LE[2], buffer2LE[1], buffer2LE[0] };
}
}
/// <summary>
/// This is a warning code of an impending leap second to be inserted/deleted in the last minute of the current day.
/// </summary>
private enum NtpPacketLeapIndicator {
/// <summary>
/// No warning.
/// </summary>
None = 0,
/// <summary>
/// Last minute has 61 seconds.
/// </summary>
LastMinuteHas61Seconds = 1,
/// <summary>
/// Last minute has 59 seconds.
/// </summary>
LastMinuteHas59Seconds = 2,
/// <summary>
/// Alarm condition (clock not synchronized).
/// </summary>
ClockNotSynchronized = 3
}
/// <summary>
/// This is a number indicating the protocol mode.
/// </summary>
private enum NtpPacketMode {
/// <summary>
/// Unspecified.
/// </summary>
Unspecified = 0,
/// <summary>
/// Symmetric active.
/// </summary>
SymmetricActive = 1,
/// <summary>
/// Symmetric passive.
/// </summary>
SymmetricPassive = 2,
/// <summary>
/// Client.
/// </summary>
Client = 3,
/// <summary>
/// Server.
/// </summary>
Server = 4,
/// <summary>
/// Broadcast.
/// </summary>
Broadcast = 5,
/// <summary>
/// Reserved for NTP control messages.
/// </summary>
ReservedForNtpControlMessages = 6,
/// <summary>
/// Reserved for private use.
/// </summary>
ReservedForPrivateUse = 7
}
/// <summary>
/// This is a number indicating the stratum.
/// </summary>
private enum NtpPacketStratum {
/// <summary>
/// Kiss-o'-death message.
/// </summary>
Unknown = 0,
/// <summary>
/// Primary reference (e.g., calibrated atomic clock, radio clock).
/// </summary>
PrimaryReference = 1,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference1 = 2,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference2 = 3,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference3 = 4,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference4 = 5,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference5 = 6,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference6 = 7,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference7 = 8,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference8 = 9,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference9 = 10,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference10 = 11,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference11 = 12,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference12 = 13,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference13 = 14,
/// <summary>
/// Secondary reference (synchronized by NTP or SNTP).
/// </summary>
SecondaryReference14 = 15,
}
#endregion NtpPacket
#region IDisposable
/// <summary>
/// Disposing used resources.
/// </summary>
/// <param name="disposing">True is disposing managed resources.</param>
protected virtual void Dispose(bool disposing) {
}
/// <summary>
/// Release used resources.
/// </summary>
/// <remarks>Not really necessary but enables use of using blocks.</remarks>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
| |
#region Header
//
// Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
#endregion // Header
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace RevitLookup.Snoop.Forms
{
/// <summary>
/// This Form makes use of the built-in abilities of Reflection and the PropertyGrid
/// class to automatically list out the data of an object. Because we don't have much
/// control, it will get output in the order that it chooses (or alphabetical) and
/// most of the items will appear as Greyed-out, read-only items. But, we don't have
/// to go write a SnoopCollector for every item in the .NET system.
/// </summary>
public class GenericPropGrid : System.Windows.Forms.Form
{
private System.Windows.Forms.PropertyGrid m_pgProps;
private System.Windows.Forms.Button m_bnOK;
private System.Windows.Forms.Button m_bnCancel;
private System.Windows.Forms.ContextMenu m_mnuContext;
private System.Windows.Forms.MenuItem m_mnuItemShowObjInfo;
private System.Windows.Forms.MenuItem m_mnuItemShowClassInfo;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public
GenericPropGrid(object obj)
{
// Required for Windows Form Designer support
InitializeComponent();
m_pgProps.SelectedObject = obj; // This all we need to do for Reflection to kick in
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void
Dispose(bool disposing)
{
if (disposing) {
if (components != null) {
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GenericPropGrid));
this.m_pgProps = new System.Windows.Forms.PropertyGrid();
this.m_mnuContext = new System.Windows.Forms.ContextMenu();
this.m_mnuItemShowObjInfo = new System.Windows.Forms.MenuItem();
this.m_mnuItemShowClassInfo = new System.Windows.Forms.MenuItem();
this.m_bnOK = new System.Windows.Forms.Button();
this.m_bnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// m_pgProps
//
this.m_pgProps.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_pgProps.ContextMenu = this.m_mnuContext;
this.m_pgProps.Cursor = System.Windows.Forms.Cursors.Hand;
this.m_pgProps.LineColor = System.Drawing.SystemColors.ScrollBar;
this.m_pgProps.Location = new System.Drawing.Point(16, 16);
this.m_pgProps.Name = "m_pgProps";
this.m_pgProps.PropertySort = System.Windows.Forms.PropertySort.Alphabetical;
this.m_pgProps.Size = new System.Drawing.Size(472, 384);
this.m_pgProps.TabIndex = 0;
//
// m_mnuContext
//
this.m_mnuContext.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.m_mnuItemShowObjInfo,
this.m_mnuItemShowClassInfo});
this.m_mnuContext.Popup += new System.EventHandler(this.OnMenuContextPopup);
//
// m_mnuItemShowObjInfo
//
this.m_mnuItemShowObjInfo.Index = 0;
this.m_mnuItemShowObjInfo.Text = "Show Object Info...";
this.m_mnuItemShowObjInfo.Click += new System.EventHandler(this.OnShowObjInfo);
//
// m_mnuItemShowClassInfo
//
this.m_mnuItemShowClassInfo.Index = 1;
this.m_mnuItemShowClassInfo.Text = "Show Class Info...";
this.m_mnuItemShowClassInfo.Click += new System.EventHandler(this.OnShowClassInfo);
//
// m_bnOK
//
this.m_bnOK.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.m_bnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.m_bnOK.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.m_bnOK.Location = new System.Drawing.Point(171, 416);
this.m_bnOK.Name = "m_bnOK";
this.m_bnOK.Size = new System.Drawing.Size(75, 23);
this.m_bnOK.TabIndex = 1;
this.m_bnOK.Text = "OK";
//
// m_bnCancel
//
this.m_bnCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.m_bnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.m_bnCancel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.m_bnCancel.Location = new System.Drawing.Point(259, 416);
this.m_bnCancel.Name = "m_bnCancel";
this.m_bnCancel.Size = new System.Drawing.Size(75, 23);
this.m_bnCancel.TabIndex = 3;
this.m_bnCancel.Text = "Cancel";
//
// GenericPropGrid
//
this.AcceptButton = this.m_bnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.m_bnCancel;
this.ClientSize = new System.Drawing.Size(504, 454);
this.Controls.Add(this.m_bnCancel);
this.Controls.Add(this.m_bnOK);
this.Controls.Add(this.m_pgProps);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(280, 250);
this.Name = "GenericPropGrid";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "PropGrid";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// User chose "Show Object Info..." from the context menu. Allow them to browse
/// using Reflection for the sub-object selected.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void
OnShowObjInfo(object sender, System.EventArgs e)
{
object selObj = m_pgProps.SelectedGridItem.Value;
if (selObj == null)
MessageBox.Show("Value is null.");
else {
GenericPropGrid pgForm = new GenericPropGrid(selObj);
pgForm.Text = string.Format("{0} (Object Info: {1})", m_pgProps.SelectedGridItem.Label, selObj.GetType());
pgForm.ShowDialog();
}
}
/// <summary>
/// User chose "Show Class Info..." from the context menu. Allow them to browse
/// using Reflection for the class of the sub-object selected.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void
OnShowClassInfo(object sender, System.EventArgs e)
{
object selObj = m_pgProps.SelectedGridItem.Value;
if (selObj == null)
MessageBox.Show("Value is null.");
else {
GenericPropGrid pgForm = new GenericPropGrid(selObj.GetType());
pgForm.Text = string.Format("{0} (System.Type = {1})", m_pgProps.SelectedGridItem.Label, selObj.GetType().FullName);
pgForm.ShowDialog();
}
}
/// <summary>
/// disable any menu options if there is no current item selected in the PropGrid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void
OnMenuContextPopup(object sender, System.EventArgs e)
{
bool enabled = (m_pgProps.SelectedGridItem == null) ? false : true;
m_mnuItemShowObjInfo.Enabled = enabled;
m_mnuItemShowClassInfo.Enabled = enabled;
}
}
}
| |
/**
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Threading;
using Thrift.Protocol;
using Thrift.Transport;
namespace Thrift.Server
{
/// <summary>
/// Server that uses C# built-in ThreadPool to spawn threads when handling requests
/// </summary>
public class TThreadPoolServer : TServer
{
private const int DEFAULT_MIN_THREADS = 10;
private const int DEFAULT_MAX_THREADS = 100;
private volatile bool stop = false;
public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport)
: this(processor, serverTransport,
new TTransportFactory(), new TTransportFactory(),
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate)
: this(processor, serverTransport,
new TTransportFactory(), new TTransportFactory(),
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS, logDelegate)
{
}
public TThreadPoolServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(processor, serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadPoolServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
int minThreadPoolThreads, int maxThreadPoolThreads, LogDelegate logDel)
: base(processor, serverTransport, inputTransportFactory, outputTransportFactory,
inputProtocolFactory, outputProtocolFactory, logDel)
{
lock (typeof(TThreadPoolServer))
{
if (!ThreadPool.SetMaxThreads(maxThreadPoolThreads, maxThreadPoolThreads))
{
throw new Exception("Error: could not SetMaxThreads in ThreadPool");
}
if (!ThreadPool.SetMinThreads(minThreadPoolThreads, minThreadPoolThreads))
{
throw new Exception("Error: could not SetMinThreads in ThreadPool");
}
}
}
/// <summary>
/// Use new ThreadPool thread for each new client connection
/// </summary>
public override void Serve()
{
try
{
serverTransport.Listen();
}
catch (TTransportException ttx)
{
logDelegate("Error, could not listen on ServerTransport: " + ttx);
return;
}
//Fire the preServe server event when server is up but before any client connections
if (serverEventHandler != null)
serverEventHandler.preServe();
while (!stop)
{
int failureCount = 0;
try
{
TTransport client = serverTransport.Accept();
ThreadPool.QueueUserWorkItem(this.Execute, client);
}
catch (TTransportException ttx)
{
if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted)
{
++failureCount;
logDelegate(ttx.ToString());
}
}
}
if (stop)
{
try
{
serverTransport.Close();
}
catch (TTransportException ttx)
{
logDelegate("TServerTransport failed on close: " + ttx.Message);
}
stop = false;
}
}
/// <summary>
/// Loops on processing a client forever
/// threadContext will be a TTransport instance
/// </summary>
/// <param name="threadContext"></param>
private void Execute(Object threadContext)
{
TTransport client = (TTransport)threadContext;
TTransport inputTransport = null;
TTransport outputTransport = null;
TProtocol inputProtocol = null;
TProtocol outputProtocol = null;
Object connectionContext = null;
try
{
inputTransport = inputTransportFactory.GetTransport(client);
outputTransport = outputTransportFactory.GetTransport(client);
inputProtocol = inputProtocolFactory.GetProtocol(inputTransport);
outputProtocol = outputProtocolFactory.GetProtocol(outputTransport);
//Recover event handler (if any) and fire createContext server event when a client connects
if (serverEventHandler != null)
connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol);
//Process client requests until client disconnects
while (!stop)
{
if (!inputTransport.Peek())
break;
//Fire processContext server event
//N.B. This is the pattern implemented in C++ and the event fires provisionally.
//That is to say it may be many minutes between the event firing and the client request
//actually arriving or the client may hang up without ever makeing a request.
if (serverEventHandler != null)
serverEventHandler.processContext(connectionContext, inputTransport);
//Process client request (blocks until transport is readable)
if (!processor.Process(inputProtocol, outputProtocol))
break;
}
}
catch (TTransportException)
{
//Usually a client disconnect, expected
}
catch (Exception x)
{
//Unexpected
logDelegate("Error: " + x);
}
//Fire deleteContext server event after client disconnects
if (serverEventHandler != null)
serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol);
//Close transports
if (inputTransport != null)
inputTransport.Close();
if (outputTransport != null)
outputTransport.Close();
}
public override void Stop()
{
stop = true;
serverTransport.Close();
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.AspNet.SignalR.Configuration;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
namespace Microsoft.AspNet.SignalR.Transports
{
/// <summary>
/// Default implementation of <see cref="ITransportHeartbeat"/>.
/// </summary>
public class TransportHeartbeat : ITransportHeartbeat, IDisposable
{
private readonly ConcurrentDictionary<string, ConnectionMetadata> _connections = new ConcurrentDictionary<string, ConnectionMetadata>();
private readonly Timer _timer;
private readonly TransportOptions _transportOptions;
private readonly ILogger _logger;
private readonly IPerformanceCounterManager _counters;
private readonly object _counterLock = new object();
private int _running;
private ulong _heartbeatCount;
/// <summary>
/// Initializes and instance of the <see cref="TransportHeartbeat"/> class.
/// </summary>
/// <param name="serviceProvider">The <see cref="IDependencyResolver"/>.</param>
public TransportHeartbeat(IOptions<SignalROptions> optionsAccessor,
IPerformanceCounterManager counters,
ILoggerFactory loggerFactory)
{
_transportOptions = optionsAccessor.Value.Transports;
_counters = counters;
_logger = loggerFactory.CreateLogger<TransportHeartbeat>();
// REVIEW: When to dispose the timer?
_timer = new Timer(Beat,
null,
_transportOptions.HeartbeatInterval(),
_transportOptions.HeartbeatInterval());
}
private ILogger Logger
{
get
{
return _logger;
}
}
/// <summary>
/// Adds a new connection to the list of tracked connections.
/// </summary>
/// <param name="connection">The connection to be added.</param>
public ITrackingConnection AddOrUpdateConnection(ITrackingConnection connection)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
var newMetadata = new ConnectionMetadata(connection);
bool isNewConnection = true;
ITrackingConnection oldConnection = null;
_connections.AddOrUpdate(connection.ConnectionId, newMetadata, (key, old) =>
{
Logger.LogVerbose(String.Format("Connection {0} exists. Closing previous connection.", old.Connection.ConnectionId));
// Kick out the older connection. This should only happen when
// a previous connection attempt fails on the client side (e.g. transport fallback).
old.Connection.ApplyState(TransportConnectionStates.Replaced);
// Don't bother disposing the registration here since the token source
// gets disposed after the request has ended
old.Connection.End();
// If we have old metadata this isn't a new connection
isNewConnection = false;
oldConnection = old.Connection;
return newMetadata;
});
if (isNewConnection)
{
Logger.LogInformation(String.Format("Connection {0} is New.", connection.ConnectionId));
connection.IncrementConnectionsCount();
}
lock (_counterLock)
{
_counters.ConnectionsCurrent.RawValue = _connections.Count;
}
// Set the initial connection time
newMetadata.Initial = DateTime.UtcNow;
newMetadata.Connection.ApplyState(TransportConnectionStates.Added);
return oldConnection;
}
/// <summary>
/// Removes a connection from the list of tracked connections.
/// </summary>
/// <param name="connection">The connection to remove.</param>
public void RemoveConnection(ITrackingConnection connection)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
// Remove the connection and associated metadata
ConnectionMetadata metadata;
if (_connections.TryRemove(connection.ConnectionId, out metadata))
{
connection.DecrementConnectionsCount();
lock (_counterLock)
{
_counters.ConnectionsCurrent.RawValue = _connections.Count;
}
connection.ApplyState(TransportConnectionStates.Removed);
Logger.LogInformation(String.Format("Removing connection {0}", connection.ConnectionId));
}
}
/// <summary>
/// Marks an existing connection as active.
/// </summary>
/// <param name="connection">The connection to mark.</param>
public void MarkConnection(ITrackingConnection connection)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
// Do nothing if the connection isn't alive
if (!connection.IsAlive)
{
return;
}
ConnectionMetadata metadata;
if (_connections.TryGetValue(connection.ConnectionId, out metadata))
{
metadata.LastMarked = DateTime.UtcNow;
}
}
public IList<ITrackingConnection> GetConnections()
{
return _connections.Values.Select(metadata => metadata.Connection).ToList();
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We're tracing exceptions and don't want to crash the process.")]
private void Beat(object state)
{
if (Interlocked.Exchange(ref _running, 1) == 1)
{
Logger.LogVerbose("Timer handler took longer than current interval");
return;
}
lock (_counterLock)
{
_counters.ConnectionsCurrent.RawValue = _connections.Count;
}
try
{
_heartbeatCount++;
foreach (var metadata in _connections.Values)
{
if (metadata.Connection.IsAlive)
{
CheckTimeoutAndKeepAlive(metadata);
}
else
{
Logger.LogVerbose(metadata.Connection.ConnectionId + " is dead");
// Check if we need to disconnect this connection
CheckDisconnect(metadata);
}
}
}
catch (Exception ex)
{
Logger.LogError("SignalR error during transport heart beat on background thread: {0}", ex);
}
finally
{
Interlocked.Exchange(ref _running, 0);
}
}
private void CheckTimeoutAndKeepAlive(ConnectionMetadata metadata)
{
if (RaiseTimeout(metadata))
{
// If we're past the expiration time then just timeout the connection
metadata.Connection.Timeout();
}
else
{
// The connection is still alive so we need to keep it alive with a server side "ping".
// This is for scenarios where networking hardware (proxies, loadbalancers) get in the way
// of us handling timeout's or disconnects gracefully
if (RaiseKeepAlive(metadata))
{
Logger.LogVerbose("KeepAlive(" + metadata.Connection.ConnectionId + ")");
// Ensure delegate continues to use the C# Compiler static delegate caching optimization.
metadata.Connection.KeepAlive().Catch((ex, state) => OnKeepAliveError(ex, state), state: Logger, logger: Logger);
}
MarkConnection(metadata.Connection);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We're tracing exceptions and don't want to crash the process.")]
private void CheckDisconnect(ConnectionMetadata metadata)
{
try
{
if (RaiseDisconnect(metadata))
{
// Remove the connection from the list
RemoveConnection(metadata.Connection);
// Fire disconnect on the connection
metadata.Connection.Disconnect();
}
}
catch (Exception ex)
{
// Swallow exceptions that might happen during disconnect
Logger.LogError(String.Format("Raising Disconnect failed: {0}", ex));
}
}
private bool RaiseDisconnect(ConnectionMetadata metadata)
{
// The transport is currently dead but it could just be reconnecting
// so we to check it's last active time to see if it's over the disconnect
// threshold
TimeSpan elapsed = DateTime.UtcNow - metadata.LastMarked;
// The threshold for disconnect is the transport threshold + (potential network issues)
var threshold = metadata.Connection.DisconnectThreshold + _transportOptions.DisconnectTimeout;
return elapsed >= threshold;
}
private bool RaiseKeepAlive(ConnectionMetadata metadata)
{
var keepAlive = _transportOptions.KeepAlive;
// Don't raise keep alive if it's set to 0 or the transport doesn't support
// keep alive
if (keepAlive == null || !metadata.Connection.SupportsKeepAlive)
{
return false;
}
// Raise keep alive if the keep alive value has passed
return _heartbeatCount % (ulong)TransportOptionsExtensions.HeartBeatsPerKeepAlive == 0;
}
private bool RaiseTimeout(ConnectionMetadata metadata)
{
// The connection already timed out so do nothing
if (metadata.Connection.IsTimedOut)
{
return false;
}
// If keep alives are enabled and the transport doesn't require timeouts,
// i.e. anything but long-polling, don't ever timeout.
var keepAlive = _transportOptions.KeepAlive;
if (keepAlive != null && !metadata.Connection.RequiresTimeout)
{
return false;
}
TimeSpan elapsed = DateTime.UtcNow - metadata.Initial;
// Only raise timeout if we're past the configured connection timeout.
return elapsed >= _transportOptions.LongPolling.PollTimeout;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_timer != null)
{
_timer.Dispose();
}
Logger.LogInformation("Dispose(). Closing all connections");
// Kill all connections
foreach (var pair in _connections)
{
ConnectionMetadata metadata;
if (_connections.TryGetValue(pair.Key, out metadata))
{
metadata.Connection.End();
}
}
}
}
public void Dispose()
{
Dispose(true);
}
private static void OnKeepAliveError(AggregateException ex, object state)
{
((ILogger)state).LogError("Failed to send keep alive: " + ex.GetBaseException());
}
private class ConnectionMetadata
{
public ConnectionMetadata(ITrackingConnection connection)
{
Connection = connection;
Initial = DateTime.UtcNow;
LastMarked = DateTime.UtcNow;
}
// The connection instance
public ITrackingConnection Connection { get; set; }
// The last time the connection had any activity
public DateTime LastMarked { get; set; }
// The initial connection time of the connection
public DateTime Initial { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Odbc;
using System.IO;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Data.Common;
namespace ReportMasterTwo
{
public sealed class ReportMaster : IDisposable
{
private string ReportFileName;
private string OutputFileName;
private string ConnString;
public List<TextFormat> FormatData;
private List<string> FieldNames;
private string SqlCommand;
private Dictionary<string, List<object>> NameValueMap;
private List<List<object>> FormatLinkedValues;
private int RecordCount;
private int DetailIndex;
private ReportMaster DetailReport;
private string DetailSubstitutionField;
private List<object> DetailObjects;
private int DetailRow;
private int DetailColumn;
public StreamReader Reader;
public OutputStyle OperatingMode;
public OutputTypeMode OutputMode;
public DatabaseMode DBMode;
public string email_address;
public const string tempfile_base = @"";
public ParsingMode ParseMode;
public bool HeaderRecord;
public ParamInput paramInput;
public StreamWriter Writer;
public List<String> out_lines;
private string emailHost;
public ReportMaster()
{}
public ReportMaster(string reportName, string outputName, string conn)
{
ReportFileName = reportName;
if (outputName.StartsWith("mailto:"))
{
OutputFileName = tempfile_base + @"attach.txt";
OutputMode = OutputTypeMode.send_to_email;
email_address = outputName.Substring(7).Trim();
}
else
{
OutputFileName = outputName;
OutputMode = OutputTypeMode.save_to_file;
}
ConnString = conn;
FormatData = null;
FieldNames = null;
NameValueMap = null;
SqlCommand = null;
FormatLinkedValues = null;
RecordCount = 0;
DetailIndex = -1;
OperatingMode = OutputStyle.fixed_width;
ParseMode = ParsingMode.normal;
DBMode = DatabaseMode.odbc;
HeaderRecord = false;
paramInput = new ParamInput();
out_lines = new List<string>();
emailHost = null;
}
public ReportMaster(string reportName, string outputName, string conn, string emailHost)
{
ReportFileName = reportName;
if (outputName.StartsWith("mailto:"))
{
OutputFileName = tempfile_base + @"attach.txt";
OutputMode = OutputTypeMode.send_to_email;
email_address = outputName.Substring(7).Trim();
}
else
{
OutputFileName = outputName;
OutputMode = OutputTypeMode.save_to_file;
}
ConnString = conn;
FormatData = null;
FieldNames = null;
NameValueMap = null;
SqlCommand = null;
FormatLinkedValues = null;
RecordCount = 0;
DetailIndex = -1;
OperatingMode = OutputStyle.fixed_width;
ParseMode = ParsingMode.normal;
DBMode = DatabaseMode.odbc;
HeaderRecord = false;
paramInput = new ParamInput();
out_lines = new List<string>();
this.emailHost = emailHost;
}
public ReportMaster(string reportName, string outputName, string conn, StreamReader s, StreamWriter w)
{
Reader = s;
ReportFileName = reportName;
OutputFileName = outputName;
ConnString = conn;
FormatData = null;
FieldNames = null;
NameValueMap = null;
SqlCommand = null;
FormatLinkedValues = null;
RecordCount = 0;
DetailIndex = -1;
OperatingMode = OutputStyle.fixed_width;
ParseMode = ParsingMode.normal;
DBMode = DatabaseMode.odbc;
HeaderRecord = false;
out_lines = new List<string>();
paramInput = new ParamInput();
Writer = w;
}
public void Run()
{
ReadReportFile();
RunDBQuery();
ProcessExpressions();
FormatResults();
Reader.Close();
Writer.Close();
}
public void FlushAll()
{
Reader.Close();
}
public void Dispose()
{
if(Reader != null)
{
Reader.Dispose();
}
if(Writer != null)
{
Writer.Dispose();
}
if(DetailReport != null)
{
DetailReport.Dispose();
}
}
private void ReadReportFile()
{
if (Reader == null)
{
Reader = new StreamReader(ReportFileName);
}
ReadFormatData(Reader);
ReadSqlData(Reader);
}
private void ProcessDatabaseResults(DbCommand comm)
{
paramInput.process(comm, DBMode);
comm.CommandTimeout = 360;
DbDataReader dr = comm.ExecuteReader();
NameValueMap = new Dictionary<string, List<object>>();
for (int i = 0; i < FieldNames.Count; i++)
{
NameValueMap.Add(FieldNames[i], new List<object>());
}
while (dr.Read())
{
for (int i = 0; i < FieldNames.Count; i++)
{
NameValueMap[FieldNames[i]].Add(dr.GetValue(i));
}
RecordCount++;
}
if (DetailReport != null)
{
if (NameValueMap.ContainsKey(DetailSubstitutionField))
{
DetailObjects = NameValueMap[DetailSubstitutionField];
}
}
dr.Close();
}
private void RunDBQuery()
{
DbConnection conn = null;
DbCommand comm = null;
if (ConnString == "")
throw new Exception("DB Connection Error!");
if (DBMode == DatabaseMode.access)
{
conn = new OleDbConnection(ConnString);
conn.Open();
comm = new OleDbCommand(SqlCommand, (OleDbConnection)conn);
}
else if (DBMode == DatabaseMode.odbc)
{
conn = new OdbcConnection(ConnString);
conn.Open();
comm = new OdbcCommand(SqlCommand, (OdbcConnection)conn);
}
else if (DBMode == DatabaseMode.sql_server)
{
conn = new SqlConnection(ConnString);
conn.Open();
comm = new SqlCommand(SqlCommand, (SqlConnection)conn);
}
else
{
throw new InvalidOperationException("Invalid DBMode State");
}
ProcessDatabaseResults(comm);
conn.Close();
}
private void ProcessExpressions()
{
List<ExpressionNode> nodes = new List<ExpressionNode>();
for(int i = 0; i < FormatData.Count; i++)
{
nodes.Add(new ExpressionNode(FormatData[i].FieldExpression, paramInput));
}
FormatLinkedValues = new List<List<object>>(FormatData.Count);
for (int i = 0; i < FormatData.Count; i++)
{
if (i == DetailIndex)
{
FormatLinkedValues.Add(ProcessDetail2());
}
FormatLinkedValues.Add(nodes[i].Eval(NameValueMap, RecordCount));
}
}
private List<object> ProcessDetail2()
{
List<object> linkedValues = new List<object>();
string results = "";
string oldSqlCommand = DetailReport.SqlCommand;
for (int i = 0; i < DetailObjects.Count; i++)
{
DetailReport.SqlCommand = DetailReport.SqlCommand.Replace("$D", DetailObjects[i].ToString());
DetailReport.RunDBQuery();
DetailReport.ProcessExpressions();
results = DetailReport.FormatResults();
linkedValues.Add(results);
DetailReport.SqlCommand = oldSqlCommand;
DetailReport.RecordCount = 0;
}
return linkedValues;
}
private string FormatResults()
{
Writer = File.CreateText(OutputFileName);
for (int i = 0; i < FormatData.Count; i++)
{
FormatData[i].AddResults(FormatLinkedValues[i]);
}
FormatData.Sort(TextFormat.Comparer);
int maxDepth = FormatData[FormatData.Count - 1].Row;
PrettyPrinter pp = new PrettyPrinter(FormatData, maxDepth, Writer, out_lines);
string temp = "";
pp.Write(OutputFileName, RecordCount, out temp, OperatingMode, HeaderRecord);
Writer.Close();
if (OutputMode == OutputTypeMode.send_to_email)
{
string tempFilename = ((OperatingMode == OutputStyle.fixed_width) ? tempfile_base + "attach.txt" : tempfile_base + "attach.csv");
MailMessage mm = new MailMessage(email_address, email_address, "Report Results", "See attached report results.");
mm.Attachments.Add(new Attachment(tempFilename));
SmtpClient client = new SmtpClient(emailHost);
client.Send(mm);
}
return temp;
}
private void ProcessDetail(string line, StreamReader sr, int lineNum, List<TextFormat> FormatData)
{
DetailIndex = lineNum;
if (sr.ReadLine() != "#Format Start#")
{
throw new ArgumentException("Invalid Formatting File");
}
DetailReport = new ReportMaster(ReportFileName, OutputFileName, ConnString, sr, Writer);
// carry the params into the detail
DetailReport.paramInput = paramInput;
DetailReport.ReadReportFile();
line = line.Substring(17);
TextFormat t = new TextFormat(line);
DetailSubstitutionField = t.FieldExpression.ToUpper();
DetailRow = t.Row;
DetailColumn = t.Column;
FormatData.Add(t);
}
private void ReadFormatData(StreamReader sr)
{
int lineCounter = 0;
FormatData = new List<TextFormat>();
string line;
while ((line = sr.ReadLine()) != "#Sql Start#")
{
ProcessLine(line, lineCounter, FormatData, sr);
}
}
public void ProcessLine(string line, int lineNum, List<TextFormat> data, StreamReader sr)
{
if (line.StartsWith("#Detail Start"))
{
ProcessDetail(line, sr, lineNum, FormatData);
lineNum++;
}
else if (line.StartsWith("#Header Record#"))
{
HeaderRecord = true;
}
else if (line.StartsWith("#Format Start#"))
{
if (ParseMode == ParsingMode.config)
{
ParseMode = ParsingMode.normal;
}
OperatingMode = OutputStyle.fixed_width;
if (OutputMode == OutputTypeMode.send_to_email)
OutputFileName = tempfile_base + "attach.txt";
return;
}
else if (line.StartsWith("#CSV Start#"))
{
if (ParseMode == ParsingMode.config)
{
ParseMode = ParsingMode.normal;
}
OperatingMode = OutputStyle.csv;
if (OutputMode == OutputTypeMode.send_to_email)
OutputFileName = tempfile_base + "attach.csv";
return;
}
else if (line.StartsWith("#Config Start#"))
{
ParseMode = ParsingMode.config;
}
else if (ParseMode == ParsingMode.config)
{
ProcessConfigLine(line);
}
else
{
FormatData.Add(new TextFormat(line));
lineNum++;
}
}
public void ProcessConfigLine(string line)
{
int valueIndex = line.IndexOf(':') + 1;
string value = line.Substring(valueIndex).Trim();
if (line.IndexOf("Connection-String") != -1)
{
ConnString = value;
}
else if (line.IndexOf("Connection-Type") != -1)
{
if (value.Equals("SqlServer"))
{
DBMode = DatabaseMode.sql_server;
}
else if (value.Equals("Access"))
{
DBMode = DatabaseMode.access;
}
else if (value.Equals("Providex"))
{
DBMode = DatabaseMode.odbc;
}
}
}
public void ProcessLine(string line, int lineNum, List<TextFormat> data)
{
FormatData.Add(new TextFormat(line));
lineNum++;
}
private void ReadSqlData(StreamReader sr)
{
string line;
string sqlTemp = "";
while ((line = sr.ReadLine()) != "#Report End#")
{
line = paramInput.search(line);
sqlTemp += line;
}
SqlCommand = sqlTemp;
sqlTemp = sqlTemp.ToUpper();
int selectIndex = sqlTemp.IndexOf("SELECT");
sqlTemp = sqlTemp.Substring(selectIndex + 6, sqlTemp.IndexOf("FROM") - (selectIndex + 6));
sqlTemp = sqlTemp.Replace(" ", "");
List<string> names = SplitOnParenClear(sqlTemp);
for (int i = 0; i < names.Count; i++)
{
names[i] = TrimWrappers(names[i]);
}
FieldNames = new List<string>(names);
}
private List<string> SplitOnParenClear(string val)
{
List<string> splits = new List<string>();
int splitIndex = 0;
string left;
string right = val;
while (true)
{
splitIndex = ExpressionNode.SplitOnParenClear(right, ',', ',');
if (splitIndex == -1)
{
splits.Add(right);
break;
}
else
{
left = right.Substring(0, splitIndex);
right = right.Substring(splitIndex + 1);
splits.Add(left);
}
}
return splits;
}
public string TrimWrappers(string inval)
{
inval = inval.Replace("[", "");
inval = inval.Replace("\"", "");
inval = inval.Replace("\n", "");
inval = inval.Replace("]", "");
inval = inval.Replace(" ", "");
inval = inval.Replace("#", "");
return inval;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TrackBarRenderer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.Drawing;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Forms.VisualStyles;
using Microsoft.Win32;
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer"]/*' />
/// <devdoc>
/// <para>
/// This is a rendering class for the TrackBar control.
/// </para>
/// </devdoc>
public sealed class TrackBarRenderer {
//Make this per-thread, so that different threads can safely use these methods.
[ThreadStatic]
private static VisualStyleRenderer visualStyleRenderer = null;
const int lineWidth = 2;
//cannot instantiate
private TrackBarRenderer() {
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.IsSupported"]/*' />
/// <devdoc>
/// <para>
/// Returns true if this class is supported for the current OS and user/application settings,
/// otherwise returns false.
/// </para>
/// </devdoc>
public static bool IsSupported {
get {
return VisualStyleRenderer.IsSupported; // no downlevel support
}
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawHorizontalTrack"]/*' />
/// <devdoc>
/// <para>
/// Renders a horizontal track.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawHorizontalTrack(Graphics g, Rectangle bounds) {
InitializeRenderer(VisualStyleElement.TrackBar.Track.Normal, 1);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawVerticalTrack"]/*' />
/// <devdoc>
/// <para>
/// Renders a vertical track.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawVerticalTrack(Graphics g, Rectangle bounds) {
InitializeRenderer(VisualStyleElement.TrackBar.TrackVertical.Normal, 1);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawHorizontalThumb"]/*' />
/// <devdoc>
/// <para>
/// Renders a horizontal thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawHorizontalThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.Thumb.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawVerticalThumb"]/*' />
/// <devdoc>
/// <para>
/// Renders a vertical thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawVerticalThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbVertical.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawLeftPointingThumb"]/*' />
/// <devdoc>
/// <para>
/// Renders a constant size left pointing thumb centered in the given bounds.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawLeftPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbLeft.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawRightPointingThumb"]/*' />
/// <devdoc>
/// <para>
/// Renders a constant size right pointing thumb centered in the given bounds.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawRightPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbRight.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawTopPointingThumb"]/*' />
/// <devdoc>
/// <para>
/// Renders a constant size top pointing thumb centered in the given bounds.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawTopPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbTop.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawBottomPointingThumb"]/*' />
/// <devdoc>
/// <para>
/// Renders a constant size bottom pointing thumb centered in the given bounds.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawBottomPointingThumb(Graphics g, Rectangle bounds, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbBottom.Normal, (int)state);
visualStyleRenderer.DrawBackground(g, bounds);
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawHorizontalTick"]/*' />
/// <devdoc>
/// <para>
/// Renders a horizontal tick.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawHorizontalTicks(Graphics g, Rectangle bounds, int numTicks, EdgeStyle edgeStyle) {
if (numTicks <= 0 || bounds.Height <= 0 || bounds.Width <= 0 || g == null) {
return;
}
InitializeRenderer(VisualStyleElement.TrackBar.Ticks.Normal, 1);
//trivial case -- avoid calcs
if (numTicks == 1) {
visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, bounds.Y, lineWidth, bounds.Height), Edges.Left, edgeStyle, EdgeEffects.None);
return;
}
float inc = ((float)bounds.Width - lineWidth) / ((float)numTicks - 1);
while (numTicks > 0) {
//draw the nth tick
float x = bounds.X + ((float)(numTicks - 1)) * inc;
visualStyleRenderer.DrawEdge(g, new Rectangle((int)Math.Round(x), bounds.Y, lineWidth, bounds.Height), Edges.Left, edgeStyle, EdgeEffects.None);
numTicks--;
}
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.DrawVerticalTick"]/*' />
/// <devdoc>
/// <para>
/// Renders a vertical tick.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static void DrawVerticalTicks(Graphics g, Rectangle bounds, int numTicks, EdgeStyle edgeStyle) {
if (numTicks<=0 || bounds.Height <= 0 || bounds.Width<=0 || g == null ) {
return;
}
InitializeRenderer(VisualStyleElement.TrackBar.TicksVertical.Normal, 1);
//trivial case
if (numTicks == 1) {
visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, bounds.Y, bounds.Width, lineWidth), Edges.Top, edgeStyle, EdgeEffects.None);
return;
}
float inc = ((float)bounds.Height - lineWidth) / ((float)numTicks - 1);
while (numTicks > 0) {
//draw the nth tick
float y = bounds.Y + ((float)(numTicks - 1)) * inc;
visualStyleRenderer.DrawEdge(g, new Rectangle(bounds.X, (int)Math.Round(y), bounds.Width, lineWidth), Edges.Top, edgeStyle, EdgeEffects.None);
numTicks--;
}
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.GetLeftPointingThumbSize"]/*' />
/// <devdoc>
/// <para>
/// Returns the size of a left pointing thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static Size GetLeftPointingThumbSize(Graphics g, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbLeft.Normal, (int)state);
return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True));
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.GetRightPointingThumbSize"]/*' />
/// <devdoc>
/// <para>
/// Returns the size of a right pointing thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static Size GetRightPointingThumbSize(Graphics g, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbRight.Normal, (int)state);
return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True));
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.GetTopPointingThumbSize"]/*' />
/// <devdoc>
/// <para>
/// Returns the size of a top pointing thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static Size GetTopPointingThumbSize(Graphics g, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbTop.Normal, (int)state);
return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True));
}
/// <include file='doc\TrackBarRenderer.uex' path='docs/doc[@for="TrackBarRenderer.GetBottomPointingThumbSize"]/*' />
/// <devdoc>
/// <para>
/// Returns the size of a bottom pointing thumb.
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Graphics instead of IDeviceContext intentionally
public static Size GetBottomPointingThumbSize(Graphics g, TrackBarThumbState state) {
InitializeRenderer(VisualStyleElement.TrackBar.ThumbBottom.Normal, (int)state);
return (visualStyleRenderer.GetPartSize(g, ThemeSizeType.True));
}
private static void InitializeRenderer(VisualStyleElement element, int state) {
if (visualStyleRenderer == null) {
visualStyleRenderer = new VisualStyleRenderer(element.ClassName, element.Part, state);
}
else {
visualStyleRenderer.SetParameters(element.ClassName, element.Part, state);
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation
{
public class SmartIndenterEnterOnTokenTests : FormatterTestsBase
{
[WorkItem(537808)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodBody1()
{
var code = @"class Class1
{
void method()
{ }
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Preprocessor1()
{
var code = @"class A
{
#region T
#endregion
}
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Preprocessor2()
{
var code = @"class A
{
#line 1
#lien 2
}
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Comments()
{
var code = @"using System;
class Class
{
// Comments
// Comments
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void UsingDirective()
{
var code = @"using System;
using System.Linq;
";
AssertIndentUsingSmartTokenFormatter(
code,
'u',
indentationLine: 1,
expectedIndentation: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void DottedName()
{
var code = @"using System.
Collection;
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 1,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Namespace()
{
var code = @"using System;
namespace NS
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 3,
expectedIndentation: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void NamespaceDottedName()
{
var code = @"using System;
namespace NS.
NS2
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void NamespaceBody()
{
var code = @"using System;
namespace NS
{
class
";
AssertIndentUsingSmartTokenFormatter(
code,
'c',
indentationLine: 4,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void NamespaceCloseBrace()
{
var code = @"using System;
namespace NS
{
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 4,
expectedIndentation: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Class()
{
var code = @"using System;
namespace NS
{
class Class
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 5,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ClassBody()
{
var code = @"using System;
namespace NS
{
class Class
{
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 6,
expectedIndentation: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ClassCloseBrace()
{
var code = @"using System;
namespace NS
{
class Class
{
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 6,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Method()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 7,
expectedIndentation: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodBody()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 8,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodCloseBrace()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 8,
expectedIndentation: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Statement()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10;
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 9,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodCall()
{
var code = @"class c
{
void Method()
{
M(
a: 1,
b: 1);
}
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Switch()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 9,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void SwitchBody()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case
";
AssertIndentUsingSmartTokenFormatter(
code,
'c',
indentationLine: 10,
expectedIndentation: 16);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void SwitchCase()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 11,
expectedIndentation: 20);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void SwitchCaseBlock()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
{
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 11,
expectedIndentation: 20);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Block()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
{
int
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 12,
expectedIndentation: 24);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MultilineStatement1()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10 +
1
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 9,
expectedIndentation: 16);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MultilineStatement2()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10 +
20 +
30
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 10,
expectedIndentation: 20);
}
// Bug number 902477
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Comments2()
{
var code = @"class Class
{
void Method()
{
if (true) // Test
int
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 5,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void AfterCompletedBlock()
{
var code = @"class Program
{
static void Main(string[] args)
{
foreach(var a in x) {}
int
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 5,
expectedIndentation: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void AfterTopLevelAttribute()
{
var code = @"class Program
{
[Attr]
[
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'[',
indentationLine: 3,
expectedIndentation: 4);
}
[WorkItem(537802)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void EmbededStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
if (true)
Console.WriteLine(1);
int
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'i',
indentationLine: 6,
expectedIndentation: 8);
}
[WorkItem(537808)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodBraces1()
{
var code = @"class Class1
{
void method()
{ }
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 3,
expectedIndentation: 4);
}
[WorkItem(537808)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void MethodBraces2()
{
var code = @"class Class1
{
void method()
{
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 4,
expectedIndentation: 4);
}
[WorkItem(537795)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Property1()
{
var code = @"class C
{
string Name
{
get;
set;
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 6,
expectedIndentation: 4);
}
[WorkItem(537563)]
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Class1()
{
var code = @"class C
{
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 2,
expectedIndentation: 0);
}
[Fact]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ArrayInitializer1()
{
var code = @"class C
{
var a = new []
{ 1, 2, 3 }
}
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ArrayInitializer2()
{
var code = @"class C
{
var a = new []
{
1, 2, 3
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 5,
expectedIndentation: 4);
}
[Fact]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void ArrayInitializer3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new []
{
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 7,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void QueryExpression2()
{
var code = @"class C
{
void Method()
{
var a = from c in b
where
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'w',
indentationLine: 5,
expectedIndentation: 16);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void QueryExpression3()
{
var code = @"class C
{
void Method()
{
var a = from c in b
where select
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'w',
indentationLine: 5,
expectedIndentation: 16);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void QueryExpression4()
{
var code = @"class C
{
void Method()
{
var a = from c in b where c > 10
select
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
's',
indentationLine: 5,
expectedIndentation: 16);
}
[Fact]
[WorkItem(853748)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ArrayInitializer()
{
var code = @"class C
{
void Method()
{
var l = new int[] {
}
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'}',
indentationLine: 5,
expectedIndentation: 8);
}
[Fact]
[WorkItem(939305)]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ArrayExpression()
{
var code = @"class C
{
void M(object[] q)
{
M(
q: new object[]
{ });
}
}
";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 6,
expectedIndentation: 14);
}
[Fact]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void CollectionExpression()
{
var code = @"class C
{
void M(List<int> e)
{
M(
new List<int>
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
}
}
";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 6,
expectedIndentation: 12);
}
[Fact]
[WorkItem(1070773)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void ObjectInitializer()
{
var code = @"class C
{
void M(What dd)
{
M(
new What
{ d = 3, dd = "" });
}
}
class What
{
public int d;
public string dd;
}";
AssertIndentUsingSmartTokenFormatter(
code,
'{',
indentationLine: 6,
expectedIndentation: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void Preprocessor()
{
var code = @"
#line 1 """"Bar""""class Foo : [|IComparable|]#line default#line hidden";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 1,
expectedIndentation: 0);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_Implicit()
{
var code = @"class X {
int[] a = {
1,
};
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_ImplicitNew()
{
var code = @"class X {
int[] a = new[] {
1,
};
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_Explicit()
{
var code = @"class X {
int[] a = new int[] {
1,
};
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_Collection()
{
var code = @"using System.Collections.Generic;
class X {
private List<int> a = new List<int>() {
1,
};
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 4,
expectedIndentation: 8);
}
[Fact]
[WorkItem(1070774)]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public void InsideInitializerWithTypeBody_ObjectInitializers()
{
var code = @"class C
{
private What sdfsd = new What
{
d = 3,
}
}
class What
{
public int d;
public string dd;
}";
AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
code,
indentationLine: 5,
expectedIndentation: 8);
}
private void AssertIndentUsingSmartTokenFormatter(
string code,
char ch,
int indentationLine,
int? expectedIndentation)
{
// create tree service
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var hostdoc = workspace.Documents.First();
var buffer = hostdoc.GetTextBuffer();
var snapshot = buffer.CurrentSnapshot;
var line = snapshot.GetLineFromLineNumber(indentationLine);
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var root = document.GetSyntaxRootAsync().Result as CompilationUnitSyntax;
Assert.True(
CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(
Formatter.GetDefaultFormattingRules(workspace, root.Language),
root, line, workspace.Options, CancellationToken.None));
var actualIndentation = GetSmartTokenFormatterIndentationWorker(workspace, buffer, indentationLine, ch);
Assert.Equal(expectedIndentation.Value, actualIndentation);
}
}
private void AssertIndentNotUsingSmartTokenFormatterButUsingIndenter(
string code,
int indentationLine,
int? expectedIndentation)
{
// create tree service
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var hostdoc = workspace.Documents.First();
var buffer = hostdoc.GetTextBuffer();
var snapshot = buffer.CurrentSnapshot;
var line = snapshot.GetLineFromLineNumber(indentationLine);
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var root = document.GetSyntaxRootAsync().Result as CompilationUnitSyntax;
Assert.False(
CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(
Formatter.GetDefaultFormattingRules(workspace, root.Language),
root, line, workspace.Options, CancellationToken.None));
TestIndentation(indentationLine, expectedIndentation, workspace);
}
}
}
}
| |
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections.Generic;
using System.Linq;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Compiler.TypeSystem.Services;
using Boo.Lang.Compiler.Util;
namespace Boo.Lang.Compiler.Steps
{
public class ProcessInheritedAbstractMembers : AbstractVisitorCompilerStep, ITypeMemberReifier
{
private List<TypeDefinition> _newAbstractClasses;
private Set<IEntity> _explicitMembers;
override public void Run()
{
_newAbstractClasses = new List<TypeDefinition>();
Visit(CompileUnit.Modules);
ProcessNewAbstractClasses();
}
override public void Dispose()
{
_newAbstractClasses = null;
base.Dispose();
}
override public void OnProperty(Property node)
{
if (node.IsAbstract && null == node.Type)
node.Type = CodeBuilder.CreateTypeReference(TypeSystemServices.ObjectType);
var explicitInfo = node.ExplicitInfo;
if (null != explicitInfo)
{
Visit(explicitInfo);
if (null != explicitInfo.Entity)
ProcessPropertyImplementation(node, (IProperty) explicitInfo.Entity);
}
}
override public void OnMethod(Method node)
{
if (node.IsAbstract && null == node.ReturnType)
node.ReturnType = CodeBuilder.CreateTypeReference(TypeSystemServices.VoidType);
var explicitInfo = node.ExplicitInfo;
if (null != explicitInfo)
{
Visit(explicitInfo);
if (null != explicitInfo.Entity)
ProcessMethodImplementation(node, (IMethod) explicitInfo.Entity);
}
}
override public void OnExplicitMemberInfo(ExplicitMemberInfo node)
{
var member = (TypeMember)node.ParentNode;
if (!CheckExplicitMemberValidity((IExplicitMember)member))
return;
var interfaceType = GetEntity(node.InterfaceType);
var baseMember = FindBaseMemberOf((IMember) member.Entity, interfaceType);
if (null == baseMember)
{
Error(CompilerErrorFactory.NotAMemberOfExplicitInterface(member, interfaceType));
return;
}
TraceImplements(member, baseMember);
node.Entity = baseMember;
}
bool CheckExplicitMemberValidity(IExplicitMember member)
{
var node = (Node) member;
var explicitMember = (IMember)GetEntity(node);
var declaringType = explicitMember.DeclaringType;
if (!declaringType.IsClass)
{
Error(CompilerErrorFactory.InvalidTypeForExplicitMember(node, declaringType));
return false;
}
var targetInterface = GetType(member.ExplicitInfo.InterfaceType);
if (!targetInterface.IsInterface)
{
Error(CompilerErrorFactory.InvalidInterfaceForInterfaceMember(node, member.ExplicitInfo.InterfaceType.Name));
return false;
}
if (!declaringType.IsSubclassOf(targetInterface))
{
Error(CompilerErrorFactory.InterfaceImplForInvalidInterface(node, targetInterface.Name, ((TypeMember)node).Name));
return false;
}
return true;
}
public override void OnInterfaceDefinition(InterfaceDefinition node)
{
if (WasVisited(node))
return;
MarkVisited(node);
base.OnInterfaceDefinition(node);
}
public override void OnClassDefinition(ClassDefinition node)
{
if (WasVisited(node))
return;
MarkVisited(node);
base.OnClassDefinition(node);
ProcessBaseTypes(node, GetType(node), null);
}
/// <summary>
/// This method scans all inherited types (classes and interfaces) and checks if abstract members of base types
/// were implemented in current class definition. If abstract member is not implemented then stub is created.
/// Stubs are created in two cases:
/// 1) if any member of base interfaces is not implemented
/// 2) if any member of base types is not implemented and current class definition is not abstract.
/// </summary>
/// <param name="originalNode"></param>
/// <param name="currentType"></param>
/// <param name="rootBaseType"></param>
private void ProcessBaseTypes(ClassDefinition originalNode, IType currentType, TypeReference rootBaseType)
{
//First method call iterates through BaseTypes of ClassDefinition.
//Following recursive calls work with IType. Using IType is necessary to process external types (no ClassDefinition).
if (rootBaseType == null)
{
//Executing method first time.
//Checking all interfaces and base type
_explicitMembers = null;
foreach (var baseTypeRef in originalNode.BaseTypes)
{
var baseType = GetType(baseTypeRef);
EnsureRelatedNodeWasVisited(originalNode, baseType);
if (baseType.IsInterface)
{
if (_explicitMembers == null) _explicitMembers = ExplicitlyImplementedMembersOn(originalNode);
ResolveInterfaceMembers(originalNode, baseType, baseTypeRef);
}
//Do not resolve abstract members if class is abstract
else if (!IsAbstract(GetType(originalNode)) && IsAbstract(baseType))
ResolveAbstractMembers(originalNode, baseType, baseTypeRef);
}
}
else
{
//This is recursive call. Checking base type only.
//Don't need to check interfaces because they must be already implemented in the base type.
if (currentType.BaseType != null && IsAbstract(currentType.BaseType))
ResolveAbstractMembers(originalNode, currentType.BaseType, rootBaseType);
}
}
private Set<IEntity> ExplicitlyImplementedMembersOn(ClassDefinition definition)
{
var explicitMembers = new Set<IEntity>();
foreach (TypeMember member in definition.Members)
{
var explicitMember = member as IExplicitMember;
if (null == explicitMember)
continue;
var memberInfo = explicitMember.ExplicitInfo;
if (null == memberInfo || null == memberInfo.Entity)
continue;
explicitMembers.Add(memberInfo.Entity);
}
return explicitMembers;
}
/// <summary>
/// This function checks for inheriting implementations from EXTERNAL classes only.
/// </summary>
bool CheckInheritsImplementation(ClassDefinition node, IMember abstractMember)
{
foreach (var baseTypeRef in node.BaseTypes)
{
IType type = GetType(baseTypeRef);
if (type.IsInterface)
continue;
IMember implementation = FindBaseMemberOf(abstractMember, type);
if (null != implementation && !IsAbstract(implementation))
return true;
}
return false;
}
private IMember FindBaseMemberOf(IMember member, IType inType)
{
if (member.DeclaringType == inType) return null;
foreach (var candidate in ImplementationCandidatesFor(member, inType))
{
if (candidate == member)
continue;
if (IsValidImplementationFor(member, candidate))
return candidate;
}
return null;
}
private bool IsValidImplementationFor(IEntity member, IEntity candidate)
{
switch (member.EntityType)
{
case EntityType.Method:
if (CheckInheritedMethodImpl(candidate as IMethod, member as IMethod))
return true;
break;
case EntityType.Event:
if (CheckInheritedEventImpl(candidate as IEvent, member as IEvent))
return true;
break;
case EntityType.Property:
if (CheckInheritedPropertyImpl(candidate as IProperty, member as IProperty))
return true;
break;
}
return false;
}
private IEnumerable<IMember> ImplementationCandidatesFor(IMember abstractMember, IType inBaseType)
{
while (inBaseType != null)
{
foreach (var candidate in inBaseType.GetMembers())
{
if (candidate.EntityType != abstractMember.EntityType)
continue;
if (candidate.EntityType == EntityType.Field)
continue;
string candidateName = abstractMember.DeclaringType.IsInterface
? SimpleNameOf(candidate)
: candidate.Name;
if (candidateName == abstractMember.Name)
yield return (IMember)candidate;
}
inBaseType = inBaseType.BaseType;
}
}
private string SimpleNameOf(IEntity candidate)
{
//candidate.Name == "CopyTo"
//vs
//candidate.Name == "System.ICollection.CopyTo"
var temp = candidate.FullName.Split('.');
return temp[temp.Length - 1];
}
bool CheckInheritedMethodImpl(IMethod impl, IMethod baseMethod)
{
return TypeSystemServices.CheckOverrideSignature(impl, baseMethod);
}
bool CheckInheritedEventImpl(IEvent impl, IEvent target)
{
return impl.Type == target.Type;
}
bool CheckInheritedPropertyImpl(IProperty impl, IProperty target)
{
if (!TypeSystemServices.CheckOverrideSignature(impl.GetParameters(), target.GetParameters()))
return false;
if (HasGetter(target) && !HasGetter(impl)) return false;
if (HasSetter(target) && !HasSetter(impl)) return false;
return true;
}
private static bool HasGetter(IProperty property)
{
return property.GetGetMethod() != null;
}
private static bool HasSetter(IProperty property)
{
return property.GetSetMethod() != null;
}
private bool IsAbstract(IType type)
{
if (type.IsAbstract)
return true;
var internalType = type as AbstractInternalType;
if (null != internalType)
return _newAbstractClasses.Contains(internalType.TypeDefinition);
return false;
}
void ResolveAbstractProperty(ClassDefinition node, IProperty baseProperty, TypeReference rootBaseType)
{
foreach (var p in GetAbstractPropertyImplementationCandidates(node, baseProperty))
{
if (!ResolveAsImplementationOf(baseProperty, p))
continue;
//fully-implemented?
if (!HasGetter(baseProperty) || (HasGetter(baseProperty) && null != p.Getter))
if (!HasSetter(baseProperty) || (HasSetter(baseProperty) && null != p.Setter))
return;
}
if (CheckInheritsImplementation(node, baseProperty))
return;
AbstractMemberNotImplemented(node, rootBaseType, baseProperty);
}
private ClassDefinition ClassDefinitionFor(TypeReference parent)
{
var internalClass = GetType(parent) as InternalClass;
return internalClass != null
? (ClassDefinition) internalClass.TypeDefinition
: null;
}
private bool ResolveAsImplementationOf(IProperty baseProperty, Property property)
{
if (!TypeSystemServices.CheckOverrideSignature(GetEntity(property).GetParameters(), baseProperty.GetParameters()))
return false;
ProcessPropertyImplementation(property, baseProperty);
AssertValidPropertyImplementation(property, baseProperty);
return true;
}
private void AssertValidPropertyImplementation(Property p, IProperty baseProperty)
{
if (baseProperty.Type != p.Type.Entity)
Error(CompilerErrorFactory.ConflictWithInheritedMember(p, GetEntity(p), baseProperty));
AssertValidInterfaceImplementation(p, baseProperty);
}
private void ProcessPropertyImplementation(Property p, IProperty baseProperty)
{
if (p.Type == null) p.Type = CodeBuilder.CreateTypeReference(baseProperty.Type);
ProcessPropertyAccessor(p, p.Getter, baseProperty.GetGetMethod());
ProcessPropertyAccessor(p, p.Setter, baseProperty.GetSetMethod());
}
private static void ProcessPropertyAccessor(Property p, Method accessor, IMethod method)
{
if (accessor == null)
return;
accessor.Modifiers |= TypeMemberModifiers.Virtual;
if (p.ExplicitInfo != null)
{
accessor.ExplicitInfo = p.ExplicitInfo.CloneNode();
accessor.ExplicitInfo.Entity = method;
accessor.Visibility = TypeMemberModifiers.Private;
}
}
void ResolveAbstractEvent(ClassDefinition node, TypeReference baseTypeRef, IEvent baseEvent)
{
var ev = node.Members[baseEvent.Name] as Event;
if (ev != null)
{
ProcessEventImplementation(ev, baseEvent);
return;
}
if (CheckInheritsImplementation(node, baseEvent))
return;
TypeMember conflicting;
if (null != (conflicting = node.Members[baseEvent.Name]))
{
//we've got a non-resolved conflicting member
Error(CompilerErrorFactory.ConflictWithInheritedMember(conflicting, (IMember)GetEntity(conflicting), baseEvent));
return;
}
AddStub(node, CodeBuilder.CreateAbstractEvent(baseTypeRef.LexicalInfo, baseEvent));
AbstractMemberNotImplemented(node, baseTypeRef, baseEvent);
}
private void ProcessEventImplementation(Event ev, IEvent baseEvent)
{
MakeVirtualFinal(ev.Add);
MakeVirtualFinal(ev.Remove);
MakeVirtualFinal(ev.Raise);
AssertValidInterfaceImplementation(ev, baseEvent);
Context.TraceInfo("{0}: Event {1} implements {2}", ev.LexicalInfo, ev, baseEvent);
}
private static void MakeVirtualFinal(Method method)
{
if (method == null) return;
method.Modifiers |= TypeMemberModifiers.Final | TypeMemberModifiers.Virtual;
}
void ResolveAbstractMethod(ClassDefinition node, IMethod baseAbstractMethod, TypeReference rootBaseType)
{
if (baseAbstractMethod.IsSpecialName)
return;
foreach (Method method in GetAbstractMethodImplementationCandidates(node, baseAbstractMethod))
if (ResolveAsImplementationOf(baseAbstractMethod, method))
return;
if (CheckInheritsImplementation(node, baseAbstractMethod))
return;
if (!AbstractMemberNotImplemented(node, rootBaseType, baseAbstractMethod))
{
//BEHAVIOR < 0.7.7: no stub, mark class as abstract
AddStub(node, CodeBuilder.CreateAbstractMethod(rootBaseType.LexicalInfo, baseAbstractMethod));
}
}
private bool ResolveAsImplementationOf(IMethod baseMethod, Method method)
{
if (!TypeSystemServices.CheckOverrideSignature(GetEntity(method), baseMethod))
return false;
ProcessMethodImplementation(method, baseMethod);
if (!method.IsOverride && !method.IsVirtual)
method.Modifiers |= TypeMemberModifiers.Virtual;
AssertValidInterfaceImplementation(method, baseMethod);
TraceImplements(method, baseMethod);
return true;
}
private void ProcessMethodImplementation(Method method, IMethod baseMethod)
{
IMethod methodEntity = GetEntity(method);
CallableSignature baseSignature = TypeSystemServices.GetOverriddenSignature(baseMethod, methodEntity);
if (IsUnknown(methodEntity.ReturnType))
method.ReturnType = CodeBuilder.CreateTypeReference(baseSignature.ReturnType);
else if (baseSignature.ReturnType != methodEntity.ReturnType)
Error(CompilerErrorFactory.ConflictWithInheritedMember(method, methodEntity, baseMethod));
}
private void TraceImplements(TypeMember member, IEntity baseMember)
{
Context.TraceInfo("{0}: Member {1} implements {2}", member.LexicalInfo, member, baseMember);
}
private static bool IsUnknown(IType type)
{
return TypeSystemServices.IsUnknown(type);
}
private IEnumerable<Method> GetAbstractMethodImplementationCandidates(TypeDefinition node, IMethod baseMethod)
{
return GetAbstractMemberImplementationCandidates<Method>(node, baseMethod);
}
private IEnumerable<Property> GetAbstractPropertyImplementationCandidates(TypeDefinition node, IProperty baseProperty)
{
return GetAbstractMemberImplementationCandidates<Property>(node, baseProperty);
}
private IEnumerable<TMember> GetAbstractMemberImplementationCandidates<TMember>(TypeDefinition node, IMember baseEntity)
where TMember : TypeMember, IExplicitMember
{
var candidates = new List<TMember>();
foreach (TypeMember m in node.Members)
{
var member = m as TMember;
if (member != null && IsCandidateMemberImplementationFor(baseEntity, m))
candidates.Add(member);
}
// BOO-1031: Move explicitly implemented candidates to top of list so that
// they're used for resolution before non-explicit ones, if possible.
// HACK: using IComparer<T> instead of Comparison<T> to workaround
// mono bug #399214.
candidates.Sort(new ExplicitMembersFirstComparer<TMember>());
return candidates;
}
private bool IsCandidateMemberImplementationFor(IMember baseMember, TypeMember candidate)
{
return candidate.Name == baseMember.Name
&& IsCorrectExplicitMemberImplOrNoExplicitMemberAtAll(candidate, baseMember);
}
private sealed class ExplicitMembersFirstComparer<T> : IComparer<T>
where T : IExplicitMember
{
public int Compare(T lhs, T rhs)
{
if (lhs.ExplicitInfo != null && rhs.ExplicitInfo == null) return -1;
if (lhs.ExplicitInfo == null && rhs.ExplicitInfo != null) return 1;
return 0;
}
}
private bool IsCorrectExplicitMemberImplOrNoExplicitMemberAtAll(TypeMember member, IMember entity)
{
ExplicitMemberInfo info = ((IExplicitMember)member).ExplicitInfo;
if (info == null)
return true;
if (info.Entity != null)
return false; // already bound to another member
return entity.DeclaringType == GetType(info.InterfaceType);
}
//returns true if a stub has been created, false otherwise.
//TODO: add entity argument to the method to not need return type?
bool AbstractMemberNotImplemented(ClassDefinition node, TypeReference baseTypeRef, IMember member)
{
if (IsValueType(node))
{
Error(CompilerErrorFactory.ValueTypeCantHaveAbstractMember(baseTypeRef, GetType(node), member));
return false;
}
if (!node.IsAbstract)
{
//BEHAVIOR >= 0.7.7: (see BOO-789 for details)
//create a stub for this not implemented member
//it will raise a NotImplementedException if called at runtime
TypeMember m = CodeBuilder.CreateStub(node, member);
CompilerWarning warning = null;
if (null != m)
{
warning = CompilerWarningFactory.AbstractMemberNotImplementedStubCreated(baseTypeRef, GetType(node), member);
if (m.NodeType != NodeType.Property || null == node.Members[m.Name])
AddStub(node, m);
}
else
{
warning = CompilerWarningFactory.AbstractMemberNotImplemented(baseTypeRef, GetType(node), member);
_newAbstractClasses.AddUnique(node);
}
Warnings.Add(warning);
return (null != m);
}
return false;
}
private static bool IsValueType(ClassDefinition node)
{
return ((IType)node.Entity).IsValueType;
}
void ResolveInterfaceMembers(ClassDefinition node, IType baseType, TypeReference rootBaseType)
{
foreach (IType entity in baseType.GetInterfaces())
ResolveInterfaceMembers(node, entity, rootBaseType);
foreach (IMember entity in baseType.GetMembers())
{
if (_explicitMembers.Contains(entity))
continue;
ResolveAbstractMember(node, entity, rootBaseType);
}
}
void ResolveAbstractMembers(ClassDefinition node, IType baseType, TypeReference rootBaseType)
{
foreach (IEntity member in baseType.GetMembers())
{
switch (member.EntityType)
{
case EntityType.Method:
{
var method = (IMethod)member;
if (method.IsAbstract)
ResolveAbstractMethod(node, method, rootBaseType);
break;
}
case EntityType.Property:
{
var property = (IProperty)member;
if (IsAbstract(property))
ResolveAbstractProperty(node, property, rootBaseType);
break;
}
case EntityType.Event:
{
var ev = (IEvent)member;
if (ev.IsAbstract)
ResolveAbstractEvent(node, rootBaseType, ev);
break;
}
}
}
ProcessBaseTypes(node, baseType, rootBaseType);
}
private static bool IsAbstract(IProperty property)
{
return IsAbstractAccessor(property.GetGetMethod()) ||
IsAbstractAccessor(property.GetSetMethod());
}
private static bool IsAbstractAccessor(IMethod accessor)
{
return null != accessor && accessor.IsAbstract;
}
void ResolveAbstractMember(ClassDefinition node, IMember member, TypeReference rootBaseType)
{
switch (member.EntityType)
{
case EntityType.Method:
{
ResolveAbstractMethod(node, (IMethod)member, rootBaseType);
break;
}
case EntityType.Property:
{
ResolveAbstractProperty(node, (IProperty)member, rootBaseType);
break;
}
case EntityType.Event:
{
ResolveAbstractEvent(node, rootBaseType, (IEvent)member);
break;
}
default:
{
NotImplemented(rootBaseType, "abstract member: " + member);
break;
}
}
}
void ProcessNewAbstractClasses()
{
foreach (ClassDefinition node in _newAbstractClasses)
node.Modifiers |= TypeMemberModifiers.Abstract;
}
void AddStub(TypeDefinition node, TypeMember stub)
{
node.Members.Add(stub);
}
void AssertValidInterfaceImplementation(TypeMember node, IMember baseMember)
{
if (!baseMember.DeclaringType.IsInterface)
return;
IExplicitMember explicitNode = node as IExplicitMember;
if (null != explicitNode && null != explicitNode.ExplicitInfo)
return; //node is an explicit interface impl
if (node.Visibility != TypeMemberModifiers.Public)
Errors.Add(CompilerErrorFactory.InterfaceImplementationMustBePublicOrExplicit(node, baseMember));
}
public TypeMember Reify(TypeMember node)
{
Visit(node);
var method = node as Method;
if (method != null)
{
ReifyMethod(method);
return node;
}
var @event = node as Event;
if (@event != null)
{
ReifyEvent(@event);
return node;
}
var property = node as Property;
if (property != null)
ReifyProperty(property);
return node;
}
private void ReifyProperty(Property property)
{
foreach (var baseProperty in InheritedAbstractMembersOf(property.DeclaringType).OfType<IProperty>())
if (IsCandidateMemberImplementationFor(baseProperty, property) && ResolveAsImplementationOf(baseProperty, property))
return;
}
private void ReifyEvent(Event @event)
{
foreach (var baseEvent in InheritedAbstractMembersOf(@event.DeclaringType).OfType<IEvent>())
if (baseEvent.Name == @event.Name)
{
ProcessEventImplementation(@event, baseEvent);
break;
}
}
private void ReifyMethod(Method method)
{
foreach (var baseMethod in InheritedAbstractMembersOf(method.DeclaringType).OfType<IMethod>())
if (IsCandidateMemberImplementationFor(baseMethod, method) && ResolveAsImplementationOf(baseMethod, method))
return;
}
private IEnumerable<IMember> InheritedAbstractMembersOf(TypeDefinition typeDefinition)
{
var type = GetType(typeDefinition);
foreach (var baseType in type.GetInterfaces())
foreach (IMember member in baseType.GetMembers())
if (IsAbstract(member))
yield return member;
foreach (IMember member in type.BaseType.GetMembers())
if (IsAbstract(member))
yield return member;
}
private static bool IsAbstract(IMember member)
{
switch (member.EntityType)
{
case EntityType.Method:
return ((IMethod) member).IsAbstract;
case EntityType.Property:
return IsAbstract((IProperty) member);
case EntityType.Event:
return ((IEvent) member).IsAbstract;
default:
return false;
}
}
}
}
| |
using System;
//System.Int32.Equals(System.Object)
public class Int32Equals2
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: test two random Int32");
try
{
Int32 o1;
object o2 = o1 = TestLibrary.Generator.GetInt32(-55);
if (!o1.Equals(o2))
{
TestLibrary.TestFramework.LogError("001", "Equal error , random number: " + o1);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: test 0 = 0");
try
{
Int32 o1 = 0;
object o2 = 0;
if (!o1.Equals(o2))
{
TestLibrary.TestFramework.LogError("003", "Equal error 0 = 0 ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: test Int32.MaxValue");
try
{
Int32 o1 = Int32.MaxValue;
object o2 = Int32.MaxValue;
if (!o1.Equals(o2))
{
TestLibrary.TestFramework.LogError("005", "Equal error Int32.MaxValue ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: test Int32.MinValue");
try
{
Int32 o1 = Int32.MinValue;
object o2 = Int32.MinValue;
if (!o1.Equals(o2))
{
TestLibrary.TestFramework.LogError("007", "Equal error Int32.MinValue ");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: test two different value");
try
{
Int32 o1 = 0;
object o2 = o1 + 1;
if (o1.Equals(o2))
{
TestLibrary.TestFramework.LogError("009", "Equal two different value get a true, error");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: test other parameter ");
try
{
double f1 = 3.00;
Int32 i1 = 3;
if (i1.Equals(f1))
{
TestLibrary.TestFramework.LogError("011", "different kind parameters is not equal");
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
#endregion
#endregion
public static int Main()
{
Int32Equals2 test = new Int32Equals2();
TestLibrary.TestFramework.BeginTestCase("Int32Equals2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using System;
using System.Reflection;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// Stores information about a current texture download and a reference to the texture asset
/// </summary>
public class J2KImage
{
private const int IMAGE_PACKET_SIZE = 1000;
private const int FIRST_PACKET_SIZE = 600;
/// <summary>
/// If we've requested an asset but not received it in this ticks timeframe, then allow a duplicate
/// request from the client to trigger a fresh asset request.
/// </summary>
/// <remarks>
/// There are 10,000 ticks in a millisecond
/// </remarks>
private const int ASSET_REQUEST_TIMEOUT = 100000000;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public uint LastSequence;
public float Priority;
public uint StartPacket;
public sbyte DiscardLevel;
public UUID TextureID;
public IJ2KDecoder J2KDecoder;
public IAssetService AssetService;
public UUID AgentID;
public IInventoryAccessModule InventoryAccessModule;
private OpenJPEG.J2KLayerInfo[] m_layers;
/// <summary>
/// Has this request decoded the asset data?
/// </summary>
public bool IsDecoded { get; private set; }
/// <summary>
/// Has this request received the required asset data?
/// </summary>
public bool HasAsset { get; private set; }
/// <summary>
/// Time in milliseconds at which the asset was requested.
/// </summary>
public long AssetRequestTime { get; private set; }
public C5.IPriorityQueueHandle<J2KImage> PriorityQueueHandle;
private uint m_currentPacket;
private bool m_decodeRequested;
private bool m_assetRequested;
private bool m_sentInfo;
private uint m_stopPacket;
private byte[] m_asset;
private LLImageManager m_imageManager;
public J2KImage(LLImageManager imageManager)
{
m_imageManager = imageManager;
}
/// <summary>
/// Sends packets for this texture to a client until packetsToSend is
/// hit or the transfer completes
/// </summary>
/// <param name="client">Reference to the client that the packets are destined for</param>
/// <param name="packetsToSend">Maximum number of packets to send during this call</param>
/// <param name="packetsSent">Number of packets sent during this call</param>
/// <returns>True if the transfer completes at the current discard level, otherwise false</returns>
public bool SendPackets(IClientAPI client, int packetsToSend, out int packetsSent)
{
packetsSent = 0;
if (m_currentPacket <= m_stopPacket)
{
bool sendMore = true;
if (!m_sentInfo || (m_currentPacket == 0))
{
sendMore = !SendFirstPacket(client);
m_sentInfo = true;
++m_currentPacket;
++packetsSent;
}
if (m_currentPacket < 2)
{
m_currentPacket = 2;
}
while (sendMore && packetsSent < packetsToSend && m_currentPacket <= m_stopPacket)
{
sendMore = SendPacket(client);
++m_currentPacket;
++packetsSent;
}
}
return (m_currentPacket > m_stopPacket);
}
/// <summary>
/// This is where we decide what we need to update
/// and assign the real discardLevel and packetNumber
/// assuming of course that the connected client might be bonkers
/// </summary>
public void RunUpdate()
{
if (!HasAsset)
{
if (!m_assetRequested || DateTime.UtcNow.Ticks > AssetRequestTime + ASSET_REQUEST_TIMEOUT)
{
// m_log.DebugFormat(
// "[J2KIMAGE]: Requesting asset {0} from request in packet {1}, already requested? {2}, due to timeout? {3}",
// TextureID, LastSequence, m_assetRequested, DateTime.UtcNow.Ticks > AssetRequestTime + ASSET_REQUEST_TIMEOUT);
m_assetRequested = true;
AssetRequestTime = DateTime.UtcNow.Ticks;
AssetService.Get(TextureID.ToString(), this, AssetReceived);
}
}
else
{
if (!IsDecoded)
{
//We need to decode the requested image first
if (!m_decodeRequested)
{
//Request decode
m_decodeRequested = true;
// m_log.DebugFormat("[J2KIMAGE]: Requesting decode of asset {0}", TextureID);
// Do we have a jpeg decoder?
if (J2KDecoder != null)
{
if (m_asset == null)
{
J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
}
else
{
// Send it off to the jpeg decoder
J2KDecoder.BeginDecode(TextureID, m_asset, J2KDecodedCallback);
}
}
else
{
J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
}
}
}
else
{
// Check for missing image asset data
if (m_asset == null)
{
m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing asset data (no missing image texture?). Canceling texture transfer");
m_currentPacket = m_stopPacket;
return;
}
if (DiscardLevel >= 0 || m_stopPacket == 0)
{
// This shouldn't happen, but if it does, we really can't proceed
if (m_layers == null)
{
m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing Layers. Canceling texture transfer");
m_currentPacket = m_stopPacket;
return;
}
int maxDiscardLevel = Math.Max(0, m_layers.Length - 1);
// Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel
if (DiscardLevel < 0 && m_stopPacket == 0)
DiscardLevel = (sbyte)maxDiscardLevel;
// Clamp at the highest discard level
DiscardLevel = (sbyte)Math.Min(DiscardLevel, maxDiscardLevel);
//Calculate the m_stopPacket
if (m_layers.Length > 0)
{
m_stopPacket = (uint)GetPacketForBytePosition(m_layers[(m_layers.Length - 1) - DiscardLevel].End);
//I don't know why, but the viewer seems to expect the final packet if the file
//is just one packet bigger.
if (TexturePacketCount() == m_stopPacket + 1)
{
m_stopPacket = TexturePacketCount();
}
}
else
{
m_stopPacket = TexturePacketCount();
}
m_currentPacket = StartPacket;
}
}
}
}
private bool SendFirstPacket(IClientAPI client)
{
if (client == null)
return false;
if (m_asset == null)
{
m_log.Warn("[J2KIMAGE]: Sending ImageNotInDatabase for texture " + TextureID);
client.SendImageNotFound(TextureID);
return true;
}
else if (m_asset.Length <= FIRST_PACKET_SIZE)
{
// We have less then one packet's worth of data
client.SendImageFirstPart(1, TextureID, (uint)m_asset.Length, m_asset, 2);
m_stopPacket = 0;
return true;
}
else
{
// This is going to be a multi-packet texture download
byte[] firstImageData = new byte[FIRST_PACKET_SIZE];
try { Buffer.BlockCopy(m_asset, 0, firstImageData, 0, FIRST_PACKET_SIZE); }
catch (Exception)
{
m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}", TextureID, m_asset.Length);
return true;
}
client.SendImageFirstPart(TexturePacketCount(), TextureID, (uint)m_asset.Length, firstImageData, (byte)ImageCodec.J2C);
}
return false;
}
private bool SendPacket(IClientAPI client)
{
if (client == null)
return false;
bool complete = false;
int imagePacketSize = ((int)m_currentPacket == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE;
try
{
if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_asset.Length)
{
imagePacketSize = LastPacketSize();
complete = true;
if ((CurrentBytePosition() + imagePacketSize) > m_asset.Length)
{
imagePacketSize = m_asset.Length - CurrentBytePosition();
complete = true;
}
}
// It's concievable that the client might request packet one
// from a one packet image, which is really packet 0,
// which would leave us with a negative imagePacketSize..
if (imagePacketSize > 0)
{
byte[] imageData = new byte[imagePacketSize];
int currentPosition = CurrentBytePosition();
try { Buffer.BlockCopy(m_asset, currentPosition, imageData, 0, imagePacketSize); }
catch (Exception e)
{
m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}, currentposition={2}, imagepacketsize={3}, exception={4}",
TextureID, m_asset.Length, currentPosition, imagePacketSize, e.Message);
return false;
}
//Send the packet
client.SendImageNextPart((ushort)(m_currentPacket - 1), TextureID, imageData);
}
return !complete;
}
catch (Exception)
{
return false;
}
}
private ushort TexturePacketCount()
{
if (!IsDecoded)
return 0;
if (m_asset == null)
return 0;
if (m_asset.Length <= FIRST_PACKET_SIZE)
return 1;
return (ushort)(((m_asset.Length - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1);
}
private int GetPacketForBytePosition(int bytePosition)
{
return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1;
}
private int LastPacketSize()
{
if (m_currentPacket == 1)
return m_asset.Length;
int lastsize = (m_asset.Length - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE;
//If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary
if (lastsize == 0)
{
lastsize = IMAGE_PACKET_SIZE;
}
return lastsize;
}
private int CurrentBytePosition()
{
if (m_currentPacket == 0)
return 0;
if (m_currentPacket == 1)
return FIRST_PACKET_SIZE;
int result = FIRST_PACKET_SIZE + ((int)m_currentPacket - 2) * IMAGE_PACKET_SIZE;
if (result < 0)
result = FIRST_PACKET_SIZE;
return result;
}
private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers)
{
m_layers = layers;
IsDecoded = true;
RunUpdate();
}
private void AssetDataCallback(UUID AssetID, AssetBase asset)
{
HasAsset = true;
if (asset == null || asset.Data == null)
{
if (m_imageManager.MissingImage != null)
{
m_asset = m_imageManager.MissingImage.Data;
}
else
{
m_asset = null;
IsDecoded = true;
}
}
else
{
m_asset = asset.Data;
}
RunUpdate();
}
private void AssetReceived(string id, Object sender, AssetBase asset)
{
// m_log.DebugFormat(
// "[J2KIMAGE]: Received asset {0} ({1} bytes)", id, asset != null ? asset.Data.Length.ToString() : "n/a");
UUID assetID = UUID.Zero;
if (asset != null)
{
assetID = asset.FullID;
}
else if ((InventoryAccessModule != null) && (sender != InventoryAccessModule))
{
// Unfortunately we need this here, there's no other way.
// This is due to the fact that textures opened directly from the agent's inventory
// don't have any distinguishing feature. As such, in order to serve those when the
// foreign user is visiting, we need to try again after the first fail to the local
// asset service.
string assetServerURL = string.Empty;
if (InventoryAccessModule.IsForeignUser(AgentID, out assetServerURL) && !string.IsNullOrEmpty(assetServerURL))
{
if (!assetServerURL.EndsWith("/") && !assetServerURL.EndsWith("="))
assetServerURL = assetServerURL + "/";
// m_log.DebugFormat("[J2KIMAGE]: texture {0} not found in local asset storage. Trying user's storage.", assetServerURL + id);
AssetService.Get(assetServerURL + id, InventoryAccessModule, AssetReceived);
return;
}
}
AssetDataCallback(assetID, asset);
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using AllReady.Models;
namespace AllReady.Migrations
{
[DbContext(typeof(AllReadyContext))]
[Migration("20160417142032_AddExternalUrlToCampaigns")]
partial class AddExternalUrlToCampaigns
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("AllReady.Models.Activity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("EventType");
b.Property<int>("CampaignId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<string>("ImageUrl");
b.Property<bool>("IsAllowWaitList");
b.Property<bool>("IsLimitVolunteers");
b.Property<int?>("LocationId");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("ActivityId");
b.Property<string>("AdditionalInfo");
b.Property<DateTime?>("CheckinDateTime");
b.Property<string>("PreferredEmail");
b.Property<string>("PreferredPhoneNumber");
b.Property<DateTime>("SignupDateTime");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ActivitySkill", b =>
{
b.Property<int>("ActivityId");
b.Property<int>("SkillId");
b.HasKey("ActivityId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("ActivityId");
b.Property<string>("Description");
b.Property<DateTimeOffset?>("EndDateTime");
b.Property<bool>("IsAllowWaitList");
b.Property<bool>("IsLimitVolunteers");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<int?>("OrganizationId");
b.Property<DateTimeOffset?>("StartDateTime");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("Name");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<int?>("OrganizationId");
b.Property<string>("PasswordHash");
b.Property<string>("PendingNewEmail");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<string>("TimeZoneId")
.IsRequired();
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignImpactId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<string>("ExternalUrl");
b.Property<string>("ExternalUrlText");
b.Property<string>("FullDescription");
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<bool>("Locked");
b.Property<int>("ManagingOrganizationId");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.Property<string>("TimeZoneId")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.Property<int>("CampaignId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("CampaignId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.CampaignImpact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CurrentImpactLevel");
b.Property<bool>("Display");
b.Property<int>("ImpactType");
b.Property<int>("NumericImpactGoal");
b.Property<string>("TextualImpactGoal");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignId");
b.Property<int?>("OrganizationId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ClosestLocation", b =>
{
b.Property<string>("PostalCode");
b.Property<string>("City");
b.Property<double>("Distance");
b.Property<string>("State");
b.HasKey("PostalCode");
});
modelBuilder.Entity("AllReady.Models.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.Property<string>("PhoneNumber");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address1");
b.Property<string>("Address2");
b.Property<string>("City");
b.Property<string>("Country");
b.Property<string>("Name");
b.Property<string>("PhoneNumber");
b.Property<string>("PostalCodePostalCode");
b.Property<string>("State");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Organization", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("LocationId");
b.Property<string>("LogoUrl");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("PrivacyPolicy");
b.Property<string>("WebUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.OrganizationContact", b =>
{
b.Property<int>("OrganizationId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("OrganizationId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b =>
{
b.Property<string>("PostalCode");
b.Property<string>("City");
b.Property<string>("State");
b.HasKey("PostalCode");
});
modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b =>
{
b.Property<double>("Latitude");
b.Property<double>("Longitude");
b.HasKey("Latitude", "Longitude");
});
modelBuilder.Entity("AllReady.Models.Resource", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CategoryTag");
b.Property<string>("Description");
b.Property<string>("MediaUrl");
b.Property<string>("Name");
b.Property<DateTime>("PublishDateBegin");
b.Property<DateTime>("PublishDateEnd");
b.Property<string>("ResourceUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("Name")
.IsRequired();
b.Property<int?>("OwningOrganizationId");
b.Property<int?>("ParentSkillId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AdditionalInfo");
b.Property<string>("PreferredEmail");
b.Property<string>("PreferredPhoneNumber");
b.Property<string>("Status");
b.Property<DateTime>("StatusDateTimeUtc");
b.Property<string>("StatusDescription");
b.Property<int?>("TaskId");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.Property<int>("TaskId");
b.Property<int>("SkillId");
b.HasKey("TaskId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.Property<string>("UserId");
b.Property<int>("SkillId");
b.HasKey("UserId", "SkillId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("AllReady.Models.Activity", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.ActivitySkill", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.HasOne("AllReady.Models.CampaignImpact")
.WithMany()
.HasForeignKey("CampaignImpactId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("ManagingOrganizationId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.HasOne("AllReady.Models.PostalCodeGeo")
.WithMany()
.HasForeignKey("PostalCodePostalCode");
});
modelBuilder.Entity("AllReady.Models.Organization", b =>
{
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
});
modelBuilder.Entity("AllReady.Models.OrganizationContact", b =>
{
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OrganizationId");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.HasOne("AllReady.Models.Organization")
.WithMany()
.HasForeignKey("OwningOrganizationId");
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("ParentSkillId");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
//
// System.Web.HttpApplicationFactory
//
// Author:
// Patrik Torstensson (ptorsten@hotmail.com)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (c) 2002,2003 Ximian, Inc. (http://www.ximian.com)
// (c) Copyright 2004 Novell, Inc. (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Web.UI;
using System.Web.SessionState;
#if !TARGET_J2EE
using System.Web.Compilation;
#else
using System.Web.Configuration;
using vmw.common;
#endif
namespace System.Web {
class HttpApplicationFactory {
private string _appFilename;
private Type _appType;
private bool _appInitialized;
private bool _appFiredEnd;
private Stack _appFreePublicList;
private int _appFreePublicInstances;
FileSystemWatcher appFileWatcher;
FileSystemWatcher binWatcher;
static private int _appMaxFreePublicInstances = 32;
private HttpApplicationState _state;
static IHttpHandler custApplication;
#if TARGET_J2EE
static private HttpApplicationFactory s_Factory {
get {
HttpApplicationFactory factory = (HttpApplicationFactory)AppDomain.CurrentDomain.GetData("HttpApplicationFactory");
if (factory == null) {
factory = new HttpApplicationFactory();
AppDomain.CurrentDomain.SetData("HttpApplicationFactory", factory);
}
return factory;
}
}
#else
static private HttpApplicationFactory s_Factory = new HttpApplicationFactory();
#endif
public HttpApplicationFactory() {
_appInitialized = false;
_appFiredEnd = false;
_appFreePublicList = new Stack();
_appFreePublicInstances = 0;
}
static private string GetAppFilename (HttpContext context)
{
string physicalAppPath = context.Request.PhysicalApplicationPath;
string appFilePath = Path.Combine (physicalAppPath, "Global.asax");
if (File.Exists (appFilePath))
return appFilePath;
return Path.Combine (physicalAppPath, "global.asax");
}
#if TARGET_J2EE
void CompileApp(HttpContext context)
{
try
{
String url = IAppDomainConfig.WAR_ROOT_SYMBOL+"/global.asax";
_appType = System.Web.GH.PageMapper.GetObjectType(url);
}
catch (Exception e)
{
_appType = typeof (System.Web.HttpApplication);
}
_state = new HttpApplicationState ();
}
#endif
#if !TARGET_J2EE
void CompileApp (HttpContext context)
{
if (File.Exists (_appFilename)) {
_appType = ApplicationFileParser.GetCompiledApplicationType (_appFilename, context);
if (_appType == null) {
string msg = String.Format ("Error compiling application file ({0}).", _appFilename);
throw new ApplicationException (msg);
}
appFileWatcher = CreateWatcher (_appFilename, new FileSystemEventHandler (OnAppFileChanged));
} else {
_appType = typeof (System.Web.HttpApplication);
_state = new HttpApplicationState ();
}
}
#endif
static bool IsEventHandler (MethodInfo m)
{
if (m.ReturnType != typeof (void))
return false;
ParameterInfo [] pi = m.GetParameters ();
int length = pi.Length;
if (length == 0)
return true;
if (length != 2)
return false;
if (pi [0].ParameterType != typeof (object) ||
pi [1].ParameterType != typeof (EventArgs))
return false;
return true;
}
static void AddEvent (MethodInfo method, Hashtable appTypeEventHandlers)
{
string name = method.Name.Replace ("_On", "_");
if (appTypeEventHandlers [name] == null) {
appTypeEventHandlers [name] = method;
return;
}
ArrayList list;
if (appTypeEventHandlers [name] is MethodInfo)
list = new ArrayList ();
else
list = appTypeEventHandlers [name] as ArrayList;
list.Add (method);
}
static Hashtable GetApplicationTypeEvents (HttpApplication app)
{
Type appType = app.GetType ();
Hashtable appTypeEventHandlers = new Hashtable ();
BindingFlags flags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static;
MethodInfo [] methods = appType.GetMethods (flags);
foreach (MethodInfo m in methods) {
if (IsEventHandler (m))
AddEvent (m, appTypeEventHandlers);
}
return appTypeEventHandlers;
}
static bool FireEvent (string method_name, object target, object [] args)
{
Hashtable possibleEvents = GetApplicationTypeEvents ((HttpApplication) target);
MethodInfo method = possibleEvents [method_name] as MethodInfo;
if (method == null)
return false;
if (method.GetParameters ().Length == 0)
args = null;
try {
method.Invoke (target, args);
} catch {
// Ignore any exception here
}
return true;
}
internal static void FireOnAppStart (HttpApplication app)
{
object [] args = new object [] {app, EventArgs.Empty};
FireEvent ("Application_Start", app, args);
}
void FireOnAppEnd ()
{
if (_appType == null)
return; // we didn't even get an application
HttpApplication app = (HttpApplication) HttpRuntime.CreateInternalObject (_appType);
AttachEvents (app);
FireEvent ("Application_End", app, new object [] {this, EventArgs.Empty});
app.Dispose ();
}
FileSystemWatcher CreateWatcher (string file, FileSystemEventHandler hnd)
{
FileSystemWatcher watcher = new FileSystemWatcher ();
watcher.Path = Path.GetFullPath (Path.GetDirectoryName (file));
watcher.Filter = Path.GetFileName (file);
watcher.Changed += hnd;
watcher.Created += hnd;
watcher.Deleted += hnd;
watcher.EnableRaisingEvents = true;
return watcher;
}
void OnAppFileChanged (object sender, FileSystemEventArgs args)
{
binWatcher.EnableRaisingEvents = false;
appFileWatcher.EnableRaisingEvents = false;
HttpRuntime.UnloadAppDomain ();
}
private void InitializeFactory (HttpContext context)
{
_appFilename = GetAppFilename (context);
CompileApp (context);
// Create a application object
HttpApplication app = (HttpApplication) HttpRuntime.CreateInternalObject (_appType);
// Startup
app.Startup(context, HttpApplicationFactory.ApplicationState);
// Shutdown the application if bin directory changes.
string binFiles = HttpRuntime.BinDirectory;
if (Directory.Exists (binFiles))
binFiles = Path.Combine (binFiles, "*.*");
binWatcher = CreateWatcher (binFiles, new FileSystemEventHandler (OnAppFileChanged));
// Fire OnAppStart
HttpApplicationFactory.FireOnAppStart (app);
// Recycle our application instance
RecyclePublicInstance(app);
}
private void Dispose() {
ArrayList torelease = new ArrayList();
lock (_appFreePublicList) {
while (_appFreePublicList.Count > 0) {
torelease.Add(_appFreePublicList.Pop());
_appFreePublicInstances--;
}
}
if (torelease.Count > 0) {
foreach (Object obj in torelease) {
((HttpApplication) obj).Cleanup();
}
}
if (!_appFiredEnd) {
lock (this) {
if (!_appFiredEnd) {
FireOnAppEnd();
_appFiredEnd = true;
}
}
}
}
internal static IHttpHandler GetInstance(HttpContext context)
{
if (custApplication != null)
return custApplication;
if (!s_Factory._appInitialized) {
lock (s_Factory) {
if (!s_Factory._appInitialized) {
s_Factory.InitializeFactory(context);
s_Factory._appInitialized = true;
}
}
}
return s_Factory.GetPublicInstance(context);
}
internal static void RecycleInstance(HttpApplication app) {
if (!s_Factory._appInitialized)
throw new InvalidOperationException("Factory not intialized");
s_Factory.RecyclePublicInstance(app);
}
internal static void AttachEvents (HttpApplication app)
{
Hashtable possibleEvents = GetApplicationTypeEvents (app);
foreach (string key in possibleEvents.Keys) {
int pos = key.IndexOf ('_');
if (pos == -1 || key.Length <= pos + 1)
continue;
string moduleName = key.Substring (0, pos);
object target;
if (moduleName == "Application") {
target = app;
} else {
target = app.Modules [moduleName];
if (target == null)
continue;
}
string eventName = key.Substring (pos + 1);
EventInfo evt = target.GetType ().GetEvent (eventName);
if (evt == null)
continue;
string usualName = moduleName + "_" + eventName;
object methodData = possibleEvents [usualName];
if (methodData == null)
continue;
if (methodData is MethodInfo) {
AddHandler (evt, target, app, (MethodInfo) methodData);
continue;
}
ArrayList list = (ArrayList) methodData;
foreach (MethodInfo method in list)
AddHandler (evt, target, app, method);
}
}
static void AddHandler (EventInfo evt, object target, HttpApplication app, MethodInfo method)
{
int length = method.GetParameters ().Length;
if (length == 0) {
NoParamsInvoker npi = new NoParamsInvoker (app, method.Name);
evt.AddEventHandler (target, npi.FakeDelegate);
} else {
evt.AddEventHandler (target, Delegate.CreateDelegate (
typeof (EventHandler), app, method.Name));
}
}
#if TARGET_J2EE
internal HttpApplication GetPublicInstance()
{
HttpApplication app = null;
lock (_appFreePublicList)
{
if (_appFreePublicInstances > 0)
{
app = (HttpApplication) _appFreePublicList.Pop();
_appFreePublicInstances--;
}
}
return app;
}
#endif
private IHttpHandler GetPublicInstance(HttpContext context) {
HttpApplication app = null;
lock (_appFreePublicList) {
if (_appFreePublicInstances > 0) {
app = (HttpApplication) _appFreePublicList.Pop();
_appFreePublicInstances--;
}
}
if (app == null) {
// Create non-public object
app = (HttpApplication) HttpRuntime.CreateInternalObject(_appType);
app.Startup(context, HttpApplicationFactory.ApplicationState);
}
return (IHttpHandler) app;
}
internal void RecyclePublicInstance(HttpApplication app) {
lock (_appFreePublicList) {
if (_appFreePublicInstances < _appMaxFreePublicInstances) {
_appFreePublicList.Push(app);
_appFreePublicInstances++;
app = null;
}
}
if (app != null) {
app.Cleanup();
}
}
static HttpStaticObjectsCollection MakeStaticCollection (ArrayList list)
{
if (list == null || list.Count == 0)
return null;
HttpStaticObjectsCollection coll = new HttpStaticObjectsCollection ();
foreach (ObjectTagBuilder tag in list) {
coll.Add (tag);
}
return coll;
}
static internal HttpApplicationState ApplicationState {
#if TARGET_J2EE
get {
if (null == s_Factory._state) {
HttpStaticObjectsCollection app = null;
HttpStaticObjectsCollection ses = null;
s_Factory._state = new HttpApplicationState (app, ses);
}
return s_Factory._state;
}
#else
get {
if (null == s_Factory._state) {
HttpStaticObjectsCollection app = MakeStaticCollection (GlobalAsaxCompiler.ApplicationObjects);
HttpStaticObjectsCollection ses = MakeStaticCollection (GlobalAsaxCompiler.SessionObjects);
s_Factory._state = new HttpApplicationState (app, ses);
}
return s_Factory._state;
}
#endif
}
internal static void EndApplication() {
s_Factory.Dispose();
}
public static void SetCustomApplication (IHttpHandler customApplication)
{
custApplication = customApplication;
}
internal Type AppType {
get { return _appType; }
}
internal static void SignalError(Exception exc) {
// TODO: Raise an error (we probably don't have a HttpContext)
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
namespace System.Web.Util
{
internal static class HttpEncoder
{
private static void AppendCharAsUnicodeJavaScript(StringBuilder builder, char c)
{
builder.Append("\\u");
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
}
private static bool CharRequiresJavaScriptEncoding(char c)
{
return c < 0x20 // control chars always have to be encoded
|| c == '\"' // chars which must be encoded per JSON spec
|| c == '\\'
|| c == '\'' // HTML-sensitive chars encoded for safety
|| c == '<'
|| c == '>'
|| (c == '&')
|| c == '\u0085' // newline chars (see Unicode 6.2, Table 5-1 [http://www.unicode.org/versions/Unicode6.2.0/ch05.pdf]) have to be encoded
|| c == '\u2028'
|| c == '\u2029';
}
internal static string HtmlAttributeEncode(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
// Don't create string writer if we don't have nothing to encode
int pos = IndexOfHtmlAttributeEncodingChars(value, 0);
if (pos == -1)
{
return value;
}
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
HtmlAttributeEncode(value, writer);
return writer.ToString();
}
internal static void HtmlAttributeEncode(string value, TextWriter output)
{
if (value == null)
{
return;
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
HtmlAttributeEncodeInternal(value, output);
}
private static unsafe void HtmlAttributeEncodeInternal(string s, TextWriter output)
{
int index = IndexOfHtmlAttributeEncodingChars(s, 0);
if (index == -1)
{
output.Write(s);
}
else
{
int cch = s.Length - index;
fixed (char* str = s)
{
char* pch = str;
while (index-- > 0)
{
output.Write(*pch++);
}
while (cch-- > 0)
{
char ch = *pch++;
if (ch <= '<')
{
switch (ch)
{
case '<':
output.Write("<");
break;
case '"':
output.Write(""");
break;
case '\'':
output.Write("'");
break;
case '&':
output.Write("&");
break;
default:
output.Write(ch);
break;
}
}
else
{
output.Write(ch);
}
}
}
}
}
internal static string HtmlDecode(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
return WebUtility.HtmlDecode(value);
}
internal static void HtmlDecode(string value, TextWriter output)
{
if (output == null)
throw new ArgumentNullException(nameof(output));
output.Write(WebUtility.HtmlDecode(value));
}
internal static string HtmlEncode(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
return WebUtility.HtmlEncode(value);
}
internal static void HtmlEncode(string value, TextWriter output)
{
if (output == null)
throw new ArgumentNullException(nameof(output));
output.Write(WebUtility.HtmlEncode(value));
}
private static unsafe int IndexOfHtmlAttributeEncodingChars(string s, int startPos)
{
Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length");
int cch = s.Length - startPos;
fixed (char* str = s)
{
for (char* pch = &str[startPos]; cch > 0; pch++, cch--)
{
char ch = *pch;
if (ch <= '<')
{
switch (ch)
{
case '<':
case '"':
case '\'':
case '&':
return s.Length - cch;
}
}
}
}
return -1;
}
private static bool IsNonAsciiByte(byte b)
{
return (b >= 0x7F || b < 0x20);
}
internal static string JavaScriptStringEncode(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
StringBuilder b = null;
int startIndex = 0;
int count = 0;
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
// Append the unhandled characters (that do not require special treament)
// to the string builder when special characters are detected.
if (CharRequiresJavaScriptEncoding(c))
{
if (b == null)
{
b = new StringBuilder(value.Length + 5);
}
if (count > 0)
{
b.Append(value, startIndex, count);
}
startIndex = i + 1;
count = 0;
}
switch (c)
{
case '\r':
b.Append("\\r");
break;
case '\t':
b.Append("\\t");
break;
case '\"':
b.Append("\\\"");
break;
case '\\':
b.Append("\\\\");
break;
case '\n':
b.Append("\\n");
break;
case '\b':
b.Append("\\b");
break;
case '\f':
b.Append("\\f");
break;
default:
if (CharRequiresJavaScriptEncoding(c))
{
AppendCharAsUnicodeJavaScript(b, c);
}
else
{
count++;
}
break;
}
}
if (b == null)
{
return value;
}
if (count > 0)
{
b.Append(value, startIndex, count);
}
return b.ToString();
}
internal static byte[] UrlDecode(byte[] bytes, int offset, int count)
{
if (!ValidateUrlEncodingParameters(bytes, offset, count))
{
return null;
}
int decodedBytesCount = 0;
byte[] decodedBytes = new byte[count];
for (int i = 0; i < count; i++)
{
int pos = offset + i;
byte b = bytes[pos];
if (b == '+')
{
b = (byte)' ';
}
else if (b == '%' && i < count - 2)
{
int h1 = HttpEncoderUtility.HexToInt((char)bytes[pos + 1]);
int h2 = HttpEncoderUtility.HexToInt((char)bytes[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{
// valid 2 hex chars
b = (byte)((h1 << 4) | h2);
i += 2;
}
}
decodedBytes[decodedBytesCount++] = b;
}
if (decodedBytesCount < decodedBytes.Length)
{
byte[] newDecodedBytes = new byte[decodedBytesCount];
Array.Copy(decodedBytes, newDecodedBytes, decodedBytesCount);
decodedBytes = newDecodedBytes;
}
return decodedBytes;
}
internal static string UrlDecode(byte[] bytes, int offset, int count, Encoding encoding)
{
if (!ValidateUrlEncodingParameters(bytes, offset, count))
{
return null;
}
UrlDecoder helper = new UrlDecoder(count, encoding);
// go through the bytes collapsing %XX and %uXXXX and appending
// each byte as byte, with exception of %uXXXX constructs that
// are appended as chars
for (int i = 0; i < count; i++)
{
int pos = offset + i;
byte b = bytes[pos];
// The code assumes that + and % cannot be in multibyte sequence
if (b == '+')
{
b = (byte)' ';
}
else if (b == '%' && i < count - 2)
{
if (bytes[pos + 1] == 'u' && i < count - 5)
{
int h1 = HttpEncoderUtility.HexToInt((char)bytes[pos + 2]);
int h2 = HttpEncoderUtility.HexToInt((char)bytes[pos + 3]);
int h3 = HttpEncoderUtility.HexToInt((char)bytes[pos + 4]);
int h4 = HttpEncoderUtility.HexToInt((char)bytes[pos + 5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
{ // valid 4 hex chars
char ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
i += 5;
// don't add as byte
helper.AddChar(ch);
continue;
}
}
else
{
int h1 = HttpEncoderUtility.HexToInt((char)bytes[pos + 1]);
int h2 = HttpEncoderUtility.HexToInt((char)bytes[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
b = (byte)((h1 << 4) | h2);
i += 2;
}
}
}
helper.AddByte(b);
}
return Utf16StringValidator.ValidateString(helper.GetString());
}
internal static string UrlDecode(string value, Encoding encoding)
{
if (value == null)
{
return null;
}
int count = value.Length;
UrlDecoder helper = new UrlDecoder(count, encoding);
// go through the string's chars collapsing %XX and %uXXXX and
// appending each char as char, with exception of %XX constructs
// that are appended as bytes
for (int pos = 0; pos < count; pos++)
{
char ch = value[pos];
if (ch == '+')
{
ch = ' ';
}
else if (ch == '%' && pos < count - 2)
{
if (value[pos + 1] == 'u' && pos < count - 5)
{
int h1 = HttpEncoderUtility.HexToInt(value[pos + 2]);
int h2 = HttpEncoderUtility.HexToInt(value[pos + 3]);
int h3 = HttpEncoderUtility.HexToInt(value[pos + 4]);
int h4 = HttpEncoderUtility.HexToInt(value[pos + 5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
{ // valid 4 hex chars
ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
pos += 5;
// only add as char
helper.AddChar(ch);
continue;
}
}
else
{
int h1 = HttpEncoderUtility.HexToInt(value[pos + 1]);
int h2 = HttpEncoderUtility.HexToInt(value[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
byte b = (byte)((h1 << 4) | h2);
pos += 2;
// don't add as char
helper.AddByte(b);
continue;
}
}
}
if ((ch & 0xFF80) == 0)
{
helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
}
else
{
helper.AddChar(ch);
}
}
return Utf16StringValidator.ValidateString(helper.GetString());
}
internal static byte[] UrlEncode(byte[] bytes, int offset, int count, bool alwaysCreateNewReturnValue)
{
byte[] encoded = UrlEncode(bytes, offset, count);
return (alwaysCreateNewReturnValue && (encoded != null) && (encoded == bytes))
? (byte[])encoded.Clone()
: encoded;
}
private static byte[] UrlEncode(byte[] bytes, int offset, int count)
{
if (!ValidateUrlEncodingParameters(bytes, offset, count))
{
return null;
}
int cSpaces = 0;
int cUnsafe = 0;
// count them first
for (int i = 0; i < count; i++)
{
char ch = (char)bytes[offset + i];
if (ch == ' ')
cSpaces++;
else if (!HttpEncoderUtility.IsUrlSafeChar(ch))
cUnsafe++;
}
// nothing to expand?
if (cSpaces == 0 && cUnsafe == 0)
{
// DevDiv 912606: respect "offset" and "count"
if (0 == offset && bytes.Length == count)
{
return bytes;
}
else
{
var subarray = new byte[count];
Buffer.BlockCopy(bytes, offset, subarray, 0, count);
return subarray;
}
}
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + cUnsafe * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[offset + i];
char ch = (char)b;
if (HttpEncoderUtility.IsUrlSafeChar(ch))
{
expandedBytes[pos++] = b;
}
else if (ch == ' ')
{
expandedBytes[pos++] = (byte)'+';
}
else
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex(b & 0x0f);
}
}
return expandedBytes;
}
// Helper to encode the non-ASCII url characters only
private static string UrlEncodeNonAscii(string str, Encoding e)
{
if (string.IsNullOrEmpty(str))
return str;
if (e == null)
e = Encoding.UTF8;
byte[] bytes = e.GetBytes(str);
byte[] encodedBytes = UrlEncodeNonAscii(bytes, 0, bytes.Length, false /* alwaysCreateNewReturnValue */);
return Encoding.ASCII.GetString(encodedBytes);
}
private static byte[] UrlEncodeNonAscii(byte[] bytes, int offset, int count, bool alwaysCreateNewReturnValue)
{
if (!ValidateUrlEncodingParameters(bytes, offset, count))
{
return null;
}
int cNonAscii = 0;
// count them first
for (int i = 0; i < count; i++)
{
if (IsNonAsciiByte(bytes[offset + i]))
cNonAscii++;
}
// nothing to expand?
if (!alwaysCreateNewReturnValue && cNonAscii == 0)
return bytes;
// expand not 'safe' characters into %XX, spaces to +s
byte[] expandedBytes = new byte[count + cNonAscii * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[offset + i];
if (IsNonAsciiByte(b))
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)HttpEncoderUtility.IntToHex(b & 0x0f);
}
else
{
expandedBytes[pos++] = b;
}
}
return expandedBytes;
}
[Obsolete("This method produces non-standards-compliant output and has interoperability issues. The preferred alternative is UrlEncode(*).")]
internal static string UrlEncodeUnicode(string value, bool ignoreAscii)
{
if (value == null)
{
return null;
}
int l = value.Length;
StringBuilder sb = new StringBuilder(l);
for (int i = 0; i < l; i++)
{
char ch = value[i];
if ((ch & 0xff80) == 0)
{ // 7 bit?
if (ignoreAscii || HttpEncoderUtility.IsUrlSafeChar(ch))
{
sb.Append(ch);
}
else if (ch == ' ')
{
sb.Append('+');
}
else
{
sb.Append('%');
sb.Append(HttpEncoderUtility.IntToHex((ch >> 4) & 0xf));
sb.Append(HttpEncoderUtility.IntToHex((ch) & 0xf));
}
}
else
{ // arbitrary Unicode?
sb.Append("%u");
sb.Append(HttpEncoderUtility.IntToHex((ch >> 12) & 0xf));
sb.Append(HttpEncoderUtility.IntToHex((ch >> 8) & 0xf));
sb.Append(HttpEncoderUtility.IntToHex((ch >> 4) & 0xf));
sb.Append(HttpEncoderUtility.IntToHex((ch) & 0xf));
}
}
return sb.ToString();
}
[SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
Justification = "Does not represent an entire URL, just a portion.")]
internal static string UrlPathEncode(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
string schemeAndAuthority;
string path;
string queryAndFragment;
bool isValidUrl = UriUtil.TrySplitUriForPathEncode(value, out schemeAndAuthority, out path, out queryAndFragment);
if (!isValidUrl)
{
// If the value is not a valid url, we treat it as a relative url.
// We don't need to extract query string from the url since UrlPathEncode()
// does not encode query string.
schemeAndAuthority = null;
path = value;
queryAndFragment = null;
}
return schemeAndAuthority + UrlPathEncodeImpl(path) + queryAndFragment;
}
// This is the original UrlPathEncode(string)
[SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
Justification = "Does not represent an entire URL, just a portion.")]
private static string UrlPathEncodeImpl(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
// recurse in case there is a query string
int i = value.IndexOf('?');
if (i >= 0)
return UrlPathEncodeImpl(value.Substring(0, i)) + value.Substring(i);
// encode DBCS characters and spaces only
return HttpEncoderUtility.UrlEncodeSpaces(UrlEncodeNonAscii(value, Encoding.UTF8));
}
private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count)
{
if (bytes == null && count == 0)
return false;
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
if (offset < 0 || offset > bytes.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || offset + count > bytes.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
return true;
}
// Internal class to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes
private class UrlDecoder
{
private readonly int _bufferSize;
// Accumulate characters in a special array
private int _numChars;
private readonly char[] _charBuffer;
// Accumulate bytes for decoding into characters in a special array
private int _numBytes;
private byte[] _byteBuffer;
// Encoding to convert chars to bytes
private readonly Encoding _encoding;
private void FlushBytes()
{
if (_numBytes > 0)
{
_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
}
}
internal UrlDecoder(int bufferSize, Encoding encoding)
{
_bufferSize = bufferSize;
_encoding = encoding;
_charBuffer = new char[bufferSize];
// byte buffer created on demand
}
internal void AddChar(char ch)
{
if (_numBytes > 0)
FlushBytes();
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b)
{
// if there are no pending bytes treat 7 bit bytes as characters
// this optimization is temp disable as it doesn't work for some encodings
/*
if (_numBytes == 0 && ((b & 0x80) == 0)) {
AddChar((char)b);
}
else
*/
{
if (_byteBuffer == null)
_byteBuffer = new byte[_bufferSize];
_byteBuffer[_numBytes++] = b;
}
}
internal string GetString()
{
if (_numBytes > 0)
FlushBytes();
if (_numChars > 0)
return new string(_charBuffer, 0, _numChars);
else
return string.Empty;
}
}
}
}
| |
/*
Copyright (c) 2012-2013, dewitcher Team
Copyright (c) 2019, Siaranite Solutions
Copyright (c) 2019, Cosmos
All rights reserved.
See in the /Licenses folder for the licenses for each respected project.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace AIC.Main.Crypto
{
/// <summary>
/// Thanks to Aurora01!
/// </summary>
public static class MD5
{
/// <summary>
/// Return hash of a string
/// </summary>
/// <param name="str"></param>
/// <returns>Hash MD5</returns>
public static string Hash(string input)
{
Value = input;
return FingerPrint;
}
/***********************Statics**************************************/
/// <summary>
/// lookup table 4294967296*sin(i)
/// </summary>
internal readonly static uint[] T = new uint[64]
{ 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391};
/*****instance variables**************/
/// <summary>
/// X used to proces data in
/// 512 bits chunks as 16 32 bit word
/// </summary>
internal static uint[] X = new uint[16];
/// <summary>
/// the finger print obtained.
/// </summary>
internal static Digest dgFingerPrint;
/// <summary>
/// the input bytes
/// </summary>
internal static byte[] m_byteInput;
/***********************PROPERTIES ***********************/
/// <summary>
///gets or sets as string
/// </summary>
internal static string Value
{
get
{
string st;
char[] tempCharArray = new Char[m_byteInput.Length];
for (int i = 0; i < m_byteInput.Length; i++)
tempCharArray[i] = (char)m_byteInput[i];
st = new String(tempCharArray);
return st;
}
set
{
m_byteInput = new byte[value.Length];
for (int i = 0; i < value.Length; i++)
m_byteInput[i] = (byte)value[i];
dgFingerPrint = CalculateMD5Value();
}
}
/// <summary>
/// Get/sets as byte array
/// </summary>
internal static byte[] ValueAsByte
{
get
{
byte[] bt = new byte[m_byteInput.Length];
for (int i = 0; i < m_byteInput.Length; i++)
bt[i] = m_byteInput[i];
return bt;
}
set
{
m_byteInput = new byte[value.Length];
for (int i = 0; i < value.Length; i++)
m_byteInput[i] = value[i];
dgFingerPrint = CalculateMD5Value();
}
}
/// <summary>
/// Gets the signature/figner print as string
/// </summary>
internal static string FingerPrint
{
get
{
return dgFingerPrint.ToString();
}
}
/*********************METHODS**************************/
/// <summary>
/// calculat md5 signature of the string in Input
/// </summary>
/// <returns> Digest: the finger print of msg</returns>
internal static Digest CalculateMD5Value()
{
/***********vairable declaration**************/
byte[] bMsg; //buffer to hold bits
uint N; //N is the size of msg as word (32 bit)
Digest dg = new Digest(); // the value to be returned
// create a buffer with bits padded and length is alos padded
bMsg = CreatePaddedBuffer();
N = (uint)(bMsg.Length * 8) / 32; //no of 32 bit blocks
for (uint i = 0; i < N / 16; i++)
{
CopyBlock(bMsg, i);
PerformTransformation(ref dg.A, ref dg.B, ref dg.C, ref dg.D);
}
return dg;
}
/********************************************************
* TRANSFORMATIONS : FF , GG , HH , II acc to RFC 1321
* where each Each letter represnets the aux function used
*********************************************************/
/// <summary>
/// perform transformatio using f(((b&c) | (~(b)&d))
/// </summary>
internal static void TransF(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i)
{
a = b + MD5Helper.RotateLeft((a + ((b & c) | (~(b) & d)) + X[k] + T[i - 1]), s);
}
/// <summary>
/// perform transformatio using g((b&d) | (c & ~d) )
/// </summary>
internal static void TransG(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i)
{
a = b + MD5Helper.RotateLeft((a + ((b & d) | (c & ~d)) + X[k] + T[i - 1]), s);
}
/// <summary>
/// perform transformatio using h(b^c^d)
/// </summary>
internal static void TransH(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i)
{
a = b + MD5Helper.RotateLeft((a + (b ^ c ^ d) + X[k] + T[i - 1]), s);
}
/// <summary>
/// perform transformatio using i (c^(b|~d))
/// </summary>
internal static void TransI(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i)
{
a = b + MD5Helper.RotateLeft((a + (c ^ (b | ~d)) + X[k] + T[i - 1]), s);
}
/// <summary>
/// Perform All the transformation on the data
/// </summary>
/// <param name="A">A</param>
/// <param name="B">B </param>
/// <param name="C">C</param>
/// <param name="D">D</param>
internal static void PerformTransformation(ref uint A, ref uint B, ref uint C, ref uint D)
{
//// saving ABCD to be used in end of loop
uint AA, BB, CC, DD;
AA = A;
BB = B;
CC = C;
DD = D;
/* Round 1
* [ABCD 0 7 1] [DABC 1 12 2] [CDAB 2 17 3] [BCDA 3 22 4]
* [ABCD 4 7 5] [DABC 5 12 6] [CDAB 6 17 7] [BCDA 7 22 8]
* [ABCD 8 7 9] [DABC 9 12 10] [CDAB 10 17 11] [BCDA 11 22 12]
* [ABCD 12 7 13] [DABC 13 12 14] [CDAB 14 17 15] [BCDA 15 22 16]
* * */
TransF(ref A, B, C, D, 0, 7, 1); TransF(ref D, A, B, C, 1, 12, 2); TransF(ref C, D, A, B, 2, 17, 3); TransF(ref B, C, D, A, 3, 22, 4);
TransF(ref A, B, C, D, 4, 7, 5); TransF(ref D, A, B, C, 5, 12, 6); TransF(ref C, D, A, B, 6, 17, 7); TransF(ref B, C, D, A, 7, 22, 8);
TransF(ref A, B, C, D, 8, 7, 9); TransF(ref D, A, B, C, 9, 12, 10); TransF(ref C, D, A, B, 10, 17, 11); TransF(ref B, C, D, A, 11, 22, 12);
TransF(ref A, B, C, D, 12, 7, 13); TransF(ref D, A, B, C, 13, 12, 14); TransF(ref C, D, A, B, 14, 17, 15); TransF(ref B, C, D, A, 15, 22, 16);
/** rOUND 2
**[ABCD 1 5 17] [DABC 6 9 18] [CDAB 11 14 19] [BCDA 0 20 20]
*[ABCD 5 5 21] [DABC 10 9 22] [CDAB 15 14 23] [BCDA 4 20 24]
*[ABCD 9 5 25] [DABC 14 9 26] [CDAB 3 14 27] [BCDA 8 20 28]
*[ABCD 13 5 29] [DABC 2 9 30] [CDAB 7 14 31] [BCDA 12 20 32]
*/
TransG(ref A, B, C, D, 1, 5, 17); TransG(ref D, A, B, C, 6, 9, 18); TransG(ref C, D, A, B, 11, 14, 19); TransG(ref B, C, D, A, 0, 20, 20);
TransG(ref A, B, C, D, 5, 5, 21); TransG(ref D, A, B, C, 10, 9, 22); TransG(ref C, D, A, B, 15, 14, 23); TransG(ref B, C, D, A, 4, 20, 24);
TransG(ref A, B, C, D, 9, 5, 25); TransG(ref D, A, B, C, 14, 9, 26); TransG(ref C, D, A, B, 3, 14, 27); TransG(ref B, C, D, A, 8, 20, 28);
TransG(ref A, B, C, D, 13, 5, 29); TransG(ref D, A, B, C, 2, 9, 30); TransG(ref C, D, A, B, 7, 14, 31); TransG(ref B, C, D, A, 12, 20, 32);
/* rOUND 3
* [ABCD 5 4 33] [DABC 8 11 34] [CDAB 11 16 35] [BCDA 14 23 36]
* [ABCD 1 4 37] [DABC 4 11 38] [CDAB 7 16 39] [BCDA 10 23 40]
* [ABCD 13 4 41] [DABC 0 11 42] [CDAB 3 16 43] [BCDA 6 23 44]
* [ABCD 9 4 45] [DABC 12 11 46] [CDAB 15 16 47] [BCDA 2 23 48]
* */
TransH(ref A, B, C, D, 5, 4, 33); TransH(ref D, A, B, C, 8, 11, 34); TransH(ref C, D, A, B, 11, 16, 35); TransH(ref B, C, D, A, 14, 23, 36);
TransH(ref A, B, C, D, 1, 4, 37); TransH(ref D, A, B, C, 4, 11, 38); TransH(ref C, D, A, B, 7, 16, 39); TransH(ref B, C, D, A, 10, 23, 40);
TransH(ref A, B, C, D, 13, 4, 41); TransH(ref D, A, B, C, 0, 11, 42); TransH(ref C, D, A, B, 3, 16, 43); TransH(ref B, C, D, A, 6, 23, 44);
TransH(ref A, B, C, D, 9, 4, 45); TransH(ref D, A, B, C, 12, 11, 46); TransH(ref C, D, A, B, 15, 16, 47); TransH(ref B, C, D, A, 2, 23, 48);
/*ORUNF 4
*[ABCD 0 6 49] [DABC 7 10 50] [CDAB 14 15 51] [BCDA 5 21 52]
*[ABCD 12 6 53] [DABC 3 10 54] [CDAB 10 15 55] [BCDA 1 21 56]
*[ABCD 8 6 57] [DABC 15 10 58] [CDAB 6 15 59] [BCDA 13 21 60]
*[ABCD 4 6 61] [DABC 11 10 62] [CDAB 2 15 63] [BCDA 9 21 64]
* */
TransI(ref A, B, C, D, 0, 6, 49); TransI(ref D, A, B, C, 7, 10, 50); TransI(ref C, D, A, B, 14, 15, 51); TransI(ref B, C, D, A, 5, 21, 52);
TransI(ref A, B, C, D, 12, 6, 53); TransI(ref D, A, B, C, 3, 10, 54); TransI(ref C, D, A, B, 10, 15, 55); TransI(ref B, C, D, A, 1, 21, 56);
TransI(ref A, B, C, D, 8, 6, 57); TransI(ref D, A, B, C, 15, 10, 58); TransI(ref C, D, A, B, 6, 15, 59); TransI(ref B, C, D, A, 13, 21, 60);
TransI(ref A, B, C, D, 4, 6, 61); TransI(ref D, A, B, C, 11, 10, 62); TransI(ref C, D, A, B, 2, 15, 63); TransI(ref B, C, D, A, 9, 21, 64);
A = A + AA;
B = B + BB;
C = C + CC;
D = D + DD;
}
/// <summary>
/// Create Padded buffer for processing , buffer is padded with 0 along
/// with the size in the end
/// </summary>
/// <returns>the padded buffer as byte array</returns>
internal static byte[] CreatePaddedBuffer()
{
uint pad; //no of padding bits for 448 mod 512
byte[] bMsg; //buffer to hold bits
ulong sizeMsg; //64 bit size pad
uint sizeMsgBuff; //buffer size in multiple of bytes
int temp = (448 - ((m_byteInput.Length * 8) % 512)); //temporary
pad = (uint)((temp + 512) % 512); //getting no of bits to be pad
if (pad == 0) ///pad is in bits
pad = 512; //at least 1 or max 512 can be added
sizeMsgBuff = (uint)((m_byteInput.Length) + (pad / 8) + 8);
sizeMsg = (ulong)m_byteInput.Length * 8;
bMsg = new byte[sizeMsgBuff]; ///no need to pad with 0 coz new bytes
// are already initialize to 0 :)
////copying string to buffer
for (int i = 0; i < m_byteInput.Length; i++)
bMsg[i] = m_byteInput[i];
bMsg[m_byteInput.Length] |= 0x80; ///making first bit of padding 1,
//wrting the size value
for (int i = 8; i > 0; i--)
bMsg[sizeMsgBuff - i] = (byte)(sizeMsg >> ((8 - i) * 8) & 0x00000000000000ff);
return bMsg;
}
/// <summary>
/// Copies a 512 bit block into X as 16 32 bit words
/// </summary>
/// <param name="bMsg"> source buffer</param>
/// <param name="block">no of block to copy starting from 0</param>
internal static void CopyBlock(byte[] bMsg, uint block)
{
block = block << 6;
for (uint j = 0; j < 61; j += 4)
{
X[j >> 2] = (((uint)bMsg[block + (j + 3)]) << 24) |
(((uint)bMsg[block + (j + 2)]) << 16) |
(((uint)bMsg[block + (j + 1)]) << 8) |
(((uint)bMsg[block + (j)]));
}
}
}
internal class Digest
{
public uint A;
public uint B;
public uint C;
public uint D;
public Digest()
{
A = 0x67452301;
B = 0xEFCDAB89;
C = 0x98BADCFE;
D = 0X10325476;
}
public override string ToString()
{
string st;
st = ToHexString(MD5Helper.ReverseByte(A), 32) +
ToHexString(MD5Helper.ReverseByte(B), 32) +
ToHexString(MD5Helper.ReverseByte(C), 32) +
ToHexString(MD5Helper.ReverseByte(D), 32);
return st;
}
internal string ToHexString(uint aNumber, byte aBits)
{
uint xValue = aNumber;
byte xCurrentBits = aBits;
string overall = "";
while (xCurrentBits >= 4)
{
xCurrentBits -= 4;
byte xCurrentDigit = (byte)((xValue >> xCurrentBits) & 0xF);
string xDigitString = null;
switch (xCurrentDigit)
{
case 0:
xDigitString = "0";
goto default;
case 1:
xDigitString = "1";
goto default;
case 2:
xDigitString = "2";
goto default;
case 3:
xDigitString = "3";
goto default;
case 4:
xDigitString = "4";
goto default;
case 5:
xDigitString = "5";
goto default;
case 6:
xDigitString = "6";
goto default;
case 7:
xDigitString = "7";
goto default;
case 8:
xDigitString = "8";
goto default;
case 9:
xDigitString = "9";
goto default;
case 10:
xDigitString = "A";
goto default;
case 11:
xDigitString = "B";
goto default;
case 12:
xDigitString = "C";
goto default;
case 13:
xDigitString = "D";
goto default;
case 14:
xDigitString = "E";
goto default;
case 15:
xDigitString = "F";
goto default;
default:
if (xDigitString == null) { }
overall += xDigitString;
break;
}
}
return overall;
}
}
internal class MD5Helper
{
internal MD5Helper() { }
public static uint RotateLeft(uint uiNumber, ushort shift)
{
return ((uiNumber >> 32 - shift) | (uiNumber << shift));
}
public static uint ReverseByte(uint uiNumber)
{
return (((uiNumber & 0x000000ff) << 24) |
(uiNumber >> 24) |
((uiNumber & 0x00ff0000) >> 8) |
((uiNumber & 0x0000ff00) << 8));
}
}
}
| |
using UnityEngine;
using UnityEngine.Serialization;
using System.Collections;
using System.Collections.Generic;
namespace UMA
{
/// <summary>
/// Slot data contains mesh information and overlay references.
/// </summary>
[System.Serializable]
#if !UMA2_LEAN_AND_CLEAN
public partial class SlotData : System.IEquatable<SlotData>
#else
public class SlotData : System.IEquatable<SlotData>, ISerializationCallbackReceiver
#endif
{
/// <summary>
/// The asset contains the immutable portions of the slot.
/// </summary>
public SlotDataAsset asset;
/// <summary>
/// Adjusts the resolution of slot overlays.
/// </summary>
public float overlayScale = 1.0f;
#if UMA2_LEAN_AND_CLEAN
public string slotName { get { return asset.slotName; } }
#endif
/// <summary>
/// list of overlays used to texture the slot.
/// </summary>
private List<OverlayData> overlayList = new List<OverlayData>();
/// <summary>
/// Constructor for slot using the given asset.
/// </summary>
/// <param name="asset">Asset.</param>
public SlotData(SlotDataAsset asset)
{
this.asset = asset;
#if !UMA2_LEAN_AND_CLEAN
#pragma warning disable 618
slotName = asset.slotName;
materialSample = asset.materialSample;
#pragma warning restore 618
#endif
overlayScale = asset.overlayScale;
}
/// <summary>
/// Deep copy of the SlotData.
/// </summary>
public SlotData Copy()
{
var res = new SlotData(asset);
int overlayCount = overlayList.Count;
res.overlayList = new List<OverlayData>(overlayCount);
for (int i = 0; i < overlayCount; i++)
{
OverlayData overlay = overlayList[i];
if (overlay != null)
{
res.overlayList.Add(overlay.Duplicate());
}
}
return res;
}
public int GetTextureChannelCount(UMAGeneratorBase generator)
{
return asset.GetTextureChannelCount(generator);
}
public bool RemoveOverlay(params string[] names)
{
bool changed = false;
foreach (var name in names)
{
for (int i = 0; i < overlayList.Count; i++)
{
if (overlayList[i].asset.overlayName == name)
{
overlayList.RemoveAt(i);
changed = true;
break;
}
}
}
return changed;
}
public bool SetOverlayColor(Color32 color, params string[] names)
{
bool changed = false;
foreach (var name in names)
{
foreach (var overlay in overlayList)
{
if (overlay.asset.overlayName == name)
{
overlay.colorData.color = color;
changed = true;
}
}
}
return changed;
}
public OverlayData GetOverlay(params string[] names)
{
foreach (var name in names)
{
foreach (var overlay in overlayList)
{
if (overlay.asset.overlayName == name)
{
return overlay;
}
}
}
return null;
}
public void SetOverlay(int index, OverlayData overlay)
{
if (index >= overlayList.Count)
{
overlayList.Capacity = index + 1;
while (index >= overlayList.Count)
{
overlayList.Add(null);
}
}
overlayList[index] = overlay;
}
public OverlayData GetOverlay(int index)
{
if (index < 0 || index >= overlayList.Count)
return null;
return overlayList[index];
}
/// <summary>
/// Attempts to find an equivalent overlay in the slot.
/// </summary>
/// <returns>The equivalent overlay (or null, if no equivalent).</returns>
/// <param name="overlay">Overlay.</param>
public OverlayData GetEquivalentOverlay(OverlayData overlay)
{
foreach (OverlayData overlay2 in overlayList)
{
if (OverlayData.Equivalent(overlay, overlay2))
{
return overlay2;
}
}
return null;
}
public int OverlayCount { get { return overlayList.Count; } }
/// <summary>
/// Sets the complete list of overlays.
/// </summary>
/// <param name="overlayList">The overlay list.</param>
public void SetOverlayList(List<OverlayData> overlayList)
{
this.overlayList = overlayList;
}
/// <summary>
/// Add an overlay to the slot.
/// </summary>
/// <param name="overlayData">Overlay.</param>
public void AddOverlay(OverlayData overlayData)
{
if (overlayData)
overlayList.Add(overlayData);
}
/// <summary>
/// Gets the complete list of overlays.
/// </summary>
/// <returns>The overlay list.</returns>
public List<OverlayData> GetOverlayList()
{
return overlayList;
}
internal bool Validate()
{
bool valid = true;
if (asset.meshData != null)
{
if (asset.material == null)
{
Debug.LogError(string.Format("Slot '{0}' has a mesh but no material.", asset.slotName), asset);
valid = false;
}
else
{
if (asset.material.material == null)
{
Debug.LogError(string.Format("Slot '{0}' has an umaMaterial without a material assigned.", asset.slotName), asset);
valid = false;
}
else
{
for (int i = 0; i < asset.material.channels.Length; i++)
{
var channel = asset.material.channels[i];
if (!asset.material.material.HasProperty(channel.materialPropertyName))
{
Debug.LogError(string.Format("Slot '{0}' Material Channel {1} refers to material property '{2}' but no such property exists.", asset.slotName, i, channel.materialPropertyName), asset);
valid = false;
}
}
}
}
for (int i = 0; i < overlayList.Count; i++)
{
var overlayData = overlayList[i];
if (overlayData != null)
{
if (overlayData.asset.material != asset.material)
{
if (!overlayData.asset.material.Equals(asset.material))
{
Debug.LogError(string.Format("Slot '{0}' and Overlay '{1}' don't have the same UMA Material", asset.slotName, overlayData.asset.overlayName));
valid = false;
}
}
if ((overlayData.asset.textureList == null) || (overlayData.asset.textureList.Length != asset.material.channels.Length))
{
Debug.LogError(string.Format("Overlay '{0}' doesn't have the right number of channels", overlayData.asset.overlayName));
valid = false;
}
else
{
for (int j = 0; j < asset.material.channels.Length; j++)
{
if ((overlayData.asset.textureList[j] == null) && (asset.material.channels[j].channelType != UMAMaterial.ChannelType.MaterialColor))
{
Debug.LogError(string.Format("Overlay '{0}' missing required texture in channel {1}", overlayData.asset.overlayName, j));
valid = false;
}
}
}
if (overlayData.colorData.channelMask.Length < asset.material.channels.Length)
{
// Fixup colorData if moving from Legacy to PBR materials
int oldsize = overlayData.colorData.channelMask.Length;
System.Array.Resize(ref overlayData.colorData.channelMask, asset.material.channels.Length);
System.Array.Resize(ref overlayData.colorData.channelAdditiveMask, asset.material.channels.Length);
for (int j = oldsize; j > asset.material.channels.Length; j++)
{
overlayData.colorData.channelMask[j] = Color.white;
overlayData.colorData.channelAdditiveMask[j] = Color.black;
}
Debug.LogWarning(string.Format("Overlay '{0}' missing required color data on Asset: " + asset.name + " Resizing and adding defaults", overlayData.asset.overlayName));
}
}
}
}
else
{
#if !UMA2_LEAN_AND_CLEAN
if (asset.meshRenderer != null)
{
Debug.LogError(string.Format("Slot '{0}' is a UMA 1x slot... you need to upgrade it by selecting it and using the UMA|Optimize Slot Meshes.", asset.slotName), asset);
valid = false;
}
#endif
if (asset.material != null)
{
for (int i = 0; i < asset.material.channels.Length; i++)
{
var channel = asset.material.channels[i];
if (!asset.material.material.HasProperty(channel.materialPropertyName))
{
Debug.LogError(string.Format("Slot '{0}' Material Channel {1} refers to material property '{2}' but no such property exists.", asset.slotName, i, channel.materialPropertyName), asset);
valid = false;
}
}
}
}
return valid;
}
public override string ToString()
{
return "SlotData: " + asset.slotName;
}
#if !UMA2_LEAN_AND_CLEAN
#region obsolete junk from version 1
[System.Obsolete("SlotData.materialSample is obsolete use asset.materialSample!", false)]
public Material materialSample;
[System.Obsolete("SlotData.slotName is obsolete use asset.slotName!", false)]
public string slotName;
[System.Obsolete("SlotData.listID is obsolete.", false)]
public int listID = -1;
[System.Obsolete("SlotData.meshRenderer is obsolete.", true)]
public SkinnedMeshRenderer meshRenderer;
[System.Obsolete("SlotData.boneNameHashes is obsolete.", true)]
public int[] boneNameHashes;
[System.Obsolete("SlotData.boneWeights is obsolete.", true)]
public BoneWeight[] boneWeights;
[System.Obsolete("SlotData.umaBoneData is obsolete.", true)]
public Transform[] umaBoneData;
[System.Obsolete("SlotData.animatedBones is obsolete, use SlotDataAsset.animatedBones.", true)]
public Transform[] animatedBones = new Transform[0];
[System.Obsolete("SlotData.textureNameList is obsolete, use SlotDataAsset.textureNameList.", true)]
public string[] textureNameList;
[System.Obsolete("SlotData.slotDNA is obsolete, use SlotDataAsset.slotDNA.", true)]
public DnaConverterBehaviour slotDNA;
[System.Obsolete("SlotData.subMeshIndex is obsolete, use SlotDataAsset.subMeshIndex.", true)]
public int subMeshIndex;
/// <summary>
/// Use this to identify slots that serves the same purpose
/// Eg. ChestArmor, Helmet, etc.
/// </summary>
[System.Obsolete("SlotData.slotGroup is obsolete, use SlotDataAsset.slotGroup.", false)]
public string slotGroup;
/// <summary>
/// Use this to identify what kind of overlays fit this slotData
/// Eg. BaseMeshSkin, BaseMeshOverlays, GenericPlateArmor01
/// </summary>
[System.Obsolete("SlotData.tags is obsolete, use SlotDataAsset.tags.", false)]
public string[] tags;
#endregion
#endif
#region operator ==, != and similar HACKS, seriously.....
[System.Obsolete("You can no longer cast UnityEngine.Object to SlotData, perhaps you want to cast it into SlotDataAsset instead?", false)]
public static implicit operator SlotData(UnityEngine.Object obj)
{
throw new System.NotImplementedException("You can no longer cast UnityEngine.Object to SlotData, perhaps you want to cast it into SlotDataAsset instead?");
}
public static implicit operator bool (SlotData obj)
{
return ((System.Object)obj) != null && obj.asset != null;
}
public bool Equals(SlotData other)
{
return (this == other);
}
public override bool Equals(object other)
{
return Equals(other as SlotData);
}
public static bool operator ==(SlotData slot, SlotData obj)
{
if (slot)
{
if (obj)
{
return System.Object.ReferenceEquals(slot, obj);
}
return false;
}
return !((bool)obj);
}
public static bool operator !=(SlotData slot, SlotData obj)
{
if (slot)
{
if (obj)
{
return !System.Object.ReferenceEquals(slot, obj);
}
return true;
}
return ((bool)obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
#region ISerializationCallbackReceiver Members
public void OnAfterDeserialize()
{
if (overlayList == null) overlayList = new List<OverlayData>();
}
public void OnBeforeSerialize()
{
}
#endregion
}
}
| |
/***************************************************************************
* IpodDap.cs
*
* Copyright (C) 2005-2007 Novell, Inc.
* Written by Aaron Bockvoer <abockover@novell.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using Mono.Unix;
using Gtk;
using Hal;
using IPod;
using Banshee.Base;
using Banshee.Dap;
using Banshee.Widgets;
using Banshee.Metadata;
public static class PluginModuleEntry
{
public static Type [] GetTypes()
{
return new Type [] {
typeof(Banshee.Dap.Ipod.IpodDap)
};
}
}
namespace Banshee.Dap.Ipod
{
[DapProperties(DapType = DapType.NonGeneric, PipelineName="Ipod")]
[SupportedCodec(CodecType.Mp3)]
[SupportedCodec(CodecType.Mp4)]
public sealed class IpodDap : DapDevice
{
private IPod.Device device;
private Hal.Device hal_device;
private bool database_supported;
private UnsupportedDatabaseView db_unsupported_container;
private bool metadata_provider_initialized = false;
public override InitializeResult Initialize(Hal.Device halDevice)
{
if (!metadata_provider_initialized) {
MetadataService.Instance.AddProvider (0, new IpodMetadataProvider ());
metadata_provider_initialized = true;
}
hal_device = halDevice;
if(!hal_device.PropertyExists("block.device") ||
!hal_device.PropertyExists("block.is_volume") ||
!hal_device.GetPropertyBoolean("block.is_volume") ||
hal_device.Parent["portable_audio_player.type"] != "ipod") {
return InitializeResult.Invalid;
} else if(!hal_device.GetPropertyBoolean("volume.is_mounted")) {
return WaitForVolumeMount(hal_device);
}
if(LoadIpod() == InitializeResult.Invalid) {
return InitializeResult.Invalid;
}
base.Initialize(halDevice);
InstallProperty("Generation", device.Generation.ToString());
InstallProperty("Model", device.Model.ToString());
InstallProperty("Model Number", device.ModelNumber);
InstallProperty("Serial Number", device.SerialNumber);
InstallProperty("Firmware Version", device.FirmwareVersion);
InstallProperty("Database Version", device.TrackDatabase.Version.ToString());
if(device.ProductionYear > 0) {
// Translators "Week 25 of 2006"
InstallProperty(Catalog.GetString("Manufactured During"),
String.Format(Catalog.GetString("Week {0} of {1}"), device.ProductionWeek,
device.ProductionYear.ToString("0000")));
}
if(device.ShouldAskIfUnknown) {
GLib.Timeout.Add(5000, AskAboutUnknown);
}
ReloadDatabase(false);
CanCancelSave = false;
return InitializeResult.Valid;
}
private InitializeResult LoadIpod()
{
try {
device = new IPod.Device(hal_device["block.device"]);
if(File.Exists(Path.Combine(device.ControlPath, Path.Combine("iTunes", "iTunesDB")))) {
device.LoadTrackDatabase();
} else {
throw new DatabaseReadException("iTunesDB does not exist");
}
database_supported = true;
} catch(DatabaseReadException) {
device.LoadTrackDatabase(true);
database_supported = false;
} catch {
return InitializeResult.Invalid;
}
return InitializeResult.Valid;
}
private bool AskAboutUnknown()
{
HigMessageDialog dialog = new HigMessageDialog(null, Gtk.DialogFlags.Modal,
Gtk.MessageType.Warning, Gtk.ButtonsType.None,
Catalog.GetString("Your iPod could not be identified"),
Catalog.GetString("Please consider submitting information about your iPod " +
"to the Banshee Project so your iPod may be more fully identified in the future.\n"));
CheckButton do_not_ask = new CheckButton(Catalog.GetString("Do not ask me again"));
do_not_ask.Show();
dialog.LabelVBox.PackStart(do_not_ask, false, false, 0);
dialog.AddButton("gtk-cancel", Gtk.ResponseType.Cancel, false);
dialog.AddButton(Catalog.GetString("Go to Web Site"), Gtk.ResponseType.Ok, false);
try {
if(dialog.Run() == (int)ResponseType.Ok) {
do_not_ask.Active = true;
Banshee.Web.Browser.Open(device.UnknownIpodUrl);
}
} finally {
dialog.Destroy();
}
if(do_not_ask.Active) {
device.DoNotAskIfUnknown();
}
return false;
}
public override void AddTrack(TrackInfo track)
{
if (track == null || IsReadOnly)
return;
TrackInfo new_track = null;
if(track is IpodDapTrackInfo)
new_track = track;
else
new_track = new IpodDapTrackInfo(track, device.TrackDatabase);
// FIXME: only add a new track if we don't have it already
if (new_track != null) {
tracks.Add(new_track);
OnTrackAdded(new_track);
}
}
protected override void OnTrackRemoved(TrackInfo track)
{
if(!(track is IpodDapTrackInfo)) {
return;
}
try {
IpodDapTrackInfo ipod_track = (IpodDapTrackInfo)track;
device.TrackDatabase.RemoveTrack(ipod_track.Track);
} catch(Exception) {
}
}
private void ReloadDatabase(bool refresh)
{
bool previous_database_supported = database_supported;
ClearTracks(false);
if(refresh) {
device.TrackDatabase.Reload();
}
if(database_supported) {
foreach(Track track in device.TrackDatabase.Tracks) {
IpodDapTrackInfo ti = new IpodDapTrackInfo(track);
AddTrack(ti);
}
} else {
BuildDatabaseUnsupportedWidget();
}
if(previous_database_supported != database_supported) {
OnPropertiesChanged();
}
}
public override void Eject()
{
try {
device.Eject();
base.Eject();
} catch(Exception e) {
LogCore.Instance.PushError(Catalog.GetString("Could not eject iPod"),
e.Message);
}
}
public override void Synchronize()
{
UpdateSaveProgress(
Catalog.GetString("Synchronizing iPod"),
Catalog.GetString("Pre-processing tracks"),
0.0);
foreach(IpodDapTrackInfo track in Tracks) {
if(track.Track == null) {
CommitTrackToDevice(track);
} else {
track.Track.Uri = new Uri(track.Uri.AbsoluteUri);
}
}
device.TrackDatabase.SaveProgressChanged += delegate(object o, TrackSaveProgressArgs args)
{
double progress = args.CurrentTrack == null ? 0.0 : args.TotalProgress;
string message = args.CurrentTrack == null
? Catalog.GetString("Flushing to Disk (may take time)")
: args.CurrentTrack.Artist + " - " + args.CurrentTrack.Title;
UpdateSaveProgress(Catalog.GetString("Synchronizing iPod"), message, progress);
};
try {
device.TrackDatabase.Save();
} catch(Exception e) {
Console.Error.WriteLine (e);
LogCore.Instance.PushError(Catalog.GetString("Failed to synchronize iPod"), e.Message);
} finally {
ReloadDatabase(true);
FinishSave();
}
}
private void CommitTrackToDevice(IpodDapTrackInfo ti)
{
Track track = device.TrackDatabase.CreateTrack();
try {
track.Uri = new Uri(ti.Uri.AbsoluteUri);
} catch {
device.TrackDatabase.RemoveTrack (track);
return;
}
if(ti.Album != null) {
track.Album = ti.Album;
}
if(ti.Artist != null) {
track.Artist = ti.Artist;
}
if(ti.Title != null) {
track.Title = ti.Title;
}
if(ti.Genre != null) {
track.Genre = ti.Genre;
}
track.Duration = ti.Duration;
track.TrackNumber = (int)ti.TrackNumber;
track.TotalTracks = (int)ti.TrackCount;
track.Year = (int)ti.Year;
track.LastPlayed = ti.LastPlayed;
switch(ti.Rating) {
case 1: track.Rating = TrackRating.Zero; break;
case 2: track.Rating = TrackRating.Two; break;
case 3: track.Rating = TrackRating.Three; break;
case 4: track.Rating = TrackRating.Four; break;
case 5: track.Rating = TrackRating.Five; break;
default: track.Rating = TrackRating.Zero; break;
}
if(track.Artist == null) {
track.Artist = String.Empty;
}
if(track.Album == null) {
track.Album = String.Empty;
}
if(track.Title == null) {
track.Title = String.Empty;
}
if(track.Genre == null) {
track.Genre = String.Empty;
}
if (ti.CoverArtFileName != null && File.Exists (ti.CoverArtFileName)) {
try {
Gdk.Pixbuf pixbuf = new Gdk.Pixbuf (ti.CoverArtFileName);
if (pixbuf != null) {
SetCoverArt (track, ArtworkUsage.Cover, pixbuf);
pixbuf.Dispose ();
}
} catch (Exception e) {
Console.Error.WriteLine ("Failed to set cover art from {0}: {1}", ti.CoverArtFileName, e);
}
}
}
private void SetCoverArt (Track track, ArtworkUsage usage, Gdk.Pixbuf pixbuf)
{
foreach (ArtworkFormat format in device.LookupArtworkFormats (usage)) {
if (!track.HasCoverArt (format)) {
track.SetCoverArt (format, ArtworkHelpers.ToBytes (format, pixbuf));
}
}
}
public override Gdk.Pixbuf GetIcon(int size)
{
string prefix = "multimedia-player-";
string id = null;
switch(device.Model) {
case DeviceModel.Color: id = "ipod-standard-color"; break;
case DeviceModel.ColorU2: id = "ipod-U2-color"; break;
case DeviceModel.Regular: id = "ipod-standard-monochrome"; break;
case DeviceModel.RegularU2: id = "ipod-U2-monochrome"; break;
case DeviceModel.Mini: id = "ipod-mini-silver"; break;
case DeviceModel.MiniBlue: id = "ipod-mini-blue"; break;
case DeviceModel.MiniPink: id = "ipod-mini-pink"; break;
case DeviceModel.MiniGreen: id = "ipod-mini-green"; break;
case DeviceModel.MiniGold: id = "ipod-mini-gold"; break;
case DeviceModel.Shuffle: id = "ipod-shuffle"; break;
case DeviceModel.NanoWhite: id = "ipod-nano-white"; break;
case DeviceModel.NanoBlack: id = "ipod-nano-black"; break;
case DeviceModel.VideoWhite: id = "ipod-video-white"; break;
case DeviceModel.VideoBlack: id = "ipod-video-black"; break;
default:
id = "ipod-standard-monochrome";
break;
}
Gdk.Pixbuf icon = IconThemeUtils.LoadIcon(prefix + id, size);
if(icon != null) {
return icon;
}
return base.GetIcon(size);
}
public override void SetName(string name)
{
device.Name = name;
device.Save();
}
public override void SetOwner(string owner)
{
device.UserName = owner;
device.Save();
}
private void BuildDatabaseUnsupportedWidget()
{
db_unsupported_container = new UnsupportedDatabaseView(this);
db_unsupported_container.Show();
db_unsupported_container.Refresh += delegate(object o, EventArgs args) {
LoadIpod();
ReloadDatabase(false);
OnReactivate();
};
}
public override string Name {
get {
if(device.Name != null && device.Name != String.Empty) {
return device.Name;
} else if(hal_device.PropertyExists("volume.label")) {
return hal_device["volume.label"];
} else if(hal_device.PropertyExists("info.product")) {
return hal_device["info.product"];
}
return "iPod";
}
}
public override string Owner {
get {
return device.UserName;
}
}
public override ulong StorageCapacity {
get {
return device.VolumeSize;
}
}
public override ulong StorageUsed {
get {
return device.VolumeUsed;
}
}
public override bool IsReadOnly {
get {
return !device.CanWrite;
}
}
public override bool IsPlaybackSupported {
get {
return true;
}
}
public override string GenericName {
get {
return "iPod";
}
}
public override Gtk.Widget ViewWidget {
get {
return !database_supported ? db_unsupported_container : null;
}
}
internal IPod.Device Device {
get {
return device;
}
}
}
}
| |
// 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.
/*============================================================
**
** Class: Privilege
**
** Purpose: Managed wrapper for NT privileges.
**
** Date: July 1, 2004
**
===========================================================*/
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
using FCall = System.Security.Principal.Win32;
using Luid = Interop.mincore.LUID;
namespace System.Security.AccessControl
{
#if false
internal delegate void PrivilegedHelper();
#endif
internal sealed class Privilege
{
[ThreadStatic]
private static TlsContents tlsSlotData;
private static Dictionary<Luid, string> privileges = new Dictionary<Luid, string>();
private static Dictionary<string, Luid> luids = new Dictionary<string, Luid>();
private static ReaderWriterLockSlim privilegeLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
private bool needToRevert = false;
private bool initialState = false;
private bool stateWasChanged = false;
private Luid luid;
private readonly Thread currentThread = Thread.CurrentThread;
private TlsContents tlsContents = null;
public const string CreateToken = "SeCreateTokenPrivilege";
public const string AssignPrimaryToken = "SeAssignPrimaryTokenPrivilege";
public const string LockMemory = "SeLockMemoryPrivilege";
public const string IncreaseQuota = "SeIncreaseQuotaPrivilege";
public const string UnsolicitedInput = "SeUnsolicitedInputPrivilege";
public const string MachineAccount = "SeMachineAccountPrivilege";
public const string TrustedComputingBase = "SeTcbPrivilege";
public const string Security = "SeSecurityPrivilege";
public const string TakeOwnership = "SeTakeOwnershipPrivilege";
public const string LoadDriver = "SeLoadDriverPrivilege";
public const string SystemProfile = "SeSystemProfilePrivilege";
public const string SystemTime = "SeSystemtimePrivilege";
public const string ProfileSingleProcess = "SeProfileSingleProcessPrivilege";
public const string IncreaseBasePriority = "SeIncreaseBasePriorityPrivilege";
public const string CreatePageFile = "SeCreatePagefilePrivilege";
public const string CreatePermanent = "SeCreatePermanentPrivilege";
public const string Backup = "SeBackupPrivilege";
public const string Restore = "SeRestorePrivilege";
public const string Shutdown = "SeShutdownPrivilege";
public const string Debug = "SeDebugPrivilege";
public const string Audit = "SeAuditPrivilege";
public const string SystemEnvironment = "SeSystemEnvironmentPrivilege";
public const string ChangeNotify = "SeChangeNotifyPrivilege";
public const string RemoteShutdown = "SeRemoteShutdownPrivilege";
public const string Undock = "SeUndockPrivilege";
public const string SyncAgent = "SeSyncAgentPrivilege";
public const string EnableDelegation = "SeEnableDelegationPrivilege";
public const string ManageVolume = "SeManageVolumePrivilege";
public const string Impersonate = "SeImpersonatePrivilege";
public const string CreateGlobal = "SeCreateGlobalPrivilege";
public const string TrustedCredentialManagerAccess = "SeTrustedCredManAccessPrivilege";
public const string ReserveProcessor = "SeReserveProcessorPrivilege";
//
// This routine is a wrapper around a hashtable containing mappings
// of privilege names to LUIDs
//
private static Luid LuidFromPrivilege(string privilege)
{
Luid luid;
luid.LowPart = 0;
luid.HighPart = 0;
//
// Look up the privilege LUID inside the cache
//
try
{
privilegeLock.EnterReadLock();
if (luids.ContainsKey(privilege))
{
luid = luids[privilege];
privilegeLock.ExitReadLock();
}
else
{
privilegeLock.ExitReadLock();
if (false == Interop.mincore.LookupPrivilegeValue(null, privilege, out luid))
{
int error = Marshal.GetLastWin32Error();
if (error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (error == Interop.mincore.Errors.ERROR_NO_SUCH_PRIVILEGE)
{
throw new ArgumentException(
SR.Format(SR.Argument_InvalidPrivilegeName,
privilege));
}
else
{
Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "LookupPrivilegeValue() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}
privilegeLock.EnterWriteLock();
}
}
finally
{
if (privilegeLock.IsReadLockHeld)
{
privilegeLock.ExitReadLock();
}
if (privilegeLock.IsWriteLockHeld)
{
if (!luids.ContainsKey(privilege))
{
luids[privilege] = luid;
privileges[luid] = privilege;
}
privilegeLock.ExitWriteLock();
}
}
return luid;
}
private sealed class TlsContents : IDisposable
{
private bool disposed = false;
private int referenceCount = 1;
private SafeTokenHandle threadHandle = new SafeTokenHandle(IntPtr.Zero);
private bool isImpersonating = false;
private static volatile SafeTokenHandle processHandle = new SafeTokenHandle(IntPtr.Zero);
private static readonly object syncRoot = new object();
#region Constructor and Finalizer
static TlsContents()
{
}
public TlsContents()
{
int error = 0;
int cachingError = 0;
bool success = true;
if (processHandle.IsInvalid)
{
lock (syncRoot)
{
if (processHandle.IsInvalid)
{
SafeTokenHandle localProcessHandle;
if (false == Interop.mincore.OpenProcessToken(
Interop.mincore.GetCurrentProcess(),
TokenAccessLevels.Duplicate,
out localProcessHandle))
{
cachingError = Marshal.GetLastWin32Error();
success = false;
}
processHandle = localProcessHandle;
}
}
}
try
{
// Make the sequence non-interruptible
}
finally
{
try
{
//
// Open the thread token; if there is no thread token, get one from
// the process token by impersonating self.
//
SafeTokenHandle threadHandleBefore = this.threadHandle;
error = FCall.OpenThreadToken(
TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
WinSecurityContext.Process,
out this.threadHandle);
unchecked { error &= ~(int)0x80070000; }
if (error != 0)
{
if (success == true)
{
this.threadHandle = threadHandleBefore;
if (error != Interop.mincore.Errors.ERROR_NO_TOKEN)
{
success = false;
}
Contract.Assert(this.isImpersonating == false, "Incorrect isImpersonating state");
if (success == true)
{
error = 0;
if (false == Interop.mincore.DuplicateTokenEx(
processHandle,
TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
IntPtr.Zero,
Interop.mincore.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
System.Security.Principal.TokenType.TokenImpersonation,
ref this.threadHandle))
{
error = Marshal.GetLastWin32Error();
success = false;
}
}
if (success == true)
{
error = FCall.SetThreadToken(this.threadHandle);
unchecked { error &= ~(int)0x80070000; }
if (error != 0)
{
success = false;
}
}
if (success == true)
{
this.isImpersonating = true;
}
}
else
{
error = cachingError;
}
}
else
{
success = true;
}
}
finally
{
if (!success)
{
Dispose();
}
}
}
if (error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
error == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}
~TlsContents()
{
if (!this.disposed)
{
Dispose(false);
}
}
#endregion
#region IDisposable implementation
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (this.disposed) return;
if (disposing)
{
if (this.threadHandle != null)
{
this.threadHandle.Dispose();
this.threadHandle = null;
}
}
if (this.isImpersonating)
{
Interop.mincore.RevertToSelf();
}
this.disposed = true;
}
#endregion
#region Reference Counting
public void IncrementReferenceCount()
{
this.referenceCount++;
}
public int DecrementReferenceCount()
{
int result = --this.referenceCount;
if (result == 0)
{
Dispose();
}
return result;
}
public int ReferenceCountValue
{
get { return this.referenceCount; }
}
#endregion
#region Properties
public SafeTokenHandle ThreadHandle
{
[System.Security.SecurityCritical] // auto-generated
get
{ return this.threadHandle; }
}
public bool IsImpersonating
{
get { return this.isImpersonating; }
}
#endregion
}
#region Constructors
public Privilege(string privilegeName)
{
if (privilegeName == null)
{
throw new ArgumentNullException("privilegeName");
}
Contract.EndContractBlock();
this.luid = LuidFromPrivilege(privilegeName);
}
#endregion
//
// Finalizer simply ensures that the privilege was not leaked
//
~Privilege()
{
Contract.Assert(!this.needToRevert, "Must revert privileges that you alter!");
if (this.needToRevert)
{
Revert();
}
}
#region Public interface
public void Enable()
{
this.ToggleState(true);
}
public bool NeedToRevert
{
get { return this.needToRevert; }
}
#endregion
// [SecurityPermission( SecurityAction.Demand, TogglePrivileges=true )]
private void ToggleState(bool enable)
{
int error = 0;
//
// All privilege operations must take place on the same thread
//
if (!this.currentThread.Equals(Thread.CurrentThread))
{
throw new InvalidOperationException(SR.InvalidOperation_MustBeSameThread);
}
//
// This privilege was already altered and needs to be reverted before it can be altered again
//
if (this.needToRevert)
{
throw new InvalidOperationException(SR.InvalidOperation_MustRevertPrivilege);
}
//
// Need to make this block of code non-interruptible so that it would preserve
// consistency of thread oken state even in the face of catastrophic exceptions
//
try
{
//
// The payload is entirely in the finally block
// This is how we ensure that the code will not be
// interrupted by catastrophic exceptions
//
}
finally
{
try
{
//
// Retrieve TLS state
//
this.tlsContents = tlsSlotData;
if (this.tlsContents == null)
{
this.tlsContents = new TlsContents();
tlsSlotData = this.tlsContents;
}
else
{
this.tlsContents.IncrementReferenceCount();
}
Interop.mincore.LUID_AND_ATTRIBUTES luidAndAttrs = new Interop.mincore.LUID_AND_ATTRIBUTES();
luidAndAttrs.Luid = this.luid;
luidAndAttrs.Attributes = enable ? Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.mincore.SEPrivileges.SE_PRIVILEGE_DISABLED;
Interop.mincore.TOKEN_PRIVILEGE newState = new Interop.mincore.TOKEN_PRIVILEGE();
newState.PrivilegeCount = 1;
newState.Privileges[0] = luidAndAttrs;
Interop.mincore.TOKEN_PRIVILEGE previousState = new Interop.mincore.TOKEN_PRIVILEGE();
uint previousSize = 0;
//
// Place the new privilege on the thread token and remember the previous state.
//
if (false == Interop.mincore.AdjustTokenPrivileges(
this.tlsContents.ThreadHandle,
false,
ref newState,
(uint)Marshal.SizeOf(previousState),
ref previousState,
ref previousSize))
{
error = Marshal.GetLastWin32Error();
}
else if (Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED == Marshal.GetLastWin32Error())
{
error = Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED;
}
else
{
//
// This is the initial state that revert will have to go back to
//
this.initialState = ((previousState.Privileges[0].Attributes & Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED) != 0);
//
// Remember whether state has changed at all
//
this.stateWasChanged = (this.initialState != enable);
//
// If we had to impersonate, or if the privilege state changed we'll need to revert
//
this.needToRevert = this.tlsContents.IsImpersonating || this.stateWasChanged;
}
}
finally
{
if (!this.needToRevert)
{
this.Reset();
}
}
}
if (error == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED)
{
throw new PrivilegeNotHeldException(privileges[this.luid]);
}
if (error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
error == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "AdjustTokenPrivileges() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}
// [SecurityPermission( SecurityAction.Demand, TogglePrivileges=true )]
public void Revert()
{
int error = 0;
if (!this.currentThread.Equals(Thread.CurrentThread))
{
throw new InvalidOperationException(SR.InvalidOperation_MustBeSameThread);
}
if (!this.NeedToRevert)
{
return;
}
//
// This code must be eagerly prepared and non-interruptible.
//
try
{
//
// The payload is entirely in the finally block
// This is how we ensure that the code will not be
// interrupted by catastrophic exceptions
//
}
finally
{
bool success = true;
try
{
//
// Only call AdjustTokenPrivileges if we're not going to be reverting to self,
// on this Revert, since doing the latter obliterates the thread token anyway
//
if (this.stateWasChanged &&
(this.tlsContents.ReferenceCountValue > 1 ||
!this.tlsContents.IsImpersonating))
{
Interop.mincore.LUID_AND_ATTRIBUTES luidAndAttrs = new Interop.mincore.LUID_AND_ATTRIBUTES();
luidAndAttrs.Luid = this.luid;
luidAndAttrs.Attributes = (this.initialState ? Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.mincore.SEPrivileges.SE_PRIVILEGE_DISABLED);
Interop.mincore.TOKEN_PRIVILEGE newState = new Interop.mincore.TOKEN_PRIVILEGE();
newState.PrivilegeCount = 1;
newState.Privileges[0] = luidAndAttrs;
Interop.mincore.TOKEN_PRIVILEGE previousState = new Interop.mincore.TOKEN_PRIVILEGE();
uint previousSize = 0;
if (false == Interop.mincore.AdjustTokenPrivileges(
this.tlsContents.ThreadHandle,
false,
ref newState,
(uint)Marshal.SizeOf(previousState),
ref previousState,
ref previousSize))
{
error = Marshal.GetLastWin32Error();
success = false;
}
}
}
finally
{
if (success)
{
this.Reset();
}
}
}
if (error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "AdjustTokenPrivileges() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}
#if false
public static void RunWithPrivilege( string privilege, bool enabled, PrivilegedHelper helper )
{
if ( helper == null )
{
throw new ArgumentNullException( "helper" );
}
Contract.EndContractBlock();
Privilege p = new Privilege( privilege );
try
{
if (enabled)
{
p.Enable();
}
else
{
p.Disable();
}
helper();
}
finally
{
p.Revert();
}
}
#endif
private void Reset()
{
this.stateWasChanged = false;
this.initialState = false;
this.needToRevert = false;
if (this.tlsContents != null)
{
if (0 == this.tlsContents.DecrementReferenceCount())
{
this.tlsContents = null;
tlsSlotData = null;
}
}
}
}
}
| |
using System;
using NUnit.Framework;
using it.unifi.dsi.stlab.math.algebra;
using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance;
using it.unifi.dsi.stlab.networkreasoner.gas.system.dimensional_objects;
namespace it.unifi.dsi.stlab.networkreasoner.gas.system.tests
{
[TestFixture()]
public class RepeatUntilConditionRatioPrecisionReached
{
[Test()]
public void two_vectors_with_identical_entries_should_stop_mutation ()
{
var previousUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
var currentUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
NodeForNetwonRaphsonSystem n1 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n2 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n3 = new NodeForNetwonRaphsonSystem ();
Double v1 = 3.14;
Double v2 = 13.14;
Double v3 = 23.14;
previousUnknowns.atPut (n1, v1);
previousUnknowns.atPut (n2, v2);
previousUnknowns.atPut (n3, v3);
currentUnknowns.atPut (n1, v1);
currentUnknowns.atPut (n2, v2);
currentUnknowns.atPut (n3, v3);
var untilCondition = new UntilConditionAdimensionalRatioPrecisionReached{
Precision = 1e-10
};
var previousUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = previousUnknowns
};
var currentUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = currentUnknowns
};
Assert.IsFalse (untilCondition.canContinue (
new OneStepMutationResults{ Unknowns= previousUnknownsWrapper},
new OneStepMutationResults{ Unknowns= currentUnknownsWrapper})
);
}
[Test()]
public void two_vectors_with_close_entries_should_stop_mutation ()
{
var previousUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
var currentUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
NodeForNetwonRaphsonSystem n1 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n2 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n3 = new NodeForNetwonRaphsonSystem ();
Double precision = 1e-10;
Double epsilon = 1e-11;
Double v1 = 3.14;
Double v2 = 13.14;
Double v3 = 23.14;
previousUnknowns.atPut (n1, v1);
previousUnknowns.atPut (n2, v2);
previousUnknowns.atPut (n3, v3);
currentUnknowns.atPut (n1, v1 + precision - epsilon);
currentUnknowns.atPut (n2, v2 - precision + epsilon);
currentUnknowns.atPut (n3, v3);
var untilCondition = new UntilConditionAdimensionalRatioPrecisionReached{
Precision = precision
};
var previousUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = previousUnknowns
};
var currentUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = currentUnknowns
};
Assert.IsFalse (untilCondition.canContinue (
new OneStepMutationResults{ Unknowns= previousUnknownsWrapper},
new OneStepMutationResults{ Unknowns= currentUnknownsWrapper})
);
}
[Test()]
public void two_vectors_with_entries_differing_on_edge_should_stop_mutation ()
{
var previousUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
var currentUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
NodeForNetwonRaphsonSystem n1 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n2 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n3 = new NodeForNetwonRaphsonSystem ();
Double precision = 1e-10;
Double v1 = 3.14;
Double v2 = 13.14;
Double v3 = 23.14;
previousUnknowns.atPut (n1, v1);
previousUnknowns.atPut (n2, v2);
previousUnknowns.atPut (n3, v3);
currentUnknowns.atPut (n1, v1 + precision);
currentUnknowns.atPut (n2, v2 - precision);
currentUnknowns.atPut (n3, v3);
var untilCondition = new UntilConditionAdimensionalRatioPrecisionReached{
Precision = precision
};
var previousUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = previousUnknowns
};
var currentUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = currentUnknowns
};
Assert.IsFalse (untilCondition.canContinue (
new OneStepMutationResults{ Unknowns= previousUnknownsWrapper},
new OneStepMutationResults{ Unknowns= currentUnknownsWrapper})
);
}
[Test()]
public void second_vector_is_far_from_the_first_should_stop_mutation ()
{
var previousUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
var currentUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
NodeForNetwonRaphsonSystem n1 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n2 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n3 = new NodeForNetwonRaphsonSystem ();
Double precision = 1e-10;
Double v1 = 3.14;
Double v2 = 13.14;
Double v3 = 23.14;
previousUnknowns.atPut (n1, v1);
previousUnknowns.atPut (n2, v2);
previousUnknowns.atPut (n3, v3);
currentUnknowns.atPut (n1, v1 + 4);
currentUnknowns.atPut (n2, v2);
currentUnknowns.atPut (n3, v3);
var untilCondition = new UntilConditionAdimensionalRatioPrecisionReached{
Precision = precision
};
var previousUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = previousUnknowns
};
var currentUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = currentUnknowns
};
Assert.IsTrue (untilCondition.canContinue (
new OneStepMutationResults{ Unknowns= previousUnknownsWrapper},
new OneStepMutationResults{ Unknowns= currentUnknownsWrapper})
);
}
[Test()]
public void first_vector_is_far_from_the_second_should_stop_mutation ()
{
var previousUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
var currentUnknowns = new Vector<NodeForNetwonRaphsonSystem> ();
NodeForNetwonRaphsonSystem n1 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n2 = new NodeForNetwonRaphsonSystem ();
NodeForNetwonRaphsonSystem n3 = new NodeForNetwonRaphsonSystem ();
Double precision = 1e-10;
Double v1 = 3.14;
Double v2 = 13.14;
Double v3 = 23.14;
previousUnknowns.atPut (n1, v1 + 4);
previousUnknowns.atPut (n2, v2);
previousUnknowns.atPut (n3, v3);
currentUnknowns.atPut (n1, v1);
currentUnknowns.atPut (n2, v2);
currentUnknowns.atPut (n3, v3);
var untilCondition = new UntilConditionAdimensionalRatioPrecisionReached{
Precision = precision
};
var previousUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = previousUnknowns
};
var currentUnknownsWrapper = new DimensionalObjectWrapperWithAdimensionalValues<
Vector<NodeForNetwonRaphsonSystem>> {
WrappedObject = currentUnknowns
};
Assert.IsTrue (untilCondition.canContinue (
new OneStepMutationResults{ Unknowns= previousUnknownsWrapper},
new OneStepMutationResults{ Unknowns= currentUnknownsWrapper})
);
}
}
}
| |
#region License
/*
* HttpListenerPrefix.cs
*
* This code is derived from ListenerPrefix.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2020 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
* - Oleg Mihailik <mihailik@gmail.com>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
internal sealed class HttpListenerPrefix
{
#region Private Fields
private string _host;
private HttpListener _listener;
private string _original;
private string _path;
private string _port;
private string _prefix;
private bool _secure;
#endregion
#region Internal Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpListenerPrefix"/> class
/// with the specified URI prefix and HTTP listener.
/// </summary>
/// <remarks>
/// This constructor must be called after calling the CheckPrefix method.
/// </remarks>
/// <param name="uriPrefix">
/// A <see cref="string"/> that specifies the URI prefix.
/// </param>
/// <param name="listener">
/// A <see cref="HttpListener"/> that specifies the HTTP listener.
/// </param>
internal HttpListenerPrefix (string uriPrefix, HttpListener listener)
{
_original = uriPrefix;
_listener = listener;
parse (uriPrefix);
}
#endregion
#region Public Properties
public string Host {
get {
return _host;
}
}
public bool IsSecure {
get {
return _secure;
}
}
public HttpListener Listener {
get {
return _listener;
}
}
public string Original {
get {
return _original;
}
}
public string Path {
get {
return _path;
}
}
public string Port {
get {
return _port;
}
}
#endregion
#region Private Methods
private void parse (string uriPrefix)
{
if (uriPrefix.StartsWith ("https"))
_secure = true;
var len = uriPrefix.Length;
var host = uriPrefix.IndexOf (':') + 3;
var root = uriPrefix.IndexOf ('/', host + 1, len - host - 1);
var colon = uriPrefix.LastIndexOf (':', root - 1, root - host - 1);
if (uriPrefix[root - 1] != ']' && colon > host) {
_host = uriPrefix.Substring (host, colon - host);
_port = uriPrefix.Substring (colon + 1, root - colon - 1);
}
else {
_host = uriPrefix.Substring (host, root - host);
_port = _secure ? "443" : "80";
}
_path = uriPrefix.Substring (root);
_prefix = String.Format (
"{0}://{1}:{2}{3}",
_secure ? "https" : "http",
_host,
_port,
_path
);
}
#endregion
#region Public Methods
public static void CheckPrefix (string uriPrefix)
{
if (uriPrefix == null)
throw new ArgumentNullException ("uriPrefix");
var len = uriPrefix.Length;
if (len == 0) {
var msg = "An empty string.";
throw new ArgumentException (msg, "uriPrefix");
}
var schm = uriPrefix.StartsWith ("http://")
|| uriPrefix.StartsWith ("https://");
if (!schm) {
var msg = "The scheme is not 'http' or 'https'.";
throw new ArgumentException (msg, "uriPrefix");
}
var end = len - 1;
if (uriPrefix[end] != '/') {
var msg = "It ends without '/'.";
throw new ArgumentException (msg, "uriPrefix");
}
var host = uriPrefix.IndexOf (':') + 3;
if (host >= end) {
var msg = "No host is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
if (uriPrefix[host] == ':') {
var msg = "No host is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
var root = uriPrefix.IndexOf ('/', host, len - host);
if (root == host) {
var msg = "No host is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
if (uriPrefix[root - 1] == ':') {
var msg = "No port is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
if (root == end - 1) {
var msg = "No path is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
}
/// <summary>
/// Determines whether the current instance is equal to the specified
/// <see cref="object"/> instance.
/// </summary>
/// <remarks>
/// This method will be required to detect duplicates in any collection.
/// </remarks>
/// <param name="obj">
/// <para>
/// An <see cref="object"/> instance to compare to the current instance.
/// </para>
/// <para>
/// An reference to a <see cref="HttpListenerPrefix"/> instance.
/// </para>
/// </param>
/// <returns>
/// <c>true</c> if the current instance and <paramref name="obj"/> have
/// the same URI prefix; otherwise, <c>false</c>.
/// </returns>
public override bool Equals (object obj)
{
var pref = obj as HttpListenerPrefix;
return pref != null && _prefix.Equals (pref._prefix);
}
/// <summary>
/// Gets the hash code for the current instance.
/// </summary>
/// <remarks>
/// This method will be required to detect duplicates in any collection.
/// </remarks>
/// <returns>
/// An <see cref="int"/> that represents the hash code.
/// </returns>
public override int GetHashCode ()
{
return _prefix.GetHashCode ();
}
public override string ToString ()
{
return _prefix;
}
#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.CodeDom.Compiler;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Sarif.Readers;
namespace Microsoft.CodeAnalysis.Sarif
{
/// <summary>
/// Defines methods to support the comparison of objects of type AnnotatedCodeLocation for equality.
/// </summary>
[GeneratedCode("Microsoft.Json.Schema.ToDotNet", "0.42.0.0")]
internal sealed class AnnotatedCodeLocationEqualityComparer : IEqualityComparer<AnnotatedCodeLocation>
{
internal static readonly AnnotatedCodeLocationEqualityComparer Instance = new AnnotatedCodeLocationEqualityComparer();
public bool Equals(AnnotatedCodeLocation left, AnnotatedCodeLocation right)
{
if (ReferenceEquals(left, right))
{
return true;
}
if (ReferenceEquals(left, null) || ReferenceEquals(right, null))
{
return false;
}
if (left.Id != right.Id)
{
return false;
}
if (left.Step != right.Step)
{
return false;
}
if (!PhysicalLocation.ValueComparer.Equals(left.PhysicalLocation, right.PhysicalLocation))
{
return false;
}
if (left.FullyQualifiedLogicalName != right.FullyQualifiedLogicalName)
{
return false;
}
if (left.LogicalLocationKey != right.LogicalLocationKey)
{
return false;
}
if (left.Module != right.Module)
{
return false;
}
if (left.ThreadId != right.ThreadId)
{
return false;
}
if (left.Message != right.Message)
{
return false;
}
if (left.Kind != right.Kind)
{
return false;
}
if (left.Callee != right.Callee)
{
return false;
}
if (left.CalleeKey != right.CalleeKey)
{
return false;
}
if (left.Essential != right.Essential)
{
return false;
}
if (left.Importance != right.Importance)
{
return false;
}
if (left.Snippet != right.Snippet)
{
return false;
}
if (!object.ReferenceEquals(left.Properties, right.Properties))
{
if (left.Properties == null || right.Properties == null || left.Properties.Count != right.Properties.Count)
{
return false;
}
foreach (var value_0 in left.Properties)
{
SerializedPropertyInfo value_1;
if (!right.Properties.TryGetValue(value_0.Key, out value_1))
{
return false;
}
if (!object.Equals(value_0.Value, value_1))
{
return false;
}
}
}
return true;
}
public int GetHashCode(AnnotatedCodeLocation obj)
{
if (ReferenceEquals(obj, null))
{
return 0;
}
int result = 17;
unchecked
{
result = (result * 31) + obj.Id.GetHashCode();
result = (result * 31) + obj.Step.GetHashCode();
if (obj.PhysicalLocation != null)
{
result = (result * 31) + obj.PhysicalLocation.ValueGetHashCode();
}
if (obj.FullyQualifiedLogicalName != null)
{
result = (result * 31) + obj.FullyQualifiedLogicalName.GetHashCode();
}
if (obj.LogicalLocationKey != null)
{
result = (result * 31) + obj.LogicalLocationKey.GetHashCode();
}
if (obj.Module != null)
{
result = (result * 31) + obj.Module.GetHashCode();
}
result = (result * 31) + obj.ThreadId.GetHashCode();
if (obj.Message != null)
{
result = (result * 31) + obj.Message.GetHashCode();
}
result = (result * 31) + obj.Kind.GetHashCode();
if (obj.Callee != null)
{
result = (result * 31) + obj.Callee.GetHashCode();
}
if (obj.CalleeKey != null)
{
result = (result * 31) + obj.CalleeKey.GetHashCode();
}
result = (result * 31) + obj.Essential.GetHashCode();
result = (result * 31) + obj.Importance.GetHashCode();
if (obj.Snippet != null)
{
result = (result * 31) + obj.Snippet.GetHashCode();
}
if (obj.Properties != null)
{
// Use xor for dictionaries to be order-independent.
int xor_0 = 0;
foreach (var value_2 in obj.Properties)
{
xor_0 ^= value_2.Key.GetHashCode();
if (value_2.Value != null)
{
xor_0 ^= value_2.Value.GetHashCode();
}
}
result = (result * 31) + xor_0;
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MRTutorial.ProtectedApi.Areas.HelpPage.ModelDescriptions;
using MRTutorial.ProtectedApi.Areas.HelpPage.Models;
namespace MRTutorial.ProtectedApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
namespace DotVVM.Framework.Compilation.Javascript.Ast
{
/// <summary>
/// Represents the children of an JsNode that have a specific role.
/// </summary>
public readonly struct JsNodeCollection<T> : ICollection<T>
where T : JsNode
{
readonly JsNode node;
readonly JsTreeRole<T> role;
public JsNodeCollection(JsNode node, JsTreeRole<T> role)
{
if (node == null)
throw new ArgumentNullException("node");
if (role == null)
throw new ArgumentNullException("role");
this.node = node;
this.role = role;
}
public int Count {
get {
int count = 0;
for (var cur = node.FirstChild; cur != null; cur = cur.NextSibling) {
if (cur.Role == role)
count++;
}
return count;
}
}
public void Add(T? element)
{
node.AddChild(element, role);
}
public void AddRange(IEnumerable<T?> nodes)
{
// Evaluate 'nodes' first, since it might change when we add the new children
// Example: collection.AddRange(collection);
if (nodes != null) {
foreach (T? node in nodes.ToList())
Add(node);
}
}
public void AddRange(T?[] nodes)
{
// Fast overload for arrays - we don't need to create a copy
if (nodes != null) {
foreach (T? node in nodes)
Add(node);
}
}
public void ReplaceWith(IEnumerable<T?>? nodes)
{
// Evaluate 'nodes' first, since it might change when we call Clear()
// Example: collection.ReplaceWith(collection);
if (nodes != null)
nodes = nodes.ToList();
Clear();
if (nodes != null) {
foreach (T? node in nodes)
Add(node);
}
}
public void MoveTo(ICollection<T> targetCollection)
{
if (targetCollection == null)
throw new ArgumentNullException("targetCollection");
foreach (T node in this) {
node.Remove();
targetCollection.Add(node);
}
}
public bool Contains([NotNullWhen(true)] T? element)
{
return element != null && element.Parent == node && element.Role == role;
}
public bool Remove(T? element)
{
if (Contains(element)) {
element.Remove();
return true;
} else {
return false;
}
}
public void CopyTo(T[] array, int arrayIndex)
{
for (var cur = node.FirstChild; cur != null; cur = cur.NextSibling) {
if (cur.Role == role)
array[arrayIndex++] = (T)cur;
}
}
public T[] ToArray()
{
var result = new T[Count];
CopyTo(result, 0);
return result;
}
public void Clear()
{
foreach (T item in this)
item.Remove();
}
/// <summary>
/// Returns the first element for which the predicate returns true,
/// or the null node (JsNode with IsNull=true) if no such object is found.
/// </summary>
public T? FirstOrDefault(Func<T, bool>? predicate = null)
{
for (var cur = node.FirstChild; cur != null; cur = cur.NextSibling) {
if (cur.Role == role && (predicate == null || predicate((T)cur)))
return (T)cur;
}
return null;
}
/// <summary>
/// Returns the last element for which the predicate returns true,
/// or the null node (JsNode with IsNull=true) if no such object is found.
/// </summary>
public T? LastOrDefault(Func<T, bool>? predicate = null)
{
for (var cur = node.LastChild; cur != null; cur = cur.PrevSibling) {
if (cur.Role == role && (predicate == null || predicate((T)cur)))
return (T)cur;
}
return null;
}
bool ICollection<T>.IsReadOnly => false;
public ChildrenEnumerator GetEnumerator() => new ChildrenEnumerator(node.FirstChild, role);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public struct ChildrenEnumerator : IEnumerator<T>
{
private JsNode? next;
private JsNode? cur;
private JsTreeRole<T> role;
public ChildrenEnumerator(JsNode? firstChild, JsTreeRole<T> role)
{
this.next = firstChild;
this.cur = null;
this.role = role;
}
public T Current => (T)cur!;
public bool MoveNext()
{
while (true) {
cur = next;
if (cur is null)
return false;
// Remember next before yielding cur.
// This allows removing/replacing nodes while iterating through the list.
next = cur.NextSibling;
if (cur.Role == role)
return true;
}
}
object System.Collections.IEnumerator.Current => cur!;
public void Dispose() { }
void System.Collections.IEnumerator.Reset() { throw new NotImplementedException(); }
}
#region Equals and GetHashCode implementation
public override int GetHashCode()
{
return node.GetHashCode() ^ role.GetHashCode();
}
public override bool Equals(object? obj)
{
if (obj is not JsNodeCollection<T> other)
return false;
return this.node == other.node && this.role == other.role;
}
#endregion
public void InsertAfter(T? existingItem, T newItem)
{
node.InsertChildAfter(existingItem, newItem, role);
}
public void InsertBefore(T? existingItem, T newItem)
{
node.InsertChildBefore(existingItem, newItem, role);
}
/// <summary>
/// Applies the <paramref name="visitor"/> to all nodes in this collection.
/// </summary>
public void AcceptVisitor(IJsNodeVisitor visitor)
{
JsNode? next;
for (var cur = node.FirstChild; cur != null; cur = next) {
Debug.Assert(cur.Parent == node);
// Remember next before yielding cur.
// This allows removing/replacing nodes while iterating through the list.
next = cur.NextSibling;
if (cur.Role == role)
cur.AcceptVisitor(visitor);
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.ServiceConnectors.Interregion
{
public class LocalInterregionComms : IRegionModule, IInterregionCommsOut, IInterregionCommsIn
{
private bool m_enabled = false;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
#region Events
public event ChildAgentUpdateReceived OnChildAgentUpdate;
#endregion /* Events */
#region IRegionModule
public void Initialise(Scene scene, IConfigSource config)
{
if (m_sceneList.Count == 0)
{
IConfig startupConfig = config.Configs["Communications"];
if ((startupConfig != null) && (startupConfig.GetString("InterregionComms", "RESTComms") == "LocalComms"))
{
m_log.Debug("[LOCAL COMMS]: Enabling InterregionComms LocalComms module");
m_enabled = true;
}
}
if (!m_enabled)
return;
Init(scene);
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "LocalInterregionCommsModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
/// <summary>
/// Can be called from other modules.
/// </summary>
/// <param name="scene"></param>
public void Init(Scene scene)
{
if (!m_sceneList.Contains(scene))
{
lock (m_sceneList)
{
m_sceneList.Add(scene);
if (m_enabled)
scene.RegisterModuleInterface<IInterregionCommsOut>(this);
scene.RegisterModuleInterface<IInterregionCommsIn>(this);
}
}
}
#endregion /* IRegionModule */
#region IInterregionComms
/**
* Agent-related communications
*/
public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit, bool authorize, out string reason)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
// If this is intended as a root agent entry into the region, check whether it's authorized (e.g. not banned).
if (authorize && !s.AuthorizeUser(aCircuit.AgentID, aCircuit.FirstName, aCircuit.LastName, aCircuit.ClientVersion, out reason))
return false;
// m_log.DebugFormat("[LOCAL COMMS]: Found region {0} to send SendCreateChildAgent", regionHandle);
return s.NewUserConnection(aCircuit, out reason);
}
}
// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for SendCreateChildAgent", regionHandle);
reason = "Did not find region.";
return false;
}
public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.DebugFormat(
// "[LOCAL COMMS]: Found region {0} {1} to send ChildAgentUpdate",
// s.RegionInfo.RegionName, regionHandle);
s.IncomingChildAgentDataUpdate(cAgentData);
return true;
}
}
// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle);
return false;
}
public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
s.IncomingChildAgentDataUpdate(cAgentData);
return true;
}
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return false;
}
public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent)
{
agent = null;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
return s.IncomingRetrieveRootAgent(id, out agent);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return false;
}
public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri)
{
//uint x, y;
//Utils.LongToUInts(regionHandle, out x, out y);
//x = x / Constants.RegionSize;
//y = y / Constants.RegionSize;
//m_log.Debug("\n >>> Local SendReleaseAgent " + x + "-" + y);
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent");
return s.IncomingReleaseAgent(id);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent");
return false;
}
public bool SendCloseAgent(ulong regionHandle, UUID id)
{
//uint x, y;
//Utils.LongToUInts(regionHandle, out x, out y);
//x = x / Constants.RegionSize;
//y = y / Constants.RegionSize;
//m_log.Debug("\n >>> Local SendCloseAgent " + x + "-" + y);
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent");
return s.IncomingCloseAgent(id);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent");
return false;
}
/**
* Object-related communications
*/
public bool SendCreateObject(ulong regionHandle, SceneObjectGroup sog, bool isLocalCall, Vector3 posInOtherRegion,
bool isAttachment)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject");
if (isLocalCall)
{
if (!isAttachment)
{
sog.OffsetForNewRegion(posInOtherRegion);
}
// We need to make a local copy of the object
ISceneObject sogClone = sog.CloneForNewScene();
sogClone.SetState(sog.GetStateSnapshot(true), s.RegionInfo.RegionID);
return s.IncomingCreateObject(sogClone);
}
else
{
// Use the object as it came through the wire
return s.IncomingCreateObject(sog);
}
}
}
return false;
}
public bool SendCreateObject(ulong regionHandle, UUID userID, UUID itemID)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
return s.IncomingCreateObject(userID, itemID);
}
}
return false;
}
public bool SendDeleteObject(ulong regionHandle, UUID objectID, long nonceID)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
SceneObjectPart part = s.GetSceneObjectPart(objectID);
SceneObjectGroup sog = (part == null) ? null : part.ParentGroup;
if (sog != null)
{
m_log.InfoFormat("[LOCAL COMMS]: Crossing abort - deleting object {0} named '{1}'.", sog.UUID, sog.Name);
s.DeleteSceneObject(sog, false, true, false);
return true;
}
}
}
return false;
}
public bool SendUpdateEstateInfo(UUID regionID)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionID == regionID)
{
// m_log.DebugFormat("[LOCAL COMMS]: Found region {0} to send SendUpdateEstateInfo", regionHandle);
EstateSettings es = s.StorageManager.EstateDataStore.LoadEstateSettings(s.RegionInfo.RegionID);
if (es == null)
return false;
// Don't replace the existing estate settings unless we were able to successfully fully load them.
s.RegionInfo.EstateSettings = es;
return true;
}
}
return false;
}
#endregion /* IInterregionComms */
#region Misc
public UUID GetRegionID(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionhandle)
return s.RegionInfo.RegionID;
}
// ? weird. should not happen
return m_sceneList[0].RegionInfo.RegionID;
}
public bool IsLocalRegion(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
if (s.RegionInfo.RegionHandle == regionhandle)
return true;
return false;
}
public SimpleRegionInfo GetRegion(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
if (s.RegionInfo.RegionHandle == regionhandle)
return s.RegionInfo;
return null;
}
#endregion
public ChildAgentUpdate2Response SendChildAgentUpdate2(SimpleRegionInfo regionInfo, AgentData data)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionInfo.RegionHandle)
{
return s.IncomingChildAgentDataUpdate2(data);
}
}
return ChildAgentUpdate2Response.Error;
}
public System.Threading.Tasks.Task<Tuple<bool, string>> SendCreateRemoteChildAgentAsync(SimpleRegionInfo regionInfo, AgentCircuitData aCircuit)
{
throw new NotImplementedException();
}
internal bool SendWaitScenePresence(ulong regionHandle, UUID agentId, int maxSpWait)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
if (s.IncomingWaitScenePresence(agentId, maxSpWait))
{
return true;
}
}
}
return false;
}
public System.Threading.Tasks.Task<bool> SendCloseAgentAsync(SimpleRegionInfo regionInfo, UUID id)
{
throw new NotImplementedException();
}
}
}
| |
// 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;
namespace System.Net
{
internal static partial class Interop
{
// WININET.DLL errors propagated as HRESULT's using FACILITY=WIN32
// as returned by the WinRT Windows.Web.Http APIs. These HRESULT values
// come from the Windows SDK winerror.h file. These values are set into
// the Exception.HResult property.
//
// NOTE: Although .NET Core does not use wininet, .NET Native does and some
// sources are shared between the two. Therefore although this may appear to
// be dead code--note the lack of references to wininet elsewhere--it is not.
// No more Internet handles can be allocated
public const int WININET_E_OUT_OF_HANDLES = unchecked((int)0x80072EE1);
// The operation timed out
public const int WININET_E_TIMEOUT = unchecked((int)0x80072EE2);
// The server returned extended information
public const int WININET_E_EXTENDED_ERROR = unchecked((int)0x80072EE3);
// An internal error occurred in the Microsoft Internet extensions
public const int WININET_E_INTERNAL_ERROR = unchecked((int)0x80072EE4);
// The URL is invalid
public const int WININET_E_INVALID_URL = unchecked((int)0x80072EE5);
// The URL does not use a recognized protocol
public const int WININET_E_UNRECOGNIZED_SCHEME = unchecked((int)0x80072EE6);
// The server name or address could not be resolved
public const int WININET_E_NAME_NOT_RESOLVED = unchecked((int)0x80072EE7);
// A protocol with the required capabilities was not found
public const int WININET_E_PROTOCOL_NOT_FOUND = unchecked((int)0x80072EE8);
// The option is invalid
public const int WININET_E_INVALID_OPTION = unchecked((int)0x80072EE9);
// The length is incorrect for the option type
public const int WININET_E_BAD_OPTION_LENGTH = unchecked((int)0x80072EEA);
// The option value cannot be set
public const int WININET_E_OPTION_NOT_SETTABLE = unchecked((int)0x80072EEB);
// Microsoft Internet Extension support has been shut down
public const int WININET_E_SHUTDOWN = unchecked((int)0x80072EEC);
// The user name was not allowed
public const int WININET_E_INCORRECT_USER_NAME = unchecked((int)0x80072EED);
// The password was not allowed
public const int WININET_E_INCORRECT_PASSWORD = unchecked((int)0x80072EEE);
// The login request was denied
public const int WININET_E_LOGIN_FAILURE = unchecked((int)0x80072EEF);
// The requested operation is invalid
public const int WININET_E_INVALID_OPERATION = unchecked((int)0x80072EF0);
// The operation has been canceled
public const int WININET_E_OPERATION_CANCELLED = unchecked((int)0x80072EF1);
// The supplied handle is the wrong type for the requested operation
public const int WININET_E_INCORRECT_HANDLE_TYPE = unchecked((int)0x80072EF2);
// The handle is in the wrong state for the requested operation
public const int WININET_E_INCORRECT_HANDLE_STATE = unchecked((int)0x80072EF3);
// The request cannot be made on a Proxy session
public const int WININET_E_NOT_PROXY_REQUEST = unchecked((int)0x80072EF4);
// The registry value could not be found
public const int WININET_E_REGISTRY_VALUE_NOT_FOUND = unchecked((int)0x80072EF5);
// The registry parameter is incorrect
public const int WININET_E_BAD_REGISTRY_PARAMETER = unchecked((int)0x80072EF6);
// Direct Internet access is not available
public const int WININET_E_NO_DIRECT_ACCESS = unchecked((int)0x80072EF7);
// No context value was supplied
public const int WININET_E_NO_CONTEXT = unchecked((int)0x80072EF8);
// No status callback was supplied
public const int WININET_E_NO_CALLBACK = unchecked((int)0x80072EF9);
// There are outstanding requests
public const int WININET_E_REQUEST_PENDING = unchecked((int)0x80072EFA);
// The information format is incorrect
public const int WININET_E_INCORRECT_FORMAT = unchecked((int)0x80072EFB);
// The requested item could not be found
public const int WININET_E_ITEM_NOT_FOUND = unchecked((int)0x80072EFC);
// A connection with the server could not be established
public const int WININET_E_CANNOT_CONNECT = unchecked((int)0x80072EFD);
// The connection with the server was terminated abnormally
public const int WININET_E_CONNECTION_ABORTED = unchecked((int)0x80072EFE);
// The connection with the server was reset
public const int WININET_E_CONNECTION_RESET = unchecked((int)0x80072EFF);
// The action must be retried
public const int WININET_E_FORCE_RETRY = unchecked((int)0x80072F00);
// The proxy request is invalid
public const int WININET_E_INVALID_PROXY_REQUEST = unchecked((int)0x80072F01);
// User interaction is required to complete the operation
public const int WININET_E_NEED_UI = unchecked((int)0x80072F02);
// The handle already exists
public const int WININET_E_HANDLE_EXISTS = unchecked((int)0x80072F04);
// The date in the certificate is invalid or has expired
public const int WININET_E_SEC_CERT_DATE_INVALID = unchecked((int)0x80072F05);
// The host name in the certificate is invalid or does not match
public const int WININET_E_SEC_CERT_CN_INVALID = unchecked((int)0x80072F06);
// A redirect request will change a non-secure to a secure connection
public const int WININET_E_HTTP_TO_HTTPS_ON_REDIR = unchecked((int)0x80072F07);
// A redirect request will change a secure to a non-secure connection
public const int WININET_E_HTTPS_TO_HTTP_ON_REDIR = unchecked((int)0x80072F08);
// Mixed secure and non-secure connections
public const int WININET_E_MIXED_SECURITY = unchecked((int)0x80072F09);
// Changing to non-secure post
public const int WININET_E_CHG_POST_IS_NON_SECURE = unchecked((int)0x80072F0A);
// Data is being posted on a non-secure connection
public const int WININET_E_POST_IS_NON_SECURE = unchecked((int)0x80072F0B);
// A certificate is required to complete client authentication
public const int WININET_E_CLIENT_AUTH_CERT_NEEDED = unchecked((int)0x80072F0C);
// The certificate authority is invalid or incorrect
public const int WININET_E_INVALID_CA = unchecked((int)0x80072F0D);
// Client authentication has not been correctly installed
public const int WININET_E_CLIENT_AUTH_NOT_SETUP = unchecked((int)0x80072F0E);
// An error has occurred in a Wininet asynchronous thread. You may need to restart
public const int WININET_E_ASYNC_THREAD_FAILED = unchecked((int)0x80072F0F);
// The protocol scheme has changed during a redirect operaiton
public const int WININET_E_REDIRECT_SCHEME_CHANGE = unchecked((int)0x80072F10);
// There are operations awaiting retry
public const int WININET_E_DIALOG_PENDING = unchecked((int)0x80072F11);
// The operation must be retried
public const int WININET_E_RETRY_DIALOG = unchecked((int)0x80072F12);
// There are no new cache containers
public const int WININET_E_NO_NEW_CONTAINERS = unchecked((int)0x80072F13);
// A security zone check indicates the operation must be retried
public const int WININET_E_HTTPS_HTTP_SUBMIT_REDIR = unchecked((int)0x80072F14);
// The SSL certificate contains errors.
public const int WININET_E_SEC_CERT_ERRORS = unchecked((int)0x80072F17);
// It was not possible to connect to the revocation server or a definitive response could not be obtained.
public const int WININET_E_SEC_CERT_REV_FAILED = unchecked((int)0x80072F19);
// The requested header was not found
public const int WININET_E_HEADER_NOT_FOUND = unchecked((int)0x80072F76);
// The server does not support the requested protocol level
public const int WININET_E_DOWNLEVEL_SERVER = unchecked((int)0x80072F77);
// The server returned an invalid or unrecognized response
public const int WININET_E_INVALID_SERVER_RESPONSE = unchecked((int)0x80072F78);
// The supplied HTTP header is invalid
public const int WININET_E_INVALID_HEADER = unchecked((int)0x80072F79);
// The request for a HTTP header is invalid
public const int WININET_E_INVALID_QUERY_REQUEST = unchecked((int)0x80072F7A);
// The HTTP header already exists
public const int WININET_E_HEADER_ALREADY_EXISTS = unchecked((int)0x80072F7B);
// The HTTP redirect request failed
public const int WININET_E_REDIRECT_FAILED = unchecked((int)0x80072F7C);
// An error occurred in the secure channel support
public const int WININET_E_SECURITY_CHANNEL_ERROR = unchecked((int)0x80072F7D);
// The file could not be written to the cache
public const int WININET_E_UNABLE_TO_CACHE_FILE = unchecked((int)0x80072F7E);
// The TCP/IP protocol is not installed properly
public const int WININET_E_TCPIP_NOT_INSTALLED = unchecked((int)0x80072F7F);
// The computer is disconnected from the network
public const int WININET_E_DISCONNECTED = unchecked((int)0x80072F83);
// The server is unreachable
public const int WININET_E_SERVER_UNREACHABLE = unchecked((int)0x80072F84);
// The proxy server is unreachable
public const int WININET_E_PROXY_SERVER_UNREACHABLE = unchecked((int)0x80072F85);
// The proxy auto-configuration script is in error
public const int WININET_E_BAD_AUTO_PROXY_SCRIPT = unchecked((int)0x80072F86);
// Could not download the proxy auto-configuration script file
public const int WININET_E_UNABLE_TO_DOWNLOAD_SCRIPT = unchecked((int)0x80072F87);
// The supplied certificate is invalid
public const int WININET_E_SEC_INVALID_CERT = unchecked((int)0x80072F89);
// The supplied certificate has been revoked
public const int WININET_E_SEC_CERT_REVOKED = unchecked((int)0x80072F8A);
// The Dialup failed because file sharing was turned on and a failure was requested if security check was needed
public const int WININET_E_FAILED_DUETOSECURITYCHECK = unchecked((int)0x80072F8B);
// Initialization of the WinINet API has not occurred
public const int WININET_E_NOT_INITIALIZED = unchecked((int)0x80072F8C);
// Login failed and the client should display the entity body to the user
public const int WININET_E_LOGIN_FAILURE_DISPLAY_ENTITY_BODY = unchecked((int)0x80072F8E);
// Content decoding has failed
public const int WININET_E_DECODING_FAILED = unchecked((int)0x80072F8F);
// The HTTP request was not redirected
public const int WININET_E_NOT_REDIRECTED = unchecked((int)0x80072F80);
// A cookie from the server must be confirmed by the user
public const int WININET_E_COOKIE_NEEDS_CONFIRMATION = unchecked((int)0x80072F81);
// A cookie from the server has been declined acceptance
public const int WININET_E_COOKIE_DECLINED = unchecked((int)0x80072F82);
// The HTTP redirect request must be confirmed by the user
public const int WININET_E_REDIRECT_NEEDS_CONFIRMATION = unchecked((int)0x80072F88);
}
}
| |
#if !(NETCF_1_0 || SILVERLIGHT)
using System;
using System.Security.Cryptography;
using SystemX509 = System.Security.Cryptography.X509Certificates;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Security
{
/// <summary>
/// A class containing methods to interface the BouncyCastle world to the .NET Crypto world.
/// </summary>
public sealed class DotNetUtilities
{
private DotNetUtilities()
{
}
/// <summary>
/// Create an System.Security.Cryptography.X509Certificate from an X509Certificate Structure.
/// </summary>
/// <param name="x509Struct"></param>
/// <returns>A System.Security.Cryptography.X509Certificate.</returns>
public static SystemX509.X509Certificate ToX509Certificate(
X509CertificateStructure x509Struct)
{
return new SystemX509.X509Certificate(x509Struct.GetDerEncoded());
}
public static SystemX509.X509Certificate ToX509Certificate(
X509Certificate x509Cert)
{
return new SystemX509.X509Certificate(x509Cert.GetEncoded());
}
public static X509Certificate FromX509Certificate(
SystemX509.X509Certificate x509Cert)
{
return new X509CertificateParser().ReadCertificate(x509Cert.GetRawCertData());
}
public static AsymmetricCipherKeyPair GetDsaKeyPair(
DSA dsa)
{
return GetDsaKeyPair(dsa.ExportParameters(true));
}
public static AsymmetricCipherKeyPair GetDsaKeyPair(
DSAParameters dp)
{
DsaValidationParameters validationParameters = (dp.Seed != null)
? new DsaValidationParameters(dp.Seed, dp.Counter)
: null;
DsaParameters parameters = new DsaParameters(
new BigInteger(1, dp.P),
new BigInteger(1, dp.Q),
new BigInteger(1, dp.G),
validationParameters);
DsaPublicKeyParameters pubKey = new DsaPublicKeyParameters(
new BigInteger(1, dp.Y),
parameters);
DsaPrivateKeyParameters privKey = new DsaPrivateKeyParameters(
new BigInteger(1, dp.X),
parameters);
return new AsymmetricCipherKeyPair(pubKey, privKey);
}
public static DsaPublicKeyParameters GetDsaPublicKey(
DSA dsa)
{
return GetDsaPublicKey(dsa.ExportParameters(false));
}
public static DsaPublicKeyParameters GetDsaPublicKey(
DSAParameters dp)
{
DsaValidationParameters validationParameters = (dp.Seed != null)
? new DsaValidationParameters(dp.Seed, dp.Counter)
: null;
DsaParameters parameters = new DsaParameters(
new BigInteger(1, dp.P),
new BigInteger(1, dp.Q),
new BigInteger(1, dp.G),
validationParameters);
return new DsaPublicKeyParameters(
new BigInteger(1, dp.Y),
parameters);
}
public static AsymmetricCipherKeyPair GetRsaKeyPair(
RSA rsa)
{
return GetRsaKeyPair(rsa.ExportParameters(true));
}
public static AsymmetricCipherKeyPair GetRsaKeyPair(
RSAParameters rp)
{
BigInteger modulus = new BigInteger(1, rp.Modulus);
BigInteger pubExp = new BigInteger(1, rp.Exponent);
RsaKeyParameters pubKey = new RsaKeyParameters(
false,
modulus,
pubExp);
RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
modulus,
pubExp,
new BigInteger(1, rp.D),
new BigInteger(1, rp.P),
new BigInteger(1, rp.Q),
new BigInteger(1, rp.DP),
new BigInteger(1, rp.DQ),
new BigInteger(1, rp.InverseQ));
return new AsymmetricCipherKeyPair(pubKey, privKey);
}
public static RsaKeyParameters GetRsaPublicKey(
RSA rsa)
{
return GetRsaPublicKey(rsa.ExportParameters(false));
}
public static RsaKeyParameters GetRsaPublicKey(
RSAParameters rp)
{
return new RsaKeyParameters(
false,
new BigInteger(1, rp.Modulus),
new BigInteger(1, rp.Exponent));
}
public static AsymmetricCipherKeyPair GetKeyPair(AsymmetricAlgorithm privateKey)
{
if (privateKey is DSA)
{
return GetDsaKeyPair((DSA)privateKey);
}
if (privateKey is RSA)
{
return GetRsaKeyPair((RSA)privateKey);
}
throw new ArgumentException("Unsupported algorithm specified", "privateKey");
}
public static RSA ToRSA(RsaKeyParameters rsaKey)
{
RSAParameters rp = ToRSAParameters(rsaKey);
RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider();
// TODO This call appears to not work for private keys (when no CRT info)
rsaCsp.ImportParameters(rp);
return rsaCsp;
}
public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey)
{
RSAParameters rp = ToRSAParameters(privKey);
RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider();
rsaCsp.ImportParameters(rp);
return rsaCsp;
}
public static RSAParameters ToRSAParameters(RsaKeyParameters rsaKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = rsaKey.Modulus.ToByteArrayUnsigned();
if (rsaKey.IsPrivate)
rp.D = ConvertRSAParametersField(rsaKey.Exponent, rp.Modulus.Length);
else
rp.Exponent = rsaKey.Exponent.ToByteArrayUnsigned();
return rp;
}
public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
rp.P = privKey.P.ToByteArrayUnsigned();
rp.Q = privKey.Q.ToByteArrayUnsigned();
rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length);
rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length);
rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length);
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length);
return rp;
}
// TODO Move functionality to more general class
private static byte[] ConvertRSAParametersField(BigInteger n, int size)
{
byte[] bs = n.ToByteArrayUnsigned();
if (bs.Length == size)
return bs;
if (bs.Length > size)
throw new ArgumentException("Specified size too small", "size");
byte[] padded = new byte[size];
Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
return padded;
}
}
}
#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.
==================================================================== */
namespace NPOI.HSSF.Record.Aggregates
{
using System;
using System.Text;
using System.Collections;
using NPOI.HSSF.Record;
using NPOI.HSSF.Model;
using NPOI.SS.Formula;
using System.Collections.Generic;
using NPOI.SS.Util;
using NPOI.SS.Formula.PTG;
/// <summary>
///
/// </summary>
/// CFRecordsAggregate - aggregates Conditional Formatting records CFHeaderRecord
/// and number of up to three CFRuleRecord records toGether to simplify
/// access to them.
/// @author Dmitriy Kumshayev
public class CFRecordsAggregate : RecordAggregate
{
/** Excel allows up to 3 conditional formating rules */
private const int MAX_97_2003_CONDTIONAL_FORMAT_RULES = 3;
public const short sid = -2008; // not a real BIFF record
//private static POILogger log = POILogFactory.GetLogger(typeof(CFRecordsAggregate));
private CFHeaderRecord header;
/** List of CFRuleRecord objects */
private List<CFRuleRecord> rules;
private CFRecordsAggregate(CFHeaderRecord pHeader, CFRuleRecord[] pRules)
{
if (pHeader == null)
{
throw new ArgumentException("header must not be null");
}
if (pRules == null)
{
throw new ArgumentException("rules must not be null");
}
if (pRules.Length > MAX_97_2003_CONDTIONAL_FORMAT_RULES)
{
Console.WriteLine("Excel versions before 2007 require that "
+ "No more than " + MAX_97_2003_CONDTIONAL_FORMAT_RULES
+ " rules may be specified, " + pRules.Length + " were found,"
+ " this file will cause problems with old Excel versions");
}
header = pHeader;
rules = new List<CFRuleRecord>(3);
for (int i = 0; i < pRules.Length; i++)
{
rules.Add(pRules[i]);
}
}
public CFRecordsAggregate(CellRangeAddress[] regions, CFRuleRecord[] rules)
: this(new CFHeaderRecord(regions, rules.Length), rules)
{
}
/// <summary>
/// Create CFRecordsAggregate from a list of CF Records
/// </summary>
/// <param name="rs">list of Record objects</param>
public static CFRecordsAggregate CreateCFAggregate(RecordStream rs)
{
Record rec = rs.GetNext();
if (rec.Sid != CFHeaderRecord.sid)
{
throw new InvalidOperationException("next record sid was " + rec.Sid
+ " instead of " + CFHeaderRecord.sid + " as expected");
}
CFHeaderRecord header = (CFHeaderRecord)rec;
int nRules = header.NumberOfConditionalFormats;
CFRuleRecord[] rules = new CFRuleRecord[nRules];
for (int i = 0; i < rules.Length; i++)
{
rules[i] = (CFRuleRecord)rs.GetNext();
}
return new CFRecordsAggregate(header, rules);
}
/// <summary>
/// Create CFRecordsAggregate from a list of CF Records
/// </summary>
/// <param name="recs">list of Record objects</param>
/// <param name="pOffset">position of CFHeaderRecord object in the list of Record objects</param>
public static CFRecordsAggregate CreateCFAggregate(IList recs, int pOffset)
{
Record rec = (Record)recs[pOffset];
if (rec.Sid != CFHeaderRecord.sid)
{
throw new InvalidOperationException("next record sid was " + rec.Sid
+ " instead of " + CFHeaderRecord.sid + " as expected");
}
CFHeaderRecord header = (CFHeaderRecord)rec;
int nRules = header.NumberOfConditionalFormats;
CFRuleRecord[] rules = new CFRuleRecord[nRules];
int offset = pOffset;
int countFound = 0;
while (countFound < rules.Length)
{
offset++;
if (offset >= recs.Count)
{
break;
}
rec = (Record)recs[offset];
if (rec is CFRuleRecord)
{
rules[countFound] = (CFRuleRecord)rec;
countFound++;
}
else
{
break;
}
}
if (countFound < nRules)
{ // TODO -(MAR-2008) can this ever happen? Write junit
//if (log.Check(POILogger.DEBUG))
//{
// log.Log(POILogger.DEBUG, "Expected " + nRules + " Conditional Formats, "
// + "but found " + countFound + " rules");
//}
header.NumberOfConditionalFormats = (nRules);
CFRuleRecord[] lessRules = new CFRuleRecord[countFound];
Array.Copy(rules, 0, lessRules, 0, countFound);
rules = lessRules;
}
return new CFRecordsAggregate(header, rules);
}
public override void VisitContainedRecords(RecordVisitor rv)
{
rv.VisitRecord(header);
for (int i = 0; i < rules.Count; i++)
{
CFRuleRecord rule = rules[i];
rv.VisitRecord(rule);
}
}
/// <summary>
/// Create a deep Clone of the record
/// </summary>
public CFRecordsAggregate CloneCFAggregate()
{
CFRuleRecord[] newRecs = new CFRuleRecord[rules.Count];
for (int i = 0; i < newRecs.Length; i++)
{
newRecs[i] = (CFRuleRecord)GetRule(i).Clone();
}
return new CFRecordsAggregate((CFHeaderRecord)header.Clone(), newRecs);
}
public override short Sid
{
get { return sid; }
}
/// <summary>
/// called by the class that is responsible for writing this sucker.
/// Subclasses should implement this so that their data is passed back in a
/// byte array.
/// </summary>
/// <param name="offset">The offset to begin writing at</param>
/// <param name="data">The data byte array containing instance data</param>
/// <returns> number of bytes written</returns>
public override int Serialize(int offset, byte[] data)
{
int nRules = rules.Count;
header.NumberOfConditionalFormats = (nRules);
int pos = offset;
pos += header.Serialize(pos, data);
for (int i = 0; i < nRules; i++)
{
pos += GetRule(i).Serialize(pos, data);
}
return pos - offset;
}
public CFHeaderRecord Header
{
get { return header; }
}
private void CheckRuleIndex(int idx)
{
if (idx < 0 || idx >= rules.Count)
{
throw new ArgumentException("Bad rule record index (" + idx
+ ") nRules=" + rules.Count);
}
}
public CFRuleRecord GetRule(int idx)
{
CheckRuleIndex(idx);
return rules[idx];
}
public void SetRule(int idx, CFRuleRecord r)
{
CheckRuleIndex(idx);
rules[idx] = r;
}
/**
* @return <c>false</c> if this whole {@link CFHeaderRecord} / {@link CFRuleRecord}s should be deleted
*/
public bool UpdateFormulasAfterCellShift(FormulaShifter shifter, int currentExternSheetIx)
{
CellRangeAddress[] cellRanges = header.CellRanges;
bool changed = false;
List<CellRangeAddress> temp = new List<CellRangeAddress>();
for (int i = 0; i < cellRanges.Length; i++)
{
CellRangeAddress craOld = cellRanges[i];
CellRangeAddress craNew = ShiftRange(shifter, craOld, currentExternSheetIx);
if (craNew == null)
{
changed = true;
continue;
}
temp.Add(craNew);
if (craNew != craOld)
{
changed = true;
}
}
if (changed)
{
int nRanges = temp.Count;
if (nRanges == 0)
{
return false;
}
CellRangeAddress[] newRanges = new CellRangeAddress[nRanges];
newRanges = temp.ToArray();
header.CellRanges = (newRanges);
}
for (int i = 0; i < rules.Count; i++)
{
CFRuleRecord rule = rules[i];
Ptg[] ptgs;
ptgs = rule.ParsedExpression1;
if (ptgs != null && shifter.AdjustFormula(ptgs, currentExternSheetIx))
{
rule.ParsedExpression1 = (ptgs);
}
ptgs = rule.ParsedExpression2;
if (ptgs != null && shifter.AdjustFormula(ptgs, currentExternSheetIx))
{
rule.ParsedExpression2 = (ptgs);
}
}
return true;
}
private static CellRangeAddress ShiftRange(FormulaShifter shifter, CellRangeAddress cra, int currentExternSheetIx)
{
// FormulaShifter works well in terms of Ptgs - so convert CellRangeAddress to AreaPtg (and back) here
AreaPtg aptg = new AreaPtg(cra.FirstRow, cra.LastRow, cra.FirstColumn, cra.LastColumn, false, false, false, false);
Ptg[] ptgs = { aptg, };
if (!shifter.AdjustFormula(ptgs, currentExternSheetIx))
{
return cra;
}
Ptg ptg0 = ptgs[0];
if (ptg0 is AreaPtg)
{
AreaPtg bptg = (AreaPtg)ptg0;
return new CellRangeAddress(bptg.FirstRow, bptg.LastRow, bptg.FirstColumn, bptg.LastColumn);
}
if (ptg0 is AreaErrPtg)
{
return null;
}
throw new InvalidCastException("Unexpected shifted ptg class (" + ptg0.GetType().Name + ")");
}
public void AddRule(CFRuleRecord r)
{
if (rules.Count >= MAX_97_2003_CONDTIONAL_FORMAT_RULES)
{
Console.WriteLine("Excel versions before 2007 cannot cope with"
+ " any more than " + MAX_97_2003_CONDTIONAL_FORMAT_RULES
+ " - this file will cause problems with old Excel versions");
}
rules.Add(r);
header.NumberOfConditionalFormats = (rules.Count);
}
public int NumberOfRules
{
get { return rules.Count; }
}
/**
* @return sum of sizes of all aggregated records
*/
//public override int RecordSize
//{
// get
// {
// int size = 0;
// if (header != null)
// {
// size += header.RecordSize;
// }
// if (rules != null)
// {
// for (IEnumerator irecs = rules.GetEnumerator(); irecs.MoveNext(); )
// {
// size += ((Record)irecs.Current).RecordSize;
// }
// }
// return size;
// }
//}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[CF]\n");
if (header != null)
{
buffer.Append(header.ToString());
}
for (int i = 0; i < rules.Count; i++)
{
CFRuleRecord cfRule = rules[i];
if (cfRule != null)
{
buffer.Append(cfRule.ToString());
}
}
buffer.Append("[/CF]\n");
return buffer.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Writers.CSharp;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Extensions.CSharp
{
public static class CSharpCciExtensions
{
public static string GetCSharpDeclaration(this IDefinition definition, bool includeAttributes = false)
{
using (var stringWriter = new StringWriter())
{
using (var syntaxWriter = new TextSyntaxWriter(stringWriter))
{
var writer = new CSDeclarationWriter(syntaxWriter, new AttributesFilter(includeAttributes), false, true);
var nsp = definition as INamespaceDefinition;
var typeDefinition = definition as ITypeDefinition;
var member = definition as ITypeDefinitionMember;
if (nsp != null)
writer.WriteNamespaceDeclaration(nsp);
else if (typeDefinition != null)
writer.WriteTypeDeclaration(typeDefinition);
else if (member != null)
{
var method = member as IMethodDefinition;
if (method != null && method.IsPropertyOrEventAccessor())
WriteAccessor(syntaxWriter, method);
else
writer.WriteMemberDeclaration(member);
}
}
return stringWriter.ToString();
}
}
private static void WriteAccessor(ISyntaxWriter syntaxWriter, IMethodDefinition method)
{
var accessorKeyword = GetAccessorKeyword(method);
syntaxWriter.WriteKeyword(accessorKeyword);
syntaxWriter.WriteSymbol(";");
}
private static string GetAccessorKeyword(IMethodDefinition method)
{
switch (method.GetAccessorType())
{
case AccessorType.EventAdder:
return "add";
case AccessorType.EventRemover:
return "remove";
case AccessorType.PropertySetter:
return "set";
case AccessorType.PropertyGetter:
return "get";
default:
throw new ArgumentOutOfRangeException();
}
}
public static bool IsDefaultCSharpBaseType(this ITypeReference baseType, ITypeDefinition type)
{
Contract.Requires(baseType != null);
Contract.Requires(type != null);
if (baseType.AreEquivalent("System.Object"))
return true;
if (type.IsValueType && baseType.AreEquivalent("System.ValueType"))
return true;
if (type.IsEnum && baseType.AreEquivalent("System.Enum"))
return true;
return false;
}
public static IMethodDefinition GetInvokeMethod(this ITypeDefinition type)
{
if (!type.IsDelegate)
return null;
foreach (var method in type.Methods)
if (method.Name.Value == "Invoke")
return method;
throw new InvalidOperationException(String.Format("All delegates should have an Invoke method, but {0} doesn't have one.", type.FullName()));
}
public static ITypeReference GetEnumType(this ITypeDefinition type)
{
if (!type.IsEnum)
return null;
foreach (var field in type.Fields)
if (field.Name.Value == "value__")
return field.Type;
throw new InvalidOperationException("All enums should have a value__ field!");
}
public static bool IsOrContainsReferenceType(this ITypeReference type)
{
Queue<ITypeReference> typesToCheck = new Queue<ITypeReference>();
HashSet<ITypeReference> visited = new HashSet<ITypeReference>();
typesToCheck.Enqueue(type);
while (typesToCheck.Count != 0)
{
var typeToCheck = typesToCheck.Dequeue();
visited.Add(typeToCheck);
var resolvedType = typeToCheck.ResolvedType;
// If it is dummy we cannot really check so assume it does because that is will be the most conservative
if (resolvedType is Dummy)
return true;
if (resolvedType.IsReferenceType)
return true;
// ByReference<T> is a special type understood by runtime to hold a ref T.
if (resolvedType.AreEquivalent("System.ByReference<T>"))
return true;
foreach (var field in resolvedType.Fields.Where(f => !f.IsStatic))
{
if (!visited.Contains(field.Type))
{
typesToCheck.Enqueue(field.Type);
}
}
}
return false;
}
public static bool IsConversionOperator(this IMethodDefinition method)
{
return (method.IsSpecialName &&
(method.Name.Value == "op_Explicit" || method.Name.Value == "op_Implicit"));
}
public static bool IsExplicitInterfaceMember(this ITypeDefinitionMember member)
{
var method = member as IMethodDefinition;
if (method != null)
{
return method.IsExplicitInterfaceMethod();
}
var property = member as IPropertyDefinition;
if (property != null)
{
return property.IsExplicitInterfaceProperty();
}
return false;
}
public static bool IsExplicitInterfaceMethod(this IMethodDefinition method)
{
return MemberHelper.GetExplicitlyOverriddenMethods(method).Any();
}
public static bool IsExplicitInterfaceProperty(this IPropertyDefinition property)
{
if (property.Getter != null && property.Getter.ResolvedMethod != null)
{
return property.Getter.ResolvedMethod.IsExplicitInterfaceMethod();
}
if (property.Setter != null && property.Setter.ResolvedMethod != null)
{
return property.Setter.ResolvedMethod.IsExplicitInterfaceMethod();
}
return false;
}
public static bool IsInterfaceImplementation(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsInterfaceImplementation();
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsInterfaceImplementation());
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsInterfaceImplementation());
return false;
}
public static bool IsInterfaceImplementation(this IMethodDefinition method)
{
return MemberHelper.GetImplicitlyImplementedInterfaceMethods(method).Any()
|| MemberHelper.GetExplicitlyOverriddenMethods(method).Any();
}
public static bool IsAbstract(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsAbstract;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsAbstract);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsAbstract);
return false;
}
public static bool IsVirtual(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsVirtual;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsVirtual);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsVirtual);
return false;
}
public static bool IsNewSlot(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsNewSlot;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsNewSlot);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsNewSlot);
return false;
}
public static bool IsSealed(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsSealed;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsSealed);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsSealed);
return false;
}
public static bool IsOverride(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsOverride();
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsOverride());
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsOverride());
return false;
}
public static bool IsOverride(this IMethodDefinition method)
{
return method.IsVirtual && !method.IsNewSlot;
}
public static bool IsUnsafeType(this ITypeReference type)
{
return type.TypeCode == PrimitiveTypeCode.Pointer;
}
public static bool IsMethodUnsafe(this IMethodDefinition method)
{
foreach (var p in method.Parameters)
{
if (p.Type.IsUnsafeType())
return true;
}
if (method.Type.IsUnsafeType())
return true;
return false;
}
public static bool IsDestructor(this IMethodDefinition methodDefinition)
{
if (methodDefinition.ContainingTypeDefinition.IsValueType) return false; //only classes can have destructors
if (methodDefinition.ParameterCount == 0 && methodDefinition.IsVirtual &&
methodDefinition.Visibility == TypeMemberVisibility.Family && methodDefinition.Name.Value == "Finalize")
{
// Should we make sure that this Finalize method overrides the protected System.Object.Finalize?
return true;
}
return false;
}
public static bool IsDispose(this IMethodDefinition methodDefinition)
{
if ((methodDefinition.Name.Value != "Dispose" && methodDefinition.Name.Value != "System.IDisposable.Dispose") || methodDefinition.ParameterCount > 1 ||
!TypeHelper.TypesAreEquivalent(methodDefinition.Type, methodDefinition.ContainingTypeDefinition.PlatformType.SystemVoid))
{
return false;
}
if (methodDefinition.ParameterCount == 1 && !TypeHelper.TypesAreEquivalent(methodDefinition.Parameters.First().Type, methodDefinition.ContainingTypeDefinition.PlatformType.SystemBoolean))
{
// Dispose(Boolean) its only parameter should be bool
return false;
}
return true;
}
public static bool IsAssembly(this ITypeDefinitionMember member)
{
return member.Visibility == TypeMemberVisibility.FamilyAndAssembly ||
member.Visibility == TypeMemberVisibility.Assembly;
}
public static bool InSameUnit(ITypeDefinitionMember member1, ITypeDefinitionMember member2)
{
IUnit unit1 = TypeHelper.GetDefiningUnit(member1.ContainingTypeDefinition);
IUnit unit2 = TypeHelper.GetDefiningUnit(member2.ContainingTypeDefinition);
return UnitHelper.UnitsAreEquivalent(unit1, unit2);
}
public static ITypeReference GetReturnType(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.Type;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Type;
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Type;
IFieldDefinition field = member as IFieldDefinition;
if (field != null)
return field.Type;
return null;
}
public static IFieldDefinition GetHiddenBaseField(this IFieldDefinition field, ICciFilter filter = null)
{
foreach (ITypeReference baseClassRef in field.ContainingTypeDefinition.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IFieldDefinition baseField in baseClass.GetMembersNamed(field.Name, false).OfType<IFieldDefinition>())
{
if (baseField.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseField) && !InSameUnit(baseField, field))
continue;
if (filter != null && !filter.Include(baseField))
continue;
return baseField;
}
}
return Dummy.Field;
}
public static IEventDefinition GetHiddenBaseEvent(this IEventDefinition evnt, ICciFilter filter = null)
{
IMethodDefinition eventRep = evnt.Adder.ResolvedMethod;
if (eventRep.IsVirtual && !eventRep.IsNewSlot) return Dummy.Event; // an override
foreach (ITypeReference baseClassRef in evnt.ContainingTypeDefinition.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IEventDefinition baseEvent in baseClass.GetMembersNamed(evnt.Name, false).OfType<IEventDefinition>())
{
if (baseEvent.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseEvent) && !InSameUnit(baseEvent, evnt))
continue;
if (filter != null && !filter.Include(baseEvent))
continue;
return baseEvent;
}
}
return Dummy.Event;
}
public static IPropertyDefinition GetHiddenBaseProperty(this IPropertyDefinition property, ICciFilter filter = null)
{
IMethodDefinition propertyRep = property.Accessors.First().ResolvedMethod;
if (propertyRep.IsVirtual && !propertyRep.IsNewSlot) return Dummy.Property; // an override
ITypeDefinition type = property.ContainingTypeDefinition;
foreach (ITypeReference baseClassRef in type.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IPropertyDefinition baseProperty in baseClass.GetMembersNamed(property.Name, false).OfType<IPropertyDefinition>())
{
if (baseProperty.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseProperty) && !InSameUnit(baseProperty, property))
continue;
if (filter != null && !filter.Include(baseProperty))
continue;
if (SignaturesParametersAreEqual(property, baseProperty))
return baseProperty;
}
}
return Dummy.Property;
}
public static IMethodDefinition GetHiddenBaseMethod(this IMethodDefinition method, ICciFilter filter = null)
{
if (method.IsConstructor) return Dummy.Method;
if (method.IsVirtual && !method.IsNewSlot) return Dummy.Method; // an override
ITypeDefinition type = method.ContainingTypeDefinition;
foreach (ITypeReference baseClassRef in type.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IMethodDefinition baseMethod in baseClass.GetMembersNamed(method.Name, false).OfType<IMethodDefinition>())
{
if (baseMethod.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseMethod) && !InSameUnit(baseMethod, method))
continue;
if (filter != null && !filter.Include(baseMethod.UnWrapMember()))
continue;
// NOTE: Do not check method.IsHiddenBySignature here. C# is *always* hide-by-signature regardless of the metadata flag.
// Do not check return type here, C# hides based on parameter types alone.
if (SignaturesParametersAreEqual(method, baseMethod))
{
if (!method.IsGeneric && !baseMethod.IsGeneric)
return baseMethod;
if (method.GenericParameterCount == baseMethod.GenericParameterCount)
return baseMethod;
}
}
}
return Dummy.Method;
}
public static bool SignaturesParametersAreEqual(this ISignature sig1, ISignature sig2)
{
return IteratorHelper.EnumerablesAreEqual<IParameterTypeInformation>(sig1.Parameters, sig2.Parameters, new ParameterInformationComparer());
}
private static Regex s_isKeywordRegex;
public static bool IsKeyword(string s)
{
if (s_isKeywordRegex == null)
s_isKeywordRegex = new Regex("^(abstract|as|break|case|catch|checked|class|const|continue|default|delegate|do|else|enum|event|explicit|extern|finally|foreach|for|get|goto|if|implicit|interface|internal|in|is|lock|namespace|new|operator|out|override|params|partial|private|protected|public|readonly|ref|return|sealed|set|sizeof|stackalloc|static|struct|switch|this|throw|try|typeof|unchecked|unsafe|using|virtual|volatile|while|yield|bool|byte|char|decimal|double|fixed|float|int|long|object|sbyte|short|string|uint|ulong|ushort|void)$", RegexOptions.Compiled);
return s_isKeywordRegex.IsMatch(s);
}
public static string GetMethodName(this IMethodDefinition method)
{
if (method.IsConstructor)
{
INamedEntity named = method.ContainingTypeDefinition.UnWrap() as INamedEntity;
if (named != null)
return named.Name.Value;
}
switch (method.Name.Value)
{
case "op_Decrement": return "operator --";
case "op_Increment": return "operator ++";
case "op_UnaryNegation": return "operator -";
case "op_UnaryPlus": return "operator +";
case "op_LogicalNot": return "operator !";
case "op_OnesComplement": return "operator ~";
case "op_True": return "operator true";
case "op_False": return "operator false";
case "op_Addition": return "operator +";
case "op_Subtraction": return "operator -";
case "op_Multiply": return "operator *";
case "op_Division": return "operator /";
case "op_Modulus": return "operator %";
case "op_ExclusiveOr": return "operator ^";
case "op_BitwiseAnd": return "operator &";
case "op_BitwiseOr": return "operator |";
case "op_LeftShift": return "operator <<";
case "op_RightShift": return "operator >>";
case "op_Equality": return "operator ==";
case "op_GreaterThan": return "operator >";
case "op_LessThan": return "operator <";
case "op_Inequality": return "operator !=";
case "op_GreaterThanOrEqual": return "operator >=";
case "op_LessThanOrEqual": return "operator <=";
case "op_Explicit": return "explicit operator";
case "op_Implicit": return "implicit operator";
default: return method.Name.Value; // return just the name
}
}
public static string GetNameWithoutExplicitType(this ITypeDefinitionMember member)
{
string name = member.Name.Value;
int index = name.LastIndexOf(".");
if (index < 0)
return name;
return name.Substring(index + 1);
}
public static bool IsExtensionMethod(this IMethodDefinition method)
{
if (!method.IsStatic)
return false;
return method.Attributes.HasAttributeOfType("System.Runtime.CompilerServices.ExtensionAttribute");
}
public static bool IsEffectivelySealed(this ITypeDefinition type)
{
if (type.IsSealed)
return true;
if (type.IsInterface)
return false;
// Types with only private constructors are effectively sealed
if (!type.Methods
.Any(m =>
m.IsConstructor &&
!m.IsStaticConstructor &&
m.IsVisibleOutsideAssembly()))
return true;
return false;
}
public static bool IsException(this ITypeDefinition type)
{
foreach (var baseTypeRef in type.GetBaseTypes())
{
if (baseTypeRef.AreEquivalent("System.Exception"))
return true;
}
return false;
}
public static bool IsAttribute(this ITypeDefinition type)
{
foreach (var baseTypeRef in type.GetBaseTypes())
{
if (baseTypeRef.AreEquivalent("System.Attribute"))
return true;
}
return false;
}
public static bool HasAttributeOfType(this IEnumerable<ICustomAttribute> attributes, string attributeName)
{
return attributes.Any(a => a.Type.AreEquivalent(attributeName));
}
public static bool HasIsByRefLikeAttribute(this IEnumerable<ICustomAttribute> attributes)
{
return attributes.HasAttributeOfType("System.Runtime.CompilerServices.IsByRefLikeAttribute");
}
public static bool HasIsReadOnlyAttribute(this IEnumerable<ICustomAttribute> attributes)
{
return attributes.HasAttributeOfType("System.Runtime.CompilerServices.IsReadOnlyAttribute");
}
private static IEnumerable<ITypeReference> GetBaseTypes(this ITypeReference typeRef)
{
ITypeDefinition type = typeRef.GetDefinitionOrNull();
if (type == null)
yield break;
foreach (var baseTypeRef in type.BaseClasses)
{
yield return baseTypeRef;
foreach (var nestedBaseTypeRef in GetBaseTypes(baseTypeRef))
yield return nestedBaseTypeRef;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ModelClass" company="LoginRadius">
// Created by LoginRadius Development Team
// Copyright 2019 LoginRadius Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using LoginRadiusSDK.V2.Models.ResponseModels.UserProfile.Objects;
using LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects;
namespace LoginRadiusSDK.V2.Models.ResponseModels.UserProfile
{
/// <summary>
/// Response containing Definition for Complete UserProfile data
/// </summary>
public class UserProfile:SocialUserProfile
{
/// <summary>
/// Response containing consent profile
/// </summary>
[JsonProperty(PropertyName = "ConsentProfile")]
public ConsentProfile ConsentProfile {get;set;}
/// <summary>
/// Custom fields as user set on LoginRadius Admin Console.
/// </summary>
[JsonProperty(PropertyName = "CustomFields")]
public Dictionary<string,string> CustomFields {get;set;}
/// <summary>
/// boolean type value, default is true
/// </summary>
[JsonProperty(PropertyName = "EmailVerified")]
public bool? EmailVerified {get;set;}
/// <summary>
/// Array of Objects,string represents SourceId,Source
/// </summary>
[JsonProperty(PropertyName = "ExternalIds")]
public List<ExternalIds> ExternalIds {get;set;}
/// <summary>
/// External User Login Id
/// </summary>
[JsonProperty(PropertyName = "ExternalUserLoginId")]
public string ExternalUserLoginId {get;set;}
/// <summary>
/// boolean type value, default is true
/// </summary>
[JsonProperty(PropertyName = "IsActive")]
public bool? IsActive {get;set;}
/// <summary>
/// id is custom of not
/// </summary>
[JsonProperty(PropertyName = "IsCustomUid")]
public bool? IsCustomUid {get;set;}
/// <summary>
/// boolean type value, default is true
/// </summary>
[JsonProperty(PropertyName = "IsDeleted")]
public bool? IsDeleted {get;set;}
/// <summary>
/// boolean type value, default is true
/// </summary>
[JsonProperty(PropertyName = "IsEmailSubscribed")]
public bool? IsEmailSubscribed {get;set;}
/// <summary>
/// Pass true if wants to lock the user's Login field else false.
/// </summary>
[JsonProperty(PropertyName = "IsLoginLocked")]
public bool? IsLoginLocked {get;set;}
/// <summary>
/// Required fields filled once or not
/// </summary>
[JsonProperty(PropertyName = "IsRequiredFieldsFilledOnce")]
public bool? IsRequiredFieldsFilledOnce {get;set;}
/// <summary>
/// Is secure password or not
/// </summary>
[JsonProperty(PropertyName = "IsSecurePassword")]
public bool? IsSecurePassword {get;set;}
/// <summary>
/// Last login location
/// </summary>
[JsonProperty(PropertyName = "LastLoginLocation")]
public string LastLoginLocation {get;set;}
/// <summary>
/// Last password change date
/// </summary>
[JsonProperty(PropertyName = "LastPasswordChangeDate")]
public DateTime? LastPasswordChangeDate {get;set;}
/// <summary>
/// Last password change token
/// </summary>
[JsonProperty(PropertyName = "LastPasswordChangeToken")]
public string LastPasswordChangeToken {get;set;}
/// <summary>
/// Type of Lockout
/// </summary>
[JsonProperty(PropertyName = "LoginLockedType")]
public string LoginLockedType {get;set;}
/// <summary>
/// Number of Logins
/// </summary>
[JsonProperty(PropertyName = "NoOfLogins")]
public int? NoOfLogins {get;set;}
/// <summary>
/// Password for the email
/// </summary>
[JsonProperty(PropertyName = "Password")]
public string Password {get;set;}
/// <summary>
/// Date of password expiration
/// </summary>
[JsonProperty(PropertyName = "PasswordExpirationDate")]
public DateTime? PasswordExpirationDate {get;set;}
/// <summary>
/// Phone ID (Unique Phone Number Identifier of the user)
/// </summary>
[JsonProperty(PropertyName = "PhoneId")]
public string PhoneId {get;set;}
/// <summary>
/// boolean type value, default is false
/// </summary>
[JsonProperty(PropertyName = "PhoneIdVerified")]
public bool? PhoneIdVerified {get;set;}
/// <summary>
/// PIN of user
/// </summary>
[JsonProperty(PropertyName = "PIN")]
public PINInformation PIN {get;set;}
/// <summary>
/// Object type by default false, string represents Version, AcceptSource and datetime represents AcceptDateTime
/// </summary>
[JsonProperty(PropertyName = "PrivacyPolicy")]
public AcceptedPrivacyPolicy PrivacyPolicy {get;set;}
/// <summary>
/// User Registartion Data
/// </summary>
[JsonProperty(PropertyName = "RegistrationData")]
public RegistrationData RegistrationData {get;set;}
/// <summary>
/// Provider with which user registered
/// </summary>
[JsonProperty(PropertyName = "RegistrationProvider")]
public string RegistrationProvider {get;set;}
/// <summary>
/// URL of the webproperty from where the user is registered.
/// </summary>
[JsonProperty(PropertyName = "RegistrationSource")]
public string RegistrationSource {get;set;}
/// <summary>
///
/// </summary>
[JsonProperty(PropertyName = "Roles")]
public List<string> Roles {get;set;}
/// <summary>
/// UID, the unified identifier for each user account
/// </summary>
[JsonProperty(PropertyName = "Uid")]
public string Uid {get;set;}
/// <summary>
/// Unverified Email Address
/// </summary>
[JsonProperty(PropertyName = "UnverifiedEmail")]
public List<Email> UnverifiedEmail {get;set;}
/// <summary>
/// Username of the user
/// </summary>
[JsonProperty(PropertyName = "UserName")]
public string UserName {get;set;}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// FeatureScheme
/// </summary>
public abstract class FeatureScheme : Scheme, IFeatureScheme
{
#region Fields
private readonly Dictionary<string, ArrayList> _cachedUniqueValues;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="FeatureScheme"/> class.
/// </summary>
protected FeatureScheme()
{
// This normally is replaced by a shape type specific collection, and is just a precaution.
AppearsInLegend = false;
_cachedUniqueValues = new Dictionary<string, ArrayList>();
EditorSettings = new FeatureEditorSettings();
Breaks = new List<Break>();
}
#endregion
#region Events
/// <summary>
/// Occurs when the deselect features context menu is clicked.
/// </summary>
public event EventHandler<ExpressionEventArgs> DeselectFeatures;
/// <summary>
/// Occurs
/// </summary>
public event EventHandler NonNumericField;
/// <summary>
/// Occurs when a category indicates that its filter expression should be used
/// to select its members.
/// </summary>
public event EventHandler<ExpressionEventArgs> SelectFeatures;
/// <summary>
/// Occurs when there are more than 1000 unique categories. If the "Cancel"
/// is set to true, then only the first 1000 categories are returned. Otherwise
/// it may allow the application to lock up, but will return all of them.
/// If this event is not handled, cancle is assumed to be true.
/// </summary>
public event EventHandler<CancelEventArgs> TooManyCategories;
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether or not the legend should draw this item as a categorical
/// tier in the legend. If so, it will allow the LegendText to be visible as a kind of group for the
/// categories. If not, the categories will appear directly below the layer.
/// </summary>
[Category("Behavior")]
[Description("Gets or sets a boolean that indicates whether or not the legend should draw this item as a grouping")]
[Serialize("AppearsInLegend")]
public bool AppearsInLegend { get; set; }
/// <summary>
/// Gets or sets the dialog settings
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new FeatureEditorSettings EditorSettings
{
get
{
return base.EditorSettings as FeatureEditorSettings;
}
set
{
base.EditorSettings = value;
}
}
/// <summary>
/// Gets an enumerable of LegendItems allowing the true members to be cycled through.
/// </summary>
[ShallowCopy]
public override IEnumerable<ILegendItem> LegendItems
{
get
{
if (AppearsInLegend)
{
return GetCategories();
}
return base.LegendItems;
}
}
/// <summary>
/// Gets the number of categories in this scheme.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual int NumCategories => 0;
/// <summary>
/// Gets or sets the UITypeEditor to use for editing this FeatureScheme.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public UITypeEditor PropertyEditor { get; protected set; }
#endregion
#region Methods
/// <summary>
/// Creates categories either based on unique values, or classification method.
/// If the method is
/// </summary>
/// <param name="table">The System.DataTable to that has the data values to use</param>
public void CreateCategories(IDataTable table)
{
string fieldName = EditorSettings.FieldName;
if (EditorSettings.ClassificationType == ClassificationType.Custom) return;
if (EditorSettings.ClassificationType == ClassificationType.UniqueValues)
{
CreateUniqueCategories(fieldName, table);
}
else
{
if (table.Columns[fieldName].DataType == typeof(string))
{
// MessageBox.Show(MessageStrings.FieldNotNumeric);
NonNumericField?.Invoke(this, EventArgs.Empty);
return;
}
if (GetUniqueValues(fieldName, table).Count <= EditorSettings.NumBreaks)
{
CreateUniqueCategories(fieldName, table);
}
else
{
GetValues(table);
CreateBreakCategories();
}
}
AppearsInLegend = true;
LegendText = fieldName;
}
/// <inheritdoc />
public void CreateCategories(IAttributeSource source, ICancelProgressHandler progressHandler)
{
string fieldName = EditorSettings.FieldName;
if (EditorSettings.ClassificationType == ClassificationType.Custom) return;
if (EditorSettings.ClassificationType == ClassificationType.UniqueValues)
{
CreateUniqueCategories(fieldName, source, progressHandler);
}
else
{
if (source.GetColumn(fieldName).DataType == typeof(string))
{
NonNumericField?.Invoke(this, EventArgs.Empty);
return;
}
if (!SufficientValues(fieldName, source, EditorSettings.NumBreaks))
{
CreateUniqueCategories(fieldName, source, progressHandler);
}
else
{
GetValues(source, progressHandler);
CreateBreakCategories();
}
}
AppearsInLegend = true;
LegendText = fieldName;
}
/// <summary>
/// Uses the settings on this scheme to create a random category.
/// </summary>
/// <returns>A new IFeatureCategory</returns>
/// <param name="filterExpression">The filter expression to use</param>
public virtual IFeatureCategory CreateRandomCategory(string filterExpression)
{
return null;
}
/// <summary>
/// This simply ensures that we are creating the appropriate empty filter expression version
/// of create random category.
/// </summary>
/// <returns>The created category.</returns>
public override ICategory CreateRandomCategory()
{
return CreateRandomCategory(string.Empty);
}
/// <summary>
/// When using this scheme to define the symbology, these individual categories will be referenced in order to
/// create genuine categories (that will be cached).
/// </summary>
/// <returns>The categories of the scheme.</returns>
public abstract IEnumerable<IFeatureCategory> GetCategories();
/// <summary>
/// Gets the values from a file based data source rather than an in memory object.
/// </summary>
/// <param name="source">Source to get the values from.</param>
/// <param name="progressHandler">The progress handler.</param>
public void GetValues(IAttributeSource source, ICancelProgressHandler progressHandler)
{
int pageSize = 100000;
Values = new List<double>();
string normField = EditorSettings.NormField;
string fieldName = EditorSettings.FieldName;
if (source.NumRows() < EditorSettings.MaxSampleCount)
{
int numPages = (int)Math.Ceiling((double)source.NumRows() / pageSize);
for (int ipage = 0; ipage < numPages; ipage++)
{
int numRows = (ipage == numPages - 1) ? source.NumRows() % pageSize : pageSize;
IDataTable table = source.GetAttributes(ipage * pageSize, numRows);
if (!string.IsNullOrEmpty(EditorSettings.ExcludeExpression))
{
IDataRow[] rows = table.Select("NOT (" + EditorSettings.ExcludeExpression + ")");
foreach (IDataRow row in rows)
{
double val;
if (!double.TryParse(row[fieldName].ToString(), out val)) continue;
if (double.IsNaN(val)) continue;
if (normField != null)
{
double norm;
if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val)) continue;
Values.Add(val / norm);
continue;
}
Values.Add(val);
}
}
else
{
foreach (IDataRow row in table.Rows)
{
double val;
if (!double.TryParse(row[fieldName].ToString(), out val)) continue;
if (double.IsNaN(val)) continue;
if (normField != null)
{
double norm;
if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val)) continue;
Values.Add(val / norm);
continue;
}
Values.Add(val);
}
}
}
}
else
{
Dictionary<int, double> randomValues = new Dictionary<int, double>();
pageSize = 10000;
int count = EditorSettings.MaxSampleCount;
Random rnd = new Random();
AttributePager ap = new AttributePager(source, pageSize);
int countPerPage = count / ap.NumPages();
ProgressMeter pm = new ProgressMeter(progressHandler, "Sampling " + count + " random values", count);
for (int iPage = 0; iPage < ap.NumPages(); iPage++)
{
for (int i = 0; i < countPerPage; i++)
{
double val;
double norm = 1;
int index;
bool failed = false;
do
{
index = rnd.Next(ap.StartIndex, ap.StartIndex + pageSize);
IDataRow dr = ap.Row(index);
if (!double.TryParse(dr[fieldName].ToString(), out val)) failed = true;
if (normField == null) continue;
if (!double.TryParse(dr[normField].ToString(), out norm)) failed = true;
}
while (randomValues.ContainsKey(index) || double.IsNaN(val) || failed);
if (normField != null)
{
Values.Add(val / norm);
}
else
{
Values.Add(val);
}
randomValues.Add(index, val);
pm.CurrentValue = i + (iPage * countPerPage);
}
if (progressHandler != null && progressHandler.Cancel)
{
break;
}
}
}
Values.Sort();
Statistics.Calculate(Values);
}
/// <summary>
/// Before attempting to create categories using a color ramp, this must be calculated
/// to updated the cache of values that govern statistics and break placement.
/// </summary>
/// <param name="table">The data Table to use.</param>
public void GetValues(IDataTable table)
{
Values = new List<double>();
string normField = EditorSettings.NormField;
string fieldName = EditorSettings.FieldName;
if (!string.IsNullOrEmpty(EditorSettings.ExcludeExpression))
{
IDataRow[] rows = table.Select("NOT (" + EditorSettings.ExcludeExpression + ")");
foreach (IDataRow row in rows)
{
if (rows.Length < EditorSettings.MaxSampleCount)
{
double val;
if (!double.TryParse(row[fieldName].ToString(), out val)) continue;
if (double.IsNaN(val)) continue;
if (normField != null)
{
double norm;
if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val)) continue;
Values.Add(val / norm);
continue;
}
Values.Add(val);
}
else
{
Dictionary<int, double> randomValues = new Dictionary<int, double>();
int count = EditorSettings.MaxSampleCount;
int max = rows.Length;
Random rnd = new Random();
for (int i = 0; i < count; i++)
{
double val;
double norm = 1;
int index;
bool failed = false;
do
{
index = rnd.Next(max);
if (!double.TryParse(rows[index][fieldName].ToString(), out val)) failed = true;
if (normField == null) continue;
if (!double.TryParse(rows[index][normField].ToString(), out norm)) failed = true;
}
while (randomValues.ContainsKey(index) || double.IsNaN(val) || failed);
if (normField != null)
{
Values.Add(val / norm);
}
else
{
Values.Add(val);
}
randomValues.Add(index, val);
}
}
}
Values.Sort();
Statistics.Calculate(Values);
return;
}
if (table.Rows.Count < EditorSettings.MaxSampleCount)
{
// Simply grab all the values
foreach (var row in table.Rows)
{
string sName, sNorm = string.Empty;
if (row is IDataRow)
{
sName = ((IDataRow)row)[fieldName].ToString();
if (normField != null)
sNorm = ((IDataRow)row)[normField].ToString();
}
else
{
sName = ((DataRow)row)[fieldName].ToString();
if (normField != null)
sNorm = ((DataRow)row)[normField].ToString();
}
double val;
if (!double.TryParse(sName, out val)) continue;
if (double.IsNaN(val)) continue;
if (normField == null)
{
Values.Add(val);
continue;
}
double norm;
if (!double.TryParse(sNorm, out norm) || double.IsNaN(val)) continue;
Values.Add(val / norm);
}
}
else
{
// Grab random samples
Dictionary<int, double> randomValues = new Dictionary<int, double>();
int count = EditorSettings.MaxSampleCount;
int max = table.Rows.Count;
Random rnd = new Random();
for (int i = 0; i < count; i++)
{
double val;
double norm = 1;
int index;
bool failed = false;
do
{
index = rnd.Next(max);
if (!double.TryParse(table.Rows[index][fieldName].ToString(), out val)) failed = true;
if (normField == null) continue;
if (!double.TryParse(table.Rows[index][normField].ToString(), out norm)) failed = true;
}
while (randomValues.ContainsKey(index) || double.IsNaN(val) || failed);
if (normField != null)
{
Values.Add(val / norm);
}
else
{
Values.Add(val);
}
randomValues.Add(index, val);
}
}
Values.Sort();
}
/// <summary>
/// Queries this layer and the entire parental tree up to the map frame to determine if
/// this layer is within the selected layers.
/// </summary>
/// <returns>True, if the layer is selected.</returns>
public bool IsWithinLegendSelection()
{
if (IsSelected) return true;
ILayer lyr = GetParentItem() as ILayer;
while (lyr != null)
{
if (lyr.IsSelected) return true;
lyr = lyr.GetParentItem() as ILayer;
}
return false;
}
/// <summary>
/// This keeps the existing categories, but uses the current scheme settings to apply
/// a new color to each of the symbols.
/// </summary>
public void RegenerateColors()
{
List<IFeatureCategory> cats = GetCategories().ToList();
List<Color> colors = GetColorSet(cats.Count);
int i = 0;
foreach (IFeatureCategory category in cats)
{
category.SetColor(colors[i]);
i++;
}
}
/// <summary>
/// Uses the current settings to generate a random color between the start and end color.
/// </summary>
/// <returns>A Randomly created color that is within the bounds of this scheme.</returns>
protected Color CreateRandomColor()
{
Random rnd = new Random(DateTime.Now.Millisecond);
return CreateRandomColor(rnd);
}
/// <summary>
/// Calculates the unique colors as a scheme.
/// </summary>
/// <param name="fs">The featureset with the data table definition</param>
/// <param name="uniqueField">The unique field</param>
/// <param name="categoryFunc">Func for creating category</param>
/// <returns>A hastable with the unique colors.</returns>
protected Hashtable GenerateUniqueColors(IFeatureSet fs, string uniqueField, Func<Color, IFeatureCategory> categoryFunc)
{
if (categoryFunc == null) throw new ArgumentNullException(nameof(categoryFunc));
var result = new Hashtable(); // a hashtable of colors
var dt = fs.DataTable;
var vals = new ArrayList();
var i = 0;
var rnd = new Random();
foreach (DataRow row in dt.Rows)
{
var ind = -1;
if (uniqueField != "FID")
{
if (!vals.Contains(row[uniqueField]))
{
ind = vals.Add(row[uniqueField]);
}
}
else
{
ind = vals.Add(i);
i++;
}
if (ind == -1) continue;
var item = vals[ind];
var c = rnd.NextColor();
while (result.ContainsKey(c))
{
c = rnd.NextColor();
}
var cat = categoryFunc(c);
string flt = "[" + uniqueField + "] = ";
if (uniqueField == "FID")
{
flt += item;
}
else
{
if (dt.Columns[uniqueField].DataType == typeof(string))
{
flt += "'" + item + "'";
}
else
{
flt += Convert.ToString(item, CultureInfo.InvariantCulture);
}
}
cat.FilterExpression = flt;
AddCategory(cat);
result.Add(c, item);
}
return result;
}
/// <summary>
/// This replaces the constant size calculation with a size
/// calculation that is appropriate for features.
/// </summary>
/// <param name="count">The integer count of the number of sizes to create.</param>
/// <returns>A list of double valued sizes.</returns>
protected override List<double> GetSizeSet(int count)
{
List<double> result = new List<double>();
if (EditorSettings.UseSizeRange)
{
double start = EditorSettings.StartSize;
double dr = EditorSettings.EndSize - start;
double dx = dr / count;
if (!EditorSettings.RampColors)
{
Random rnd = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < count; i++)
{
result.Add(start + (rnd.NextDouble() * dr));
}
}
else
{
for (int i = 0; i < count; i++)
{
result.Add(start + (i * dx));
}
}
}
else
{
Size2D sizes = new Size2D(2, 2);
IPointSymbolizer ps = EditorSettings.TemplateSymbolizer as IPointSymbolizer;
if (ps != null) sizes = ps.GetSize();
double size = Math.Max(sizes.Width, sizes.Height);
for (int i = 0; i < count; i++)
{
result.Add(size);
}
}
return result;
}
/// <summary>
/// Special handling of not copying the parent during a copy operation.
/// </summary>
/// <param name="copy">The copy.</param>
protected override void OnCopy(Descriptor copy)
{
FeatureScheme scheme = copy as FeatureScheme;
if (scheme?.SelectFeatures != null)
{
foreach (var handler in scheme.SelectFeatures.GetInvocationList())
{
scheme.SelectFeatures -= (EventHandler<ExpressionEventArgs>)handler;
}
}
// Disconnecting the parent prevents the immediate application of copied scheme categories to the original layer.
SuspendEvents();
base.OnCopy(copy);
ResumeEvents();
}
/// <summary>
/// Handles the special case of not copying the parent during an on copy properties operation
/// </summary>
/// <param name="source">The source to copy the properties from.</param>
protected override void OnCopyProperties(object source)
{
base.OnCopyProperties(source);
ILegendItem parent = GetParentItem();
IFeatureLayer p = parent as IFeatureLayer;
p?.ApplyScheme(this);
}
/// <summary>
/// Instructs the parent layer to select features matching the specified expression.
/// </summary>
/// <param name="sender">The object sender.</param>
/// <param name="e">The event args.</param>
protected virtual void OnDeselectFeatures(object sender, ExpressionEventArgs e)
{
ExpressionEventArgs myE = e;
if (EditorSettings.ExcludeExpression != null)
{
myE = new ExpressionEventArgs(myE.Expression + " AND NOT (" + EditorSettings.ExcludeExpression + ")");
}
DeselectFeatures?.Invoke(sender, myE);
}
/// <summary>
/// Instructs the parent layer to select features matching the specified expression.
/// </summary>
/// <param name="sender">The object sender.</param>
/// <param name="e">The event args.</param>
protected virtual void OnSelectFeatures(object sender, ExpressionEventArgs e)
{
ExpressionEventArgs myE = e;
if (EditorSettings.ExcludeExpression != null)
{
myE = new ExpressionEventArgs(myE.Expression + " AND NOT (" + EditorSettings.ExcludeExpression + ")");
}
SelectFeatures?.Invoke(sender, myE);
}
/// <summary>
/// Ensures that the parentage gets set properly in the event that
/// this scheme is not appearing in the legend.
/// </summary>
/// <param name="value">Legend item to set the parent for.</param>
protected override void OnSetParentItem(ILegendItem value)
{
base.OnSetParentItem(value);
if (AppearsInLegend) return;
IEnumerable<IFeatureCategory> categories = GetCategories();
foreach (IFeatureCategory category in categories)
{
category.SetParentItem(value);
}
}
/// <summary>
/// This checks the type of the specified field whether it's a string field.
/// </summary>
/// <param name="fieldName">Name of the field that gets checked.</param>
/// <param name="table">Table that contains the field.</param>
/// <returns>True, if the field is of type string.</returns>
private static bool CheckFieldType(string fieldName, IDataTable table)
{
return table.Columns[fieldName].DataType == typeof(string);
}
/// <summary>
/// This checks the type of the specified field whether it's a string field
/// </summary>
/// <param name="fieldName">Name of the field that gets checked.</param>
/// <param name="source">Attribute source that contains the field.</param>
/// <returns>True, if the field is of type boolean.</returns>
private static bool CheckFieldType(string fieldName, IAttributeSource source)
{
return source.GetColumn(fieldName).DataType == typeof(string);
}
/// <summary>
/// Gets a list of all unique values of the attribute field.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <param name="table">Table that contains the field.</param>
/// <returns>A list of the unique values of the attribute field.</returns>
private static List<Break> GetUniqueValues(string fieldName, IDataTable table)
{
HashSet<object> lst = new HashSet<object>();
bool containsNull = false;
foreach (object row in table.Rows)
{
object val = null;
if (row is IDataRow idr)
val = idr[fieldName];
else if (row is DataRow dr)
val = dr[fieldName];
if (val == null || val is DBNull || val.ToString() == string.Empty)
{
containsNull = true;
}
else if (!lst.Contains(val))
{
lst.Add(val);
}
}
List<Break> result = new List<Break>();
if (containsNull) result.Add(new Break("[NULL]"));
foreach (object item in lst.OrderBy(o => o))
{
result.Add(new Break(string.Format(CultureInfo.InvariantCulture, "{0}", item))); // Changed by jany_ (2015-07-27) use InvariantCulture because this is used in Datatable.Select in FeatureCategoryControl and causes error when german localization is used
}
return result;
}
/// <summary>
/// Checks whether the source contains more than numValues different values in the given field.
/// </summary>
/// <param name="fieldName">Name of the field that gets checked.</param>
/// <param name="source">Attribute source that contains the field.</param>
/// <param name="numValues">Minimal number of values that should exist.</param>
/// <returns>True, if more than num values exist.</returns>
private static bool SufficientValues(string fieldName, IAttributeSource source, int numValues)
{
ArrayList lst = new ArrayList();
AttributeCache ac = new AttributeCache(source, numValues);
foreach (Dictionary<string, object> dr in ac)
{
object val = dr[fieldName] ?? "[NULL]";
if (val.ToString() == string.Empty) val = "[NULL]";
if (lst.Contains(val)) continue;
lst.Add(val);
if (lst.Count > numValues) return true;
}
return false;
}
private void CreateUniqueCategories(string fieldName, IAttributeSource source, ICancelProgressHandler progressHandler)
{
Breaks = GetUniqueValues(fieldName, source, progressHandler);
string fieldExpression = "[" + fieldName.ToUpper() + "]";
ClearCategories();
bool isStringField = CheckFieldType(fieldName, source);
ProgressMeter pm = new ProgressMeter(progressHandler, "Building Feature Categories", Breaks.Count);
List<double> sizeRamp = GetSizeSet(Breaks.Count);
List<Color> colorRamp = GetColorSet(Breaks.Count);
for (int colorIndex = 0; colorIndex < Breaks.Count; colorIndex++)
{
Break brk = Breaks[colorIndex];
// get the color for the category
Color randomColor = colorRamp[colorIndex];
double size = sizeRamp[colorIndex];
IFeatureCategory cat = CreateNewCategory(randomColor, size) as IFeatureCategory;
if (cat != null)
{
cat.LegendText = brk.Name;
if (isStringField) cat.FilterExpression = fieldExpression + "= '" + brk.Name.Replace("'", "''") + "'";
else cat.FilterExpression = fieldExpression + "=" + brk.Name;
AddCategory(cat);
}
colorIndex++;
pm.CurrentValue = colorIndex;
}
pm.Reset();
}
private void CreateUniqueCategories(string fieldName, IDataTable table)
{
Breaks = GetUniqueValues(fieldName, table);
List<double> sizeRamp = GetSizeSet(Breaks.Count);
List<Color> colorRamp = GetColorSet(Breaks.Count);
string fieldExpression = "[" + fieldName.ToUpper() + "]";
ClearCategories();
bool isStringField = CheckFieldType(fieldName, table);
int colorIndex = 0;
foreach (Break brk in Breaks)
{
// get the color for the category
Color randomColor = colorRamp[colorIndex];
double size = sizeRamp[colorIndex];
IFeatureCategory cat = CreateNewCategory(randomColor, size) as IFeatureCategory;
if (cat != null)
{
cat.LegendText = brk.Name;
if (isStringField) cat.FilterExpression = fieldExpression + "= '" + brk.Name.Replace("'", "''") + "'";
else cat.FilterExpression = fieldExpression + "=" + brk.Name;
if (cat.FilterExpression != null)
{
if (cat.FilterExpression.Contains("=[NULL]"))
{
cat.FilterExpression = cat.FilterExpression.Replace("=[NULL]", " is NULL");
}
else if (cat.FilterExpression.Contains("= '[NULL]'"))
{
cat.FilterExpression = cat.FilterExpression.Replace("= '[NULL]'", " is NULL");
}
}
AddCategory(cat);
}
colorIndex++;
}
}
/// <summary>
/// Gets a list of all unique values of the attribute field.
/// </summary>
/// <param name="fieldName">Name of the field that gets checked.</param>
/// <param name="source">Attribute source that contains the field.</param>
/// <param name="progressHandler">The progress handler.</param>
/// <returns>A list with the unique values.</returns>
private List<Break> GetUniqueValues(string fieldName, IAttributeSource source, ICancelProgressHandler progressHandler)
{
ArrayList lst;
bool hugeCountOk = false;
if (_cachedUniqueValues.ContainsKey(fieldName))
{
lst = _cachedUniqueValues[fieldName];
}
else
{
lst = new ArrayList();
AttributePager ap = new AttributePager(source, 5000);
ProgressMeter pm = new ProgressMeter(progressHandler, "Discovering Unique Values", source.NumRows());
for (int row = 0; row < source.NumRows(); row++)
{
object val = ap.Row(row)[fieldName] ?? "[NULL]";
if (val.ToString() == string.Empty) val = "[NULL]";
if (lst.Contains(val)) continue;
lst.Add(val);
if (lst.Count > 1000 && !hugeCountOk)
{
CancelEventArgs args = new CancelEventArgs(true);
TooManyCategories?.Invoke(this, args);
if (args.Cancel) break;
hugeCountOk = true;
}
pm.CurrentValue = row;
if (progressHandler.Cancel) break;
}
lst.Sort();
if (lst.Count < EditorSettings.MaxSampleCount)
{
_cachedUniqueValues[fieldName] = lst;
}
}
List<Break> result = new List<Break>();
if (lst != null)
{
foreach (object item in lst)
{
result.Add(new Break(item.ToString()));
}
}
return result;
}
#endregion
}
}
| |
/*
* The author of this software is Steven Fortune. Copyright (c) 1994 by AT&T
* Bell Laboratories.
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Delaunay
{
public class Voronoi : IDisposable
{
private SiteList _sites;
private Dictionary<PointF, Site> _sitesIndexedByLocation;
private List<Triangle> _triangles;
private List<Edge> _edges;
// TODO generalize this so it doesn't have to be a RectangleF;
// then we can make the fractal voronois-within-voronois
private RectangleF _plotBounds;
public RectangleF plotBounds
{
get
{
return _plotBounds;
}
}
public void Dispose()
{
int i, n;
if (_sites != null)
{
_sites.Dispose();
_sites = null;
}
if (_triangles != null)
{
n = _triangles.Count;
for (i = 0; i < n; ++i)
{
_triangles[i].Dispose();
}
_triangles.Clear();
_triangles = null;
}
if (_edges != null)
{
n = _edges.Count;
for (i = 0; i < n; ++i)
{
_edges[i].Dispose();
}
_edges.Clear();
_edges = null;
}
_plotBounds = new RectangleF();
_sitesIndexedByLocation = null;
}
public Voronoi(List<PointF> PointFs, List<uint> colors, RectangleF plotBounds)
{
_sites = new SiteList();
_sitesIndexedByLocation = new Dictionary<PointF, Site>();
AddSites(PointFs, colors);
_plotBounds = plotBounds;
_triangles = new List<Triangle>();
_edges = new List<Edge>();
FortunesAlgorithm();
}
private void AddSites(List<PointF> PointFs, List<uint> colors)
{
uint length = (uint)PointFs.Count;
for (uint i = 0; i < length; ++i)
{
AddSite(PointFs[(int)i], colors != null ? colors[(int)i] : 0, (int)i);
}
}
private void AddSite(PointF p, uint color, int index)
{
//throw new NotImplementedException("This was modified, might not work");
System.Random random = new System.Random();
float weight = (float)random.NextDouble() * 100;
Site site = Site.Create(p, index, weight, color);
_sites.Push(site);
_sitesIndexedByLocation[p] = site;
}
public List<Edge> Edges()
{
return _edges;
}
public List<PointF> Region(PointF p)
{
Site site = _sitesIndexedByLocation[p];
if (site == null)
{
return new List<PointF>();
}
return site.Region(_plotBounds);
}
// TODO: bug: if you call this before you call region(), something goes wrong :(
public List<PointF> NeighborSitesForSite(PointF coord)
{
List<PointF> PointFs = new List<PointF>();
Site site = _sitesIndexedByLocation[coord];
if (site == null)
{
return PointFs;
}
List<Site> sites = site.NeighborSites();
foreach (Site neighbor in sites)
{
PointFs.Add(neighbor.Coord());
}
return PointFs;
}
public List<Circle> Circles()
{
return _sites.Circles();
}
public List<LineSegment> VoronoiBoundaryForSite(PointF coord)
{
return visibleLineSegmentsClass.VisibleLineSegments(selectEdgesForSitePointFClass.SelectEdgesForSitePointF(coord, _edges));
}
public List<LineSegment> DelaunayLinesForSite(PointF coord)
{
return DelaunayLinesForEdgesClass.DelaunayLinesForEdges(selectEdgesForSitePointFClass.SelectEdgesForSitePointF(coord, _edges));
}
public List<LineSegment> VoronoiDiagram()
{
return visibleLineSegmentsClass.VisibleLineSegments(_edges);
}
public List<LineSegment> DelaunayTriangulation()
{
return DelaunayTriangulation(null);
}
public List<LineSegment> DelaunayTriangulation(BitmapData keepOutMask)
{
return DelaunayLinesForEdgesClass.DelaunayLinesForEdges(selectNonIntersectingEdgesClass.SelectNonIntersectingEdges(keepOutMask, _edges));
}
public List<LineSegment> Hull()
{
return DelaunayLinesForEdgesClass.DelaunayLinesForEdges(HullEdges());
}
private List<Edge> HullEdges()
{
return _edges.Filter(MyTestHullEdges);
}
bool MyTestHullEdges(Edge edge, int index, List<Edge> vector)
{
return (edge.IsPartOfConvexHull());
}
public List<PointF> HullPointFsInOrder()
{
List<Edge> hullEdges = HullEdges();
List<PointF> PointFs = new List<PointF>();
if (hullEdges.Count == 0)
{
return PointFs;
}
EdgeReorderer reorderer = new EdgeReorderer(hullEdges, typeof(Site));
hullEdges = reorderer.Edges;
List<LR> orientations = reorderer.EdgeOrientations;
reorderer.Dispose();
LR orientation;
int n = hullEdges.Count;
for (int i = 0; i < n; ++i)
{
Edge edge = hullEdges[i];
orientation = orientations[i];
PointFs.Add(edge.GetSite(orientation).Coord());
}
return PointFs;
}
public List<LineSegment> SpanningTree(BitmapData keepOutMask)
{
return SpanningTree("minimum", keepOutMask);
}
public List<LineSegment> SpanningTree()
{
return SpanningTree("minimum", null);
}
public List<LineSegment> SpanningTree(string type)
{
return SpanningTree(type, null);
}
public List<LineSegment> SpanningTree(string type, BitmapData keepOutMask)
{
List<Edge> edges = selectNonIntersectingEdgesClass.SelectNonIntersectingEdges(keepOutMask, _edges);
List<LineSegment> segments = DelaunayLinesForEdgesClass.DelaunayLinesForEdges(edges);
return Kruskal.GetKruskal(segments, type);
}
public List<List<PointF>> Regions()
{
return _sites.Regions(_plotBounds);
}
public List<uint> SiteColors()
{
return SiteColors(null);
}
public List<uint> SiteColors(BitmapData referenceImage)
{
return _sites.SiteColors(referenceImage);
}
/**
*
* @param proximityMap a BitmapData whose regions are filled with the site index values; see PlanePointFsCanvas::fillRegions()
* @param x
* @param y
* @return coordinates of nearest Site to (x, y)
*
*/
public PointF NearestSitePointF(BitmapData proximityMap, float x, float y)
{
return _sites.NearestSitePointF(proximityMap, x, y);
}
public List<PointF> SiteCoords()
{
return _sites.SiteCoords();
}
private void FortunesAlgorithm()
{
Site newSite, bottomSite, topSite, tempSite;
Vertex v, vertex;
PointF newintstar = PointF.Empty;
LR leftRight;
Halfedge lbnd, rbnd, llbnd, rrbnd, bisector;
Edge edge;
RectangleF dataBounds = _sites.GetSitesBounds();
int sqrt_nsites = (int)(Math.Sqrt(_sites.Length + 4));
HalfedgePriorityQueue heap = new HalfedgePriorityQueue(dataBounds.Y, dataBounds.Height, sqrt_nsites);
EdgeList edgeList = new EdgeList(dataBounds.X, dataBounds.Width, sqrt_nsites);
List<Halfedge> halfEdges = new List<Halfedge>();
List<Vertex> vertices = new List<Vertex>();
Site bottomMostSite = _sites.Next();
newSite = _sites.Next();
for (; ; )
{
if (heap.Empty() == false)
{
newintstar = heap.Min();
}
if (newSite != null
&& (heap.Empty() || CompareByYThenX(newSite, newintstar) < 0))
{
/* new site is smallest */
//trace("smallest: new site " + newSite);
// Step 8:
lbnd = edgeList.EdgeListLeftNeighbor(newSite.Coord()); // the Halfedge just to the left of newSite
//trace("lbnd: " + lbnd);
rbnd = lbnd.edgeListRightNeighbor; // the Halfedge just to the right
//trace("rbnd: " + rbnd);
bottomSite = RightRegion(lbnd, bottomMostSite); // this is the same as leftRegion(rbnd)
// this Site determines the region containing the new site
//trace("new Site is in region of existing site: " + bottomSite);
// Step 9:
edge = Edge.CreateBisectingEdge(bottomSite, newSite);
//trace("new edge: " + edge);
_edges.Add(edge);
bisector = Halfedge.Create(edge, LR.LEFT);
halfEdges.Add(bisector);
// inserting two Halfedges into edgeList static readonlyitutes Step 10:
// insert bisector to the right of lbnd:
edgeList.Insert(lbnd, bisector);
// first half of Step 11:
if ((vertex = Vertex.Intersect(lbnd, bisector)) != null)
{
vertices.Add(vertex);
heap.Remove(lbnd);
lbnd.vertex = vertex;
lbnd.ystar = vertex.Y + newSite.Dist(vertex);
heap.Insert(lbnd);
}
lbnd = bisector;
bisector = Halfedge.Create(edge, LR.RIGHT);
halfEdges.Add(bisector);
// second Halfedge for Step 10:
// insert bisector to the right of lbnd:
edgeList.Insert(lbnd, bisector);
// second half of Step 11:
if ((vertex = Vertex.Intersect(bisector, rbnd)) != null)
{
vertices.Add(vertex);
bisector.vertex = vertex;
bisector.ystar = vertex.Y + newSite.Dist(vertex);
heap.Insert(bisector);
}
newSite = _sites.Next();
}
else if (heap.Empty() == false)
{
/* intersection is smallest */
lbnd = heap.ExtractMin();
llbnd = lbnd.edgeListLeftNeighbor;
rbnd = lbnd.edgeListRightNeighbor;
rrbnd = rbnd.edgeListRightNeighbor;
bottomSite = LeftRegion(lbnd, bottomMostSite);
topSite = RightRegion(rbnd, bottomMostSite);
// these three sites define a Delaunay triangle
// (not actually using these for anything...)
//_triangles.Add(new Triangle(bottomSite, topSite, rightRegion(lbnd)));
v = lbnd.vertex;
v.SetIndex();
lbnd.edge.SetVertex(lbnd.leftRight, v);
rbnd.edge.SetVertex(rbnd.leftRight, v);
edgeList.Remove(lbnd);
heap.Remove(rbnd);
edgeList.Remove(rbnd);
leftRight = LR.LEFT;
if (bottomSite.Y > topSite.Y)
{
tempSite = bottomSite; bottomSite = topSite; topSite = tempSite; leftRight = LR.RIGHT;
}
edge = Edge.CreateBisectingEdge(bottomSite, topSite);
_edges.Add(edge);
bisector = Halfedge.Create(edge, leftRight);
halfEdges.Add(bisector);
edgeList.Insert(llbnd, bisector);
edge.SetVertex(LR.Other(leftRight), v);
if ((vertex = Vertex.Intersect(llbnd, bisector)) != null)
{
vertices.Add(vertex);
heap.Remove(llbnd);
llbnd.vertex = vertex;
llbnd.ystar = vertex.Y + bottomSite.Dist(vertex);
heap.Insert(llbnd);
}
if ((vertex = Vertex.Intersect(bisector, rrbnd)) != null)
{
vertices.Add(vertex);
bisector.vertex = vertex;
bisector.ystar = vertex.Y + bottomSite.Dist(vertex);
heap.Insert(bisector);
}
}
else
{
break;
}
}
// heap should be empty now
heap.Dispose();
edgeList.Dispose();
foreach (Halfedge halfEdge in halfEdges)
{
halfEdge.ReallyDispose();
}
halfEdges.Clear();
// we need the vertices to clip the edges
foreach (Edge edge2 in _edges)
{
edge2.ClipVertices(_plotBounds);
}
// but we don't actually ever use them again!
foreach (Vertex vertex2 in vertices)
{
vertex2.Dispose();
}
vertices.Clear();
}
Site LeftRegion(Halfedge he, Site bottomMostSite)
{
Edge edge = he.edge;
if (edge == null)
{
return bottomMostSite;
}
return edge.GetSite(he.leftRight);
}
Site RightRegion(Halfedge he, Site bottomMostSite)
{
Edge edge = he.edge;
if (edge == null)
{
return bottomMostSite;
}
return edge.GetSite(LR.Other(he.leftRight));
}
internal static float CompareByYThenX(Site s1, Site s2)
{
if (s1.Y < s2.Y) return -1;
if (s1.Y > s2.Y) return 1;
if (s1.X < s2.X) return -1;
if (s1.X > s2.X) return 1;
return 0;
}
internal static float CompareByYThenX(Site s1, PointF s2)
{
if (s1.Y < s2.Y) return -1;
if (s1.Y > s2.Y) return 1;
if (s1.X < s2.X) return -1;
if (s1.X > s2.X) return 1;
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SimpleCrm.Config;
using SimpleCrm.Manager;
namespace SimpleCrm.Utils
{
/// <summary>
/// Pagination control for displaying records number and button.
/// </summary>
[DefaultEvent("ScrollPage")]
public partial class PageControl : UserControl
{
/// <summary>
/// Initializes a new instance of the <see cref="PageControl"/> class.
/// </summary>
public PageControl()
{
InitializeComponent();
}
private int totalRecords = 0;
int from = 0;
int to = 0;
private int lastPageNo = 99999;
/// <summary>
/// Gets or sets the total records.
/// </summary>
/// <value>The total records.</value>
[Browsable(false)]
public int TotalRecords
{
get { return totalRecords; }
set
{
if (value < 0)
{
value = 0;
}
totalRecords = value;
lastPageNo = (int)Math.Ceiling(totalRecords * 1.0 / this.pageSize);
this.txtPageNumber.MaxValue = lastPageNo;
this.txtPageNumber.Value = this.currentPage;
if (lastPageNo < this.currentPage && this.currentPage != 1)
{
//last page < current page means user changed condition, but click scroll button to searching. if current page no
// is greater than all page number in data, the searching result will be empty.
this.currentPage = lastPageNo + 1;
this.txtPageNumber.ValueObject = null;
}
SetControlsStatus();
}
}
private int currentPage = 1;
/// <summary>
/// Gets or sets the current page.
/// </summary>
/// <value>The current page.</value>
[Browsable(false)]
public int CurrentPage
{
get { return currentPage; }
set
{
if (value <= 0)
{
value = 1;
}
currentPage = value;
}
}
/// <summary>
/// Gets the start from record.
/// </summary>
/// <value>The start from rec.</value>
[Browsable(false)]
public int StartFromRec
{
get { return (currentPage - 1) * this.pageSize; }
}
private int pageSize = 10;
/// <summary>
/// Gets or sets the size of the page.
/// </summary>
/// <value>The size of the page.</value>
[Browsable(false)]
public int PageSize
{
get { return pageSize; }
set
{
if (value > 0)
{
pageSize = value;
}
if (value >= MAX_PAGE_SIZE)
{
btnFirst.Visible = false;
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLast.Visible = false;
btnGo.Visible = false;
txtPageNumber.Visible = false;
this.TabStop = false;
}
else
{
btnFirst.Visible = true;
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLast.Visible = true;
btnGo.Visible = true;
txtPageNumber.Visible = true;
this.TabStop = true;
}
}
}
private event EventHandler<PageControlArgs> scrollPage;
private int MAX_PAGE_SIZE = 9999;
/// <summary>
/// Occurs when [scroll page].
/// </summary>
public event EventHandler<PageControlArgs> ScrollPage
{
add { scrollPage += value; }
remove { scrollPage -= value; }
}
/// <summary>
/// Raises the scroll page event.
/// </summary>
/// <param name="args">The args.</param>
private void RaiseScrollPageEvent(PageControlArgs args)
{
if (scrollPage != null)
{
scrollPage(this, args);
}
}
/// <summary>
/// Handles the Click event of the btnFirst control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void btnFirst_Click(object sender, EventArgs e)
{
this.currentPage = 1;
this.RaiseScrollPageEvent(new PageControlArgs());
SetControlsStatus();
}
/// <summary>
/// Handles the Click event of the btnPrevious control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void btnPrevious_Click(object sender, EventArgs e)
{
this.currentPage--;
this.RaiseScrollPageEvent(new PageControlArgs());
SetControlsStatus();
}
/// <summary>
/// Handles the Click event of the btnNext control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void btnNext_Click(object sender, EventArgs e)
{
this.currentPage++;
this.RaiseScrollPageEvent(new PageControlArgs());
SetControlsStatus();
}
/// <summary>
/// Handles the Click event of the btnLast control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void btnLast_Click(object sender, EventArgs e)
{
this.currentPage = lastPageNo;
this.RaiseScrollPageEvent(new PageControlArgs());
SetControlsStatus();
}
/// <summary>
/// Sets the controls status.
/// </summary>
public void SetControlsStatus()
{
this.btnFirst.Enabled = true;
this.btnPrevious.Enabled = true;
this.btnNext.Enabled = true;
this.btnLast.Enabled = true;
this.TabStop = true;
this.txtPageNumber.Enabled = false;
if (this.totalRecords == 0)
{
this.btnFirst.Enabled = false;
this.btnPrevious.Enabled = false;
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
this.btnGo.Enabled = false;
this.txtPageNumber.Text = "";
this.TabStop = false;
}
else
{
this.txtPageNumber.Enabled = true;
this.btnGo.Enabled = this.txtPageNumber.ValueObject != null
&& this.txtPageNumber.Value != this.currentPage
&& this.txtPageNumber.Value > 0;
if (lastPageNo <= this.currentPage)
{
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
if (this.currentPage == 1)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
}
}
from = 0;
to = 0;
if (totalRecords > 0)
{
if (pageSize < MAX_PAGE_SIZE)
{
from = pageSize * (currentPage - 1) + 1;
to = pageSize * (currentPage);
if (to > totalRecords)
{
to = totalRecords;
}
if (from > totalRecords)
{
from = 0;
to = 0;
}
}
else
{
from = 1;
to = totalRecords;
}
}
// lblResultStatus.Text = string.Format("Record {0}-{1} (Total Record:{2})",
// from,to,totalRecords);
lblResultStatus.Text = string.Format(ErrorCode.TOTAL_REC,
from, to, totalRecords);
}
private void btnGo_Click(object sender, EventArgs e)
{
if (txtPageNumber.ValueObject != null && txtPageNumber.Value > 0)
{
this.currentPage = txtPageNumber.Value;
RaiseScrollPageEvent(new PageControlArgs());
SetControlsStatus();
}
}
private void txtPageNumber_ValueChanged(object sender, EventArgs e)
{
if (this.txtPageNumber.ValueObject == null
|| this.txtPageNumber.Value == 0m
|| this.txtPageNumber.Value == this.currentPage)
{
this.btnGo.Enabled = false;
}
else
{
this.btnGo.Enabled = true;
}
}
private void PageControl_Load(object sender, EventArgs e)
{
if (AppConfigManager.AppConfig != null)
{
this.pageSize = AppConfigManager.AppConfig.PageSize;
}
}
}
/// <summary>
/// Arguments of Page Control
/// </summary>
public class PageControlArgs : EventArgs
{
// private PageStatus _page;
// public PageStatus PageStatus
// {
// get { return _page; }
// set { _page = value; }
// }
// public PageControlArgs(PageStatus pageStatus)
// {
// _page = pageStatus;
// }
//}
}
}
| |
using System;
using System.Diagnostics;
namespace Lucene.Net.Codecs
{
/*
* 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 BufferedIndexInput = Lucene.Net.Store.BufferedIndexInput;
using IndexInput = Lucene.Net.Store.IndexInput;
using MathUtil = Lucene.Net.Util.MathUtil;
/// <summary>
/// This abstract class reads skip lists with multiple levels.
/// <para/>
/// See <see cref="MultiLevelSkipListWriter"/> for the information about the encoding
/// of the multi level skip lists.
/// <para/>
/// Subclasses must implement the abstract method <see cref="ReadSkipData(int, IndexInput)"/>
/// which defines the actual format of the skip data.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class MultiLevelSkipListReader : IDisposable
{
/// <summary>
/// The maximum number of skip levels possible for this index. </summary>
protected internal int m_maxNumberOfSkipLevels;
// number of levels in this skip list
private int numberOfSkipLevels;
// Expert: defines the number of top skip levels to buffer in memory.
// Reducing this number results in less memory usage, but possibly
// slower performance due to more random I/Os.
// Please notice that the space each level occupies is limited by
// the skipInterval. The top level can not contain more than
// skipLevel entries, the second top level can not contain more
// than skipLevel^2 entries and so forth.
private int numberOfLevelsToBuffer = 1;
private int docCount;
private bool haveSkipped;
/// <summary>
/// SkipStream for each level. </summary>
private IndexInput[] skipStream;
/// <summary>
/// The start pointer of each skip level. </summary>
private long[] skipPointer;
/// <summary>
/// SkipInterval of each level. </summary>
private int[] skipInterval;
/// <summary>
/// Number of docs skipped per level. </summary>
private int[] numSkipped;
/// <summary>
/// Doc id of current skip entry per level. </summary>
protected internal int[] m_skipDoc;
/// <summary>
/// Doc id of last read skip entry with docId <= target. </summary>
private int lastDoc;
/// <summary>
/// Child pointer of current skip entry per level. </summary>
private long[] childPointer;
/// <summary>
/// childPointer of last read skip entry with docId <=
/// target.
/// </summary>
private long lastChildPointer;
private bool inputIsBuffered;
private readonly int skipMultiplier;
/// <summary>
/// Creates a <see cref="MultiLevelSkipListReader"/>. </summary>
protected MultiLevelSkipListReader(IndexInput skipStream, int maxSkipLevels, int skipInterval, int skipMultiplier)
{
this.skipStream = new IndexInput[maxSkipLevels];
this.skipPointer = new long[maxSkipLevels];
this.childPointer = new long[maxSkipLevels];
this.numSkipped = new int[maxSkipLevels];
this.m_maxNumberOfSkipLevels = maxSkipLevels;
this.skipInterval = new int[maxSkipLevels];
this.skipMultiplier = skipMultiplier;
this.skipStream[0] = skipStream;
this.inputIsBuffered = (skipStream is BufferedIndexInput);
this.skipInterval[0] = skipInterval;
for (int i = 1; i < maxSkipLevels; i++)
{
// cache skip intervals
this.skipInterval[i] = this.skipInterval[i - 1] * skipMultiplier;
}
m_skipDoc = new int[maxSkipLevels];
}
/// <summary>
/// Creates a <see cref="MultiLevelSkipListReader"/>, where
/// <see cref="skipInterval"/> and <see cref="skipMultiplier"/> are
/// the same.
/// </summary>
protected internal MultiLevelSkipListReader(IndexInput skipStream, int maxSkipLevels, int skipInterval)
: this(skipStream, maxSkipLevels, skipInterval, skipInterval)
{
}
/// <summary>
/// Returns the id of the doc to which the last call of <see cref="SkipTo(int)"/>
/// has skipped.
/// </summary>
public virtual int Doc
{
get
{
return lastDoc;
}
}
/// <summary>
/// Skips entries to the first beyond the current whose document number is
/// greater than or equal to <paramref name="target"/>. Returns the current doc count.
/// </summary>
public virtual int SkipTo(int target)
{
if (!haveSkipped)
{
// first time, load skip levels
LoadSkipLevels();
haveSkipped = true;
}
// walk up the levels until highest level is found that has a skip
// for this target
int level = 0;
while (level < numberOfSkipLevels - 1 && target > m_skipDoc[level + 1])
{
level++;
}
while (level >= 0)
{
if (target > m_skipDoc[level])
{
if (!LoadNextSkip(level))
{
continue;
}
}
else
{
// no more skips on this level, go down one level
if (level > 0 && lastChildPointer > skipStream[level - 1].GetFilePointer())
{
SeekChild(level - 1);
}
level--;
}
}
return numSkipped[0] - skipInterval[0] - 1;
}
private bool LoadNextSkip(int level)
{
// we have to skip, the target document is greater than the current
// skip list entry
SetLastSkipData(level);
numSkipped[level] += skipInterval[level];
if (numSkipped[level] > docCount)
{
// this skip list is exhausted
m_skipDoc[level] = int.MaxValue;
if (numberOfSkipLevels > level)
{
numberOfSkipLevels = level;
}
return false;
}
// read next skip entry
m_skipDoc[level] += ReadSkipData(level, skipStream[level]);
if (level != 0)
{
// read the child pointer if we are not on the leaf level
childPointer[level] = skipStream[level].ReadVInt64() + skipPointer[level - 1];
}
return true;
}
/// <summary>
/// Seeks the skip entry on the given level. </summary>
protected virtual void SeekChild(int level)
{
skipStream[level].Seek(lastChildPointer);
numSkipped[level] = numSkipped[level + 1] - skipInterval[level + 1];
m_skipDoc[level] = lastDoc;
if (level > 0)
{
childPointer[level] = skipStream[level].ReadVInt64() + skipPointer[level - 1];
}
}
/// <summary>
/// Disposes all resources used by this object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes all resources used by this object. Subclasses may override
/// to dispose their own resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
for (int i = 1; i < skipStream.Length; i++)
{
if (skipStream[i] != null)
{
skipStream[i].Dispose();
}
}
}
}
/// <summary>
/// Initializes the reader, for reuse on a new term. </summary>
public virtual void Init(long skipPointer, int df)
{
this.skipPointer[0] = skipPointer;
this.docCount = df;
Debug.Assert(skipPointer >= 0 && skipPointer <= skipStream[0].Length, "invalid skip pointer: " + skipPointer + ", length=" + skipStream[0].Length);
Array.Clear(m_skipDoc, 0, m_skipDoc.Length);
Array.Clear(numSkipped, 0, numSkipped.Length);
Array.Clear(childPointer, 0, childPointer.Length);
haveSkipped = false;
for (int i = 1; i < numberOfSkipLevels; i++)
{
skipStream[i] = null;
}
}
/// <summary>
/// Loads the skip levels. </summary>
private void LoadSkipLevels()
{
if (docCount <= skipInterval[0])
{
numberOfSkipLevels = 1;
}
else
{
numberOfSkipLevels = 1 + MathUtil.Log(docCount / skipInterval[0], skipMultiplier);
}
if (numberOfSkipLevels > m_maxNumberOfSkipLevels)
{
numberOfSkipLevels = m_maxNumberOfSkipLevels;
}
skipStream[0].Seek(skipPointer[0]);
int toBuffer = numberOfLevelsToBuffer;
for (int i = numberOfSkipLevels - 1; i > 0; i--)
{
// the length of the current level
long length = skipStream[0].ReadVInt64();
// the start pointer of the current level
skipPointer[i] = skipStream[0].GetFilePointer();
if (toBuffer > 0)
{
// buffer this level
skipStream[i] = new SkipBuffer(skipStream[0], (int)length);
toBuffer--;
}
else
{
// clone this stream, it is already at the start of the current level
skipStream[i] = (IndexInput)skipStream[0].Clone();
if (inputIsBuffered && length < BufferedIndexInput.BUFFER_SIZE)
{
((BufferedIndexInput)skipStream[i]).SetBufferSize((int)length);
}
// move base stream beyond the current level
skipStream[0].Seek(skipStream[0].GetFilePointer() + length);
}
}
// use base stream for the lowest level
skipPointer[0] = skipStream[0].GetFilePointer();
}
/// <summary>
/// Subclasses must implement the actual skip data encoding in this method.
/// </summary>
/// <param name="level"> The level skip data shall be read from. </param>
/// <param name="skipStream"> The skip stream to read from. </param>
protected abstract int ReadSkipData(int level, IndexInput skipStream);
/// <summary>
/// Copies the values of the last read skip entry on this <paramref name="level"/>. </summary>
protected virtual void SetLastSkipData(int level)
{
lastDoc = m_skipDoc[level];
lastChildPointer = childPointer[level];
}
/// <summary>
/// Used to buffer the top skip levels. </summary>
private sealed class SkipBuffer : IndexInput
{
private byte[] data;
private long pointer;
private int pos;
internal SkipBuffer(IndexInput input, int length)
: base("SkipBuffer on " + input)
{
data = new byte[length];
pointer = input.GetFilePointer();
input.ReadBytes(data, 0, length);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
data = null;
}
}
public override long GetFilePointer()
{
return pointer + pos;
}
public override long Length
{
get { return data.Length; }
}
public override byte ReadByte()
{
return data[pos++];
}
public override void ReadBytes(byte[] b, int offset, int len)
{
Array.Copy(data, pos, b, offset, len);
pos += len;
}
public override void Seek(long pos)
{
this.pos = (int)(pos - pointer);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <OWNER>[....]</OWNER>
//
// <copyright file="CodeGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System;
using System.CodeDom;
using System.Collections;
using System.Globalization;
using System.IO;
// This is an internal helper class which walks the tree for the ValidateIdentifiers API in the CodeGenerator. For the most part the generator code has been copied and
// turned into validation code. This code will only validate identifiers and types to check that they are ok in a language
// independent manner. By default, this will not be turned on. This gives clients of codedom a mechanism to
// protect themselves against certain types of code injection attacks (using identifier and type names).
// You can pass in any node in the tree that is a subclass of CodeObject.
internal class CodeValidator
{
private static readonly char[] newLineChars = new char[] {'\r', '\n', '\u2028', '\u2029', '\u0085'};
internal void ValidateIdentifiers(CodeObject e) {
if (e is CodeCompileUnit) {
ValidateCodeCompileUnit((CodeCompileUnit)e);
}
else if (e is CodeComment) {
ValidateComment((CodeComment)e);
}
else if (e is CodeExpression) {
ValidateExpression((CodeExpression)e);
}
else if (e is CodeNamespace) {
ValidateNamespace((CodeNamespace)e);
}
else if (e is CodeNamespaceImport) {
ValidateNamespaceImport((CodeNamespaceImport)e);
}
else if (e is CodeStatement) {
ValidateStatement((CodeStatement)e);
}
else if (e is CodeTypeMember) {
ValidateTypeMember((CodeTypeMember)e);
}
else if (e is CodeTypeReference) {
ValidateTypeReference((CodeTypeReference)e);
}
else if (e is CodeDirective) {
ValidateCodeDirective((CodeDirective) e);
}
else {
throw new ArgumentException(SR.GetString(SR.InvalidElementType, e.GetType().FullName), "e");
}
}
private void ValidateTypeMember(CodeTypeMember e) {
ValidateCommentStatements(e.Comments);
ValidateCodeDirectives(e.StartDirectives);
ValidateCodeDirectives(e.EndDirectives);
if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma);
if (e is CodeMemberEvent) {
ValidateEvent((CodeMemberEvent)e);
}
else if (e is CodeMemberField) {
ValidateField((CodeMemberField)e);
}
else if (e is CodeMemberMethod) {
ValidateMemberMethod((CodeMemberMethod)e);
}
else if (e is CodeMemberProperty) {
ValidateProperty((CodeMemberProperty)e);
}
else if (e is CodeSnippetTypeMember) {
ValidateSnippetMember((CodeSnippetTypeMember)e);
}
else if (e is CodeTypeDeclaration) {
ValidateTypeDeclaration((CodeTypeDeclaration)e);
}
else {
throw new ArgumentException(SR.GetString(SR.InvalidElementType, e.GetType().FullName), "e");
}
}
private void ValidateCodeCompileUnit(CodeCompileUnit e) {
ValidateCodeDirectives(e.StartDirectives);
ValidateCodeDirectives(e.EndDirectives);
if (e is CodeSnippetCompileUnit) {
ValidateSnippetCompileUnit((CodeSnippetCompileUnit) e);
} else {
ValidateCompileUnitStart(e);
ValidateNamespaces(e);
ValidateCompileUnitEnd(e);
}
}
private void ValidateSnippetCompileUnit(CodeSnippetCompileUnit e) {
if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma);
}
private void ValidateCompileUnitStart(CodeCompileUnit e) {
if (e.AssemblyCustomAttributes.Count > 0) {
ValidateAttributes(e.AssemblyCustomAttributes);
}
}
private void ValidateCompileUnitEnd(CodeCompileUnit e) {
}
private void ValidateNamespaces(CodeCompileUnit e) {
foreach (CodeNamespace n in e.Namespaces) {
ValidateNamespace(n);
}
}
private void ValidateNamespace(CodeNamespace e) {
ValidateCommentStatements(e.Comments);
ValidateNamespaceStart(e);
ValidateNamespaceImports(e);
ValidateTypes(e);
}
private static void ValidateNamespaceStart(CodeNamespace e) {
if (e.Name != null && e.Name.Length > 0) {
ValidateTypeName(e,"Name",e.Name);
}
}
private void ValidateNamespaceImports(CodeNamespace e) {
IEnumerator en = e.Imports.GetEnumerator();
while (en.MoveNext()) {
CodeNamespaceImport imp = (CodeNamespaceImport)en.Current;
if (imp.LinePragma != null) ValidateLinePragmaStart(imp.LinePragma);
ValidateNamespaceImport(imp);
}
}
private static void ValidateNamespaceImport(CodeNamespaceImport e) {
ValidateTypeName(e,"Namespace",e.Namespace);
}
private void ValidateAttributes(CodeAttributeDeclarationCollection attributes) {
if (attributes.Count == 0) return;
IEnumerator en = attributes.GetEnumerator();
while (en.MoveNext()) {
CodeAttributeDeclaration current = (CodeAttributeDeclaration)en.Current;
ValidateTypeName(current,"Name",current.Name);
ValidateTypeReference(current.AttributeType);
foreach (CodeAttributeArgument arg in current.Arguments) {
ValidateAttributeArgument(arg);
}
}
}
private void ValidateAttributeArgument(CodeAttributeArgument arg) {
if (arg.Name != null && arg.Name.Length > 0) {
ValidateIdentifier(arg,"Name",arg.Name);
}
ValidateExpression(arg.Value);
}
private void ValidateTypes(CodeNamespace e) {
foreach (CodeTypeDeclaration type in e.Types) {
ValidateTypeDeclaration(type);
}
}
private void ValidateTypeDeclaration(CodeTypeDeclaration e) {
// This function can be called recursively and will modify the global variable currentClass
// We will save currentClass to a local, modify it to do whatever we want and restore it back when we exit so that it is re-entrant.
CodeTypeDeclaration savedClass = currentClass;
currentClass = e;
ValidateTypeStart(e);
ValidateTypeParameters(e.TypeParameters);
ValidateTypeMembers(e); // Recursive call can come from here.
ValidateTypeReferences(e.BaseTypes);
currentClass = savedClass;
}
private void ValidateTypeMembers(CodeTypeDeclaration e) {
foreach (CodeTypeMember currentMember in e.Members) {
ValidateTypeMember(currentMember);
}
}
private void ValidateTypeParameters(CodeTypeParameterCollection parameters) {
for (int i=0; i<parameters.Count; i++) {
ValidateTypeParameter(parameters[i]);
}
}
private void ValidateTypeParameter(CodeTypeParameter e) {
ValidateIdentifier(e, "Name", e.Name);
ValidateTypeReferences(e.Constraints);
ValidateAttributes(e.CustomAttributes);
}
private void ValidateField(CodeMemberField e) {
if (e.CustomAttributes.Count > 0) {
ValidateAttributes(e.CustomAttributes);
}
ValidateIdentifier(e,"Name",e.Name);
if (!IsCurrentEnum) {
ValidateTypeReference(e.Type);
}
if (e.InitExpression != null) {
ValidateExpression(e.InitExpression);
}
}
private void ValidateConstructor(CodeConstructor e) {
if (e.CustomAttributes.Count > 0) {
ValidateAttributes(e.CustomAttributes);
}
ValidateParameters(e.Parameters);
CodeExpressionCollection baseArgs = e.BaseConstructorArgs;
CodeExpressionCollection thisArgs = e.ChainedConstructorArgs;
if (baseArgs.Count > 0) {
ValidateExpressionList(baseArgs);
}
if (thisArgs.Count > 0) {
ValidateExpressionList(thisArgs);
}
ValidateStatements(e.Statements);
}
private void ValidateProperty(CodeMemberProperty e) {
if (e.CustomAttributes.Count > 0) {
ValidateAttributes(e.CustomAttributes);
}
ValidateTypeReference(e.Type);
ValidateTypeReferences(e.ImplementationTypes);
if (e.PrivateImplementationType != null && !IsCurrentInterface) {
ValidateTypeReference(e.PrivateImplementationType);
}
if (e.Parameters.Count > 0 && String.Compare(e.Name, "Item", StringComparison.OrdinalIgnoreCase) == 0) {
ValidateParameters(e.Parameters);
}
else {
ValidateIdentifier(e,"Name",e.Name);
}
if (e.HasGet) {
if (!(IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract)) {
ValidateStatements(e.GetStatements);
}
}
if (e.HasSet) {
if (!(IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract)) {
ValidateStatements(e.SetStatements);
}
}
}
private void ValidateMemberMethod(CodeMemberMethod e) {
ValidateCommentStatements(e.Comments);
if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma);
ValidateTypeParameters(e.TypeParameters);
ValidateTypeReferences(e.ImplementationTypes);
if (e is CodeEntryPointMethod) {
ValidateStatements(((CodeEntryPointMethod)e).Statements);
}
else if (e is CodeConstructor) {
ValidateConstructor((CodeConstructor)e);
}
else if (e is CodeTypeConstructor) {
ValidateTypeConstructor((CodeTypeConstructor)e);
}
else {
ValidateMethod(e);
}
}
private void ValidateTypeConstructor(CodeTypeConstructor e) {
ValidateStatements(e.Statements);
}
private void ValidateMethod(CodeMemberMethod e) {
if (e.CustomAttributes.Count > 0) {
ValidateAttributes(e.CustomAttributes);
}
if (e.ReturnTypeCustomAttributes.Count > 0) {
ValidateAttributes(e.ReturnTypeCustomAttributes);
}
ValidateTypeReference(e.ReturnType);
if (e.PrivateImplementationType != null) {
ValidateTypeReference(e.PrivateImplementationType);
}
ValidateIdentifier(e,"Name",e.Name);
ValidateParameters(e.Parameters);
if (!IsCurrentInterface
&& (e.Attributes & MemberAttributes.ScopeMask) != MemberAttributes.Abstract) {
ValidateStatements(e.Statements);
}
}
private void ValidateSnippetMember(CodeSnippetTypeMember e) {
}
private void ValidateTypeStart(CodeTypeDeclaration e) {
ValidateCommentStatements(e.Comments);
if (e.CustomAttributes.Count > 0) {
ValidateAttributes(e.CustomAttributes);
}
ValidateIdentifier(e,"Name",e.Name);
if (IsCurrentDelegate) {
CodeTypeDelegate del = (CodeTypeDelegate)e;
ValidateTypeReference(del.ReturnType);
ValidateParameters(del.Parameters);
} else {
foreach (CodeTypeReference typeRef in e.BaseTypes) {
ValidateTypeReference(typeRef);
}
}
}
private void ValidateCommentStatements(CodeCommentStatementCollection e) {
foreach (CodeCommentStatement comment in e) {
ValidateCommentStatement(comment);
}
}
private void ValidateCommentStatement(CodeCommentStatement e) {
ValidateComment(e.Comment);
}
private void ValidateComment(CodeComment e) {
}
private void ValidateStatement(CodeStatement e) {
ValidateCodeDirectives(e.StartDirectives);
ValidateCodeDirectives(e.EndDirectives);
if (e is CodeCommentStatement) {
ValidateCommentStatement((CodeCommentStatement)e);
}
else if (e is CodeMethodReturnStatement) {
ValidateMethodReturnStatement((CodeMethodReturnStatement)e);
}
else if (e is CodeConditionStatement) {
ValidateConditionStatement((CodeConditionStatement)e);
}
else if (e is CodeTryCatchFinallyStatement) {
ValidateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e);
}
else if (e is CodeAssignStatement) {
ValidateAssignStatement((CodeAssignStatement)e);
}
else if (e is CodeExpressionStatement) {
ValidateExpressionStatement((CodeExpressionStatement)e);
}
else if (e is CodeIterationStatement) {
ValidateIterationStatement((CodeIterationStatement)e);
}
else if (e is CodeThrowExceptionStatement) {
ValidateThrowExceptionStatement((CodeThrowExceptionStatement)e);
}
else if (e is CodeSnippetStatement) {
ValidateSnippetStatement((CodeSnippetStatement)e);
}
else if (e is CodeVariableDeclarationStatement) {
ValidateVariableDeclarationStatement((CodeVariableDeclarationStatement)e);
}
else if (e is CodeAttachEventStatement) {
ValidateAttachEventStatement((CodeAttachEventStatement)e);
}
else if (e is CodeRemoveEventStatement) {
ValidateRemoveEventStatement((CodeRemoveEventStatement)e);
}
else if (e is CodeGotoStatement) {
ValidateGotoStatement((CodeGotoStatement)e);
}
else if (e is CodeLabeledStatement) {
ValidateLabeledStatement((CodeLabeledStatement)e);
}
else {
throw new ArgumentException(SR.GetString(SR.InvalidElementType, e.GetType().FullName), "e");
}
}
private void ValidateStatements(CodeStatementCollection stms) {
IEnumerator en = stms.GetEnumerator();
while (en.MoveNext()) {
ValidateStatement((CodeStatement)en.Current);
}
}
private void ValidateExpressionStatement(CodeExpressionStatement e) {
ValidateExpression(e.Expression);
}
private void ValidateIterationStatement(CodeIterationStatement e) {
ValidateStatement(e.InitStatement);
ValidateExpression(e.TestExpression);
ValidateStatement(e.IncrementStatement);
ValidateStatements(e.Statements);
}
private void ValidateThrowExceptionStatement(CodeThrowExceptionStatement e) {
if (e.ToThrow != null) {
ValidateExpression(e.ToThrow);
}
}
private void ValidateMethodReturnStatement(CodeMethodReturnStatement e) {
if (e.Expression != null) {
ValidateExpression(e.Expression);
}
}
private void ValidateConditionStatement(CodeConditionStatement e) {
ValidateExpression(e.Condition);
ValidateStatements(e.TrueStatements);
CodeStatementCollection falseStatemetns = e.FalseStatements;
if (falseStatemetns.Count > 0) {
ValidateStatements(e.FalseStatements);
}
}
private void ValidateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e) {
ValidateStatements(e.TryStatements);
CodeCatchClauseCollection catches = e.CatchClauses;
if (catches.Count > 0) {
IEnumerator en = catches.GetEnumerator();
while (en.MoveNext()) {
CodeCatchClause current = (CodeCatchClause)en.Current;
ValidateTypeReference(current.CatchExceptionType);
ValidateIdentifier(current,"LocalName",current.LocalName);
ValidateStatements(current.Statements);
}
}
CodeStatementCollection finallyStatements = e.FinallyStatements;
if (finallyStatements.Count > 0) {
ValidateStatements(finallyStatements);
}
}
private void ValidateAssignStatement(CodeAssignStatement e) {
ValidateExpression(e.Left);
ValidateExpression(e.Right);
}
private void ValidateAttachEventStatement(CodeAttachEventStatement e) {
ValidateEventReferenceExpression(e.Event);
ValidateExpression(e.Listener);
}
private void ValidateRemoveEventStatement(CodeRemoveEventStatement e) {
ValidateEventReferenceExpression(e.Event);
ValidateExpression(e.Listener);
}
private static void ValidateGotoStatement(CodeGotoStatement e) {
ValidateIdentifier(e,"Label",e.Label);
}
private void ValidateLabeledStatement(CodeLabeledStatement e) {
ValidateIdentifier(e,"Label",e.Label);
if (e.Statement != null) {
ValidateStatement(e.Statement);
}
}
private void ValidateVariableDeclarationStatement(CodeVariableDeclarationStatement e) {
ValidateTypeReference(e.Type);
ValidateIdentifier(e,"Name",e.Name);
if (e.InitExpression != null) {
ValidateExpression(e.InitExpression);
}
}
private void ValidateLinePragmaStart(CodeLinePragma e) {
}
private void ValidateEvent(CodeMemberEvent e) {
if (e.CustomAttributes.Count > 0) {
ValidateAttributes(e.CustomAttributes);
}
if (e.PrivateImplementationType != null) {
ValidateTypeReference(e.Type);
ValidateIdentifier(e,"Name",e.Name);
}
ValidateTypeReferences(e.ImplementationTypes);
}
private void ValidateParameters(CodeParameterDeclarationExpressionCollection parameters) {
IEnumerator en = parameters.GetEnumerator();
while (en.MoveNext()) {
CodeParameterDeclarationExpression current = (CodeParameterDeclarationExpression)en.Current;
ValidateParameterDeclarationExpression(current);
}
}
private void ValidateSnippetStatement(CodeSnippetStatement e) {
}
private void ValidateExpressionList(CodeExpressionCollection expressions) {
IEnumerator en = expressions.GetEnumerator();
while (en.MoveNext()) {
ValidateExpression((CodeExpression)en.Current);
}
}
private static void ValidateTypeReference(CodeTypeReference e) {
String baseType = e.BaseType;
ValidateTypeName(e,"BaseType",baseType);
ValidateArity(e);
ValidateTypeReferences(e.TypeArguments);
}
private static void ValidateTypeReferences(CodeTypeReferenceCollection refs) {
for (int i=0; i<refs.Count; i++) {
ValidateTypeReference(refs[i]);
}
}
private static void ValidateArity(CodeTypeReference e) {
// Verify that the number of TypeArguments agrees with the arity on the type.
string baseType = e.BaseType;
int totalTypeArgs = 0;
for (int i=0; i<baseType.Length; i++) {
if (baseType[i] == '`') {
i++; // skip the '
int numTypeArgs = 0;
while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <='9') {
numTypeArgs = numTypeArgs*10 + (baseType[i] - '0');
i++;
}
totalTypeArgs += numTypeArgs;
}
}
// Check if we have zero type args for open types.
if ((totalTypeArgs != e.TypeArguments.Count) && (e.TypeArguments.Count != 0)) {
throw new ArgumentException(SR.GetString(SR.ArityDoesntMatch, baseType, e.TypeArguments.Count));
}
}
private static void ValidateTypeName(Object e, String propertyName, String typeName) {
if (!CodeGenerator.IsValidLanguageIndependentTypeName(typeName)) {
String message = SR.GetString(SR.InvalidTypeName, typeName, propertyName, e.GetType().FullName);
throw new ArgumentException(message, "typeName");
}
}
private static void ValidateIdentifier(Object e, String propertyName, String identifier) {
if (!CodeGenerator.IsValidLanguageIndependentIdentifier(identifier)) {
String message = SR.GetString(SR.InvalidLanguageIdentifier, identifier, propertyName, e.GetType().FullName);
throw new ArgumentException(message , "identifier");
}
}
private void ValidateExpression(CodeExpression e) {
if (e is CodeArrayCreateExpression) {
ValidateArrayCreateExpression((CodeArrayCreateExpression)e);
}
else if (e is CodeBaseReferenceExpression) {
ValidateBaseReferenceExpression((CodeBaseReferenceExpression)e);
}
else if (e is CodeBinaryOperatorExpression) {
ValidateBinaryOperatorExpression((CodeBinaryOperatorExpression)e);
}
else if (e is CodeCastExpression) {
ValidateCastExpression((CodeCastExpression)e);
}
else if (e is CodeDefaultValueExpression) {
ValidateDefaultValueExpression((CodeDefaultValueExpression)e);
}
else if (e is CodeDelegateCreateExpression) {
ValidateDelegateCreateExpression((CodeDelegateCreateExpression)e);
}
else if (e is CodeFieldReferenceExpression) {
ValidateFieldReferenceExpression((CodeFieldReferenceExpression)e);
}
else if (e is CodeArgumentReferenceExpression) {
ValidateArgumentReferenceExpression((CodeArgumentReferenceExpression)e);
}
else if (e is CodeVariableReferenceExpression) {
ValidateVariableReferenceExpression((CodeVariableReferenceExpression)e);
}
else if (e is CodeIndexerExpression) {
ValidateIndexerExpression((CodeIndexerExpression)e);
}
else if (e is CodeArrayIndexerExpression) {
ValidateArrayIndexerExpression((CodeArrayIndexerExpression)e);
}
else if (e is CodeSnippetExpression) {
ValidateSnippetExpression((CodeSnippetExpression)e);
}
else if (e is CodeMethodInvokeExpression) {
ValidateMethodInvokeExpression((CodeMethodInvokeExpression)e);
}
else if (e is CodeMethodReferenceExpression) {
ValidateMethodReferenceExpression((CodeMethodReferenceExpression)e);
}
else if (e is CodeEventReferenceExpression) {
ValidateEventReferenceExpression((CodeEventReferenceExpression)e);
}
else if (e is CodeDelegateInvokeExpression) {
ValidateDelegateInvokeExpression((CodeDelegateInvokeExpression)e);
}
else if (e is CodeObjectCreateExpression) {
ValidateObjectCreateExpression((CodeObjectCreateExpression)e);
}
else if (e is CodeParameterDeclarationExpression) {
ValidateParameterDeclarationExpression((CodeParameterDeclarationExpression)e);
}
else if (e is CodeDirectionExpression) {
ValidateDirectionExpression((CodeDirectionExpression)e);
}
else if (e is CodePrimitiveExpression) {
ValidatePrimitiveExpression((CodePrimitiveExpression)e);
}
else if (e is CodePropertyReferenceExpression) {
ValidatePropertyReferenceExpression((CodePropertyReferenceExpression)e);
}
else if (e is CodePropertySetValueReferenceExpression) {
ValidatePropertySetValueReferenceExpression((CodePropertySetValueReferenceExpression)e);
}
else if (e is CodeThisReferenceExpression) {
ValidateThisReferenceExpression((CodeThisReferenceExpression)e);
}
else if (e is CodeTypeReferenceExpression) {
ValidateTypeReference(((CodeTypeReferenceExpression)e).Type);
}
else if (e is CodeTypeOfExpression) {
ValidateTypeOfExpression((CodeTypeOfExpression)e);
}
else {
if (e == null) {
throw new ArgumentNullException("e");
}
else {
throw new ArgumentException(SR.GetString(SR.InvalidElementType, e.GetType().FullName), "e");
}
}
}
private void ValidateArrayCreateExpression(CodeArrayCreateExpression e) {
ValidateTypeReference(e.CreateType);
CodeExpressionCollection init = e.Initializers;
if (init.Count > 0) {
ValidateExpressionList(init);
}
else {
if (e.SizeExpression != null) {
ValidateExpression(e.SizeExpression);
}
}
}
private void ValidateBaseReferenceExpression(CodeBaseReferenceExpression e) { // Nothing to validate
}
private void ValidateBinaryOperatorExpression(CodeBinaryOperatorExpression e) {
ValidateExpression(e.Left);
ValidateExpression(e.Right);
}
private void ValidateCastExpression(CodeCastExpression e) {
ValidateTypeReference(e.TargetType);
ValidateExpression(e.Expression);
}
private static void ValidateDefaultValueExpression(CodeDefaultValueExpression e) {
ValidateTypeReference(e.Type);
}
private void ValidateDelegateCreateExpression(CodeDelegateCreateExpression e) {
ValidateTypeReference(e.DelegateType);
ValidateExpression(e.TargetObject);
ValidateIdentifier(e,"MethodName",e.MethodName);
}
private void ValidateFieldReferenceExpression(CodeFieldReferenceExpression e) {
if (e.TargetObject != null) {
ValidateExpression(e.TargetObject);
}
ValidateIdentifier(e,"FieldName",e.FieldName);
}
private static void ValidateArgumentReferenceExpression(CodeArgumentReferenceExpression e) {
ValidateIdentifier(e,"ParameterName",e.ParameterName);
}
private static void ValidateVariableReferenceExpression(CodeVariableReferenceExpression e) {
ValidateIdentifier(e,"VariableName",e.VariableName);
}
private void ValidateIndexerExpression(CodeIndexerExpression e) {
ValidateExpression(e.TargetObject);
foreach(CodeExpression exp in e.Indices) {
ValidateExpression(exp);
}
}
private void ValidateArrayIndexerExpression(CodeArrayIndexerExpression e) {
ValidateExpression(e.TargetObject);
foreach(CodeExpression exp in e.Indices) {
ValidateExpression(exp);
}
}
private void ValidateSnippetExpression(CodeSnippetExpression e) {
}
private void ValidateMethodInvokeExpression(CodeMethodInvokeExpression e) {
ValidateMethodReferenceExpression(e.Method);
ValidateExpressionList(e.Parameters);
}
private void ValidateMethodReferenceExpression(CodeMethodReferenceExpression e) {
if (e.TargetObject != null) {
ValidateExpression(e.TargetObject);
}
ValidateIdentifier(e,"MethodName",e.MethodName);
ValidateTypeReferences(e.TypeArguments);
}
private void ValidateEventReferenceExpression(CodeEventReferenceExpression e) {
if (e.TargetObject != null) {
ValidateExpression(e.TargetObject);
}
ValidateIdentifier(e,"EventName",e.EventName);
}
private void ValidateDelegateInvokeExpression(CodeDelegateInvokeExpression e) {
if (e.TargetObject != null) {
ValidateExpression(e.TargetObject);
}
ValidateExpressionList(e.Parameters);
}
private void ValidateObjectCreateExpression(CodeObjectCreateExpression e) {
ValidateTypeReference(e.CreateType);
ValidateExpressionList(e.Parameters);
}
private void ValidateParameterDeclarationExpression(CodeParameterDeclarationExpression e) {
if (e.CustomAttributes.Count > 0) {
ValidateAttributes(e.CustomAttributes);
}
ValidateTypeReference(e.Type);
ValidateIdentifier(e,"Name",e.Name);
}
private void ValidateDirectionExpression(CodeDirectionExpression e) {
ValidateExpression(e.Expression);
}
private void ValidatePrimitiveExpression(CodePrimitiveExpression e) {
}
private void ValidatePropertyReferenceExpression(CodePropertyReferenceExpression e) {
if (e.TargetObject != null) {
ValidateExpression(e.TargetObject);
}
ValidateIdentifier(e,"PropertyName",e.PropertyName);
}
private void ValidatePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) { // Do nothing
}
private void ValidateThisReferenceExpression(CodeThisReferenceExpression e) { // Do nothing
}
private static void ValidateTypeOfExpression(CodeTypeOfExpression e) {
ValidateTypeReference(e.Type);
}
private static void ValidateCodeDirectives(CodeDirectiveCollection e) {
for (int i=0; i<e.Count; i++)
ValidateCodeDirective(e[i]);
}
private static void ValidateCodeDirective(CodeDirective e) {
if (e is CodeChecksumPragma)
ValidateChecksumPragma((CodeChecksumPragma) e);
else if (e is CodeRegionDirective)
ValidateRegionDirective((CodeRegionDirective) e);
else
throw new ArgumentException(SR.GetString(SR.InvalidElementType, e.GetType().FullName), "e");
}
private static void ValidateChecksumPragma(CodeChecksumPragma e) {
if (e.FileName.IndexOfAny(Path.GetInvalidPathChars()) != -1)
throw new ArgumentException(SR.GetString(SR.InvalidPathCharsInChecksum, e.FileName));
}
private static void ValidateRegionDirective(CodeRegionDirective e) {
if (e.RegionText.IndexOfAny(newLineChars) != -1)
throw new ArgumentException(SR.GetString(SR.InvalidRegion, e.RegionText));
}
private bool IsCurrentInterface {
get {
if (currentClass != null && !(currentClass is CodeTypeDelegate)) {
return currentClass.IsInterface;
}
return false;
}
}
private bool IsCurrentEnum {
get {
if (currentClass != null && !(currentClass is CodeTypeDelegate)) {
return currentClass.IsEnum;
}
return false;
}
}
private bool IsCurrentDelegate {
get {
if (currentClass != null && currentClass is CodeTypeDelegate) {
return true;
}
return false;
}
}
private CodeTypeDeclaration currentClass;
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Threading;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Execution;
#if !SILVERLIGHT && !NETCF && !PORTABLE
using System.Runtime.Remoting.Messaging;
using System.Security.Principal;
using NUnit.Compatibility;
#endif
namespace NUnit.Framework.Internal
{
/// <summary>
/// Helper class used to save and restore certain static or
/// singleton settings in the environment that affect tests
/// or which might be changed by the user tests.
///
/// An internal class is used to hold settings and a stack
/// of these objects is pushed and popped as Save and Restore
/// are called.
/// </summary>
public class TestExecutionContext
#if !SILVERLIGHT && !NETCF && !PORTABLE
: LongLivedMarshalByRefObject, ILogicalThreadAffinative
#endif
{
// NOTE: Be very careful when modifying this class. It uses
// conditional compilation extensively and you must give
// thought to whether any new features will be supported
// on each platform. In particular, instance fields,
// properties, initialization and restoration must all
// use the same conditions for each feature.
#region Instance Fields
/// <summary>
/// Link to a prior saved context
/// </summary>
private TestExecutionContext _priorContext;
/// <summary>
/// Indicates that a stop has been requested
/// </summary>
private TestExecutionStatus _executionStatus;
/// <summary>
/// The event listener currently receiving notifications
/// </summary>
private ITestListener _listener = TestListener.NULL;
/// <summary>
/// The number of assertions for the current test
/// </summary>
private int _assertCount;
private Randomizer _randomGenerator;
/// <summary>
/// The current culture
/// </summary>
private CultureInfo _currentCulture;
/// <summary>
/// The current UI culture
/// </summary>
private CultureInfo _currentUICulture;
/// <summary>
/// The current test result
/// </summary>
private TestResult _currentResult;
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// The current Principal.
/// </summary>
private IPrincipal _currentPrincipal;
#endif
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
public TestExecutionContext()
{
_priorContext = null;
TestCaseTimeout = 0;
UpstreamActions = new List<ITestAction>();
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = Thread.CurrentPrincipal;
#endif
CurrentValueFormatter = (val) => MsgUtils.DefaultValueFormatter(val);
IsSingleThreaded = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
/// <param name="other">An existing instance of TestExecutionContext.</param>
public TestExecutionContext(TestExecutionContext other)
{
_priorContext = other;
CurrentTest = other.CurrentTest;
CurrentResult = other.CurrentResult;
TestObject = other.TestObject;
WorkDirectory = other.WorkDirectory;
_listener = other._listener;
StopOnError = other.StopOnError;
TestCaseTimeout = other.TestCaseTimeout;
UpstreamActions = new List<ITestAction>(other.UpstreamActions);
_currentCulture = other.CurrentCulture;
_currentUICulture = other.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = other.CurrentPrincipal;
#endif
CurrentValueFormatter = other.CurrentValueFormatter;
Dispatcher = other.Dispatcher;
ParallelScope = other.ParallelScope;
IsSingleThreaded = other.IsSingleThreaded;
}
#endregion
#region Static Singleton Instance
// NOTE: We use different implementations for various platforms
// If a user creates a thread then the current context
// will be null. This also happens when the compiler
// automatically creates threads for async methods.
// We create a new context, which is automatically
// populated with values taken from the current thread.
#if SILVERLIGHT || PORTABLE
// In the Silverlight and portable builds, we use a ThreadStatic
// field to hold the current TestExecutionContext.
[ThreadStatic]
private static TestExecutionContext _currentContext;
/// <summary>
/// Gets and sets the current context.
/// </summary>
public static TestExecutionContext CurrentContext
{
get
{
if (_currentContext == null)
_currentContext = new TestExecutionContext();
return _currentContext;
}
private set
{
_currentContext = value;
}
}
#elif NETCF
// In the compact framework build, we use a LocalStoreDataSlot
private static LocalDataStoreSlot contextSlot = Thread.AllocateDataSlot();
/// <summary>
/// Gets and sets the current context.
/// </summary>
public static TestExecutionContext CurrentContext
{
get
{
var current = GetTestExecutionContext();
if (current == null)
{
current = new TestExecutionContext();
Thread.SetData(contextSlot, current);
}
return current;
}
private set
{
Thread.SetData(contextSlot, value);
}
}
/// <summary>
/// Get the current context or return null if none is found.
/// </summary>
public static TestExecutionContext GetTestExecutionContext()
{
return (TestExecutionContext)Thread.GetData(contextSlot);
}
#else
// In all other builds, we use the CallContext
private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext";
/// <summary>
/// Gets and sets the current context.
/// </summary>
public static TestExecutionContext CurrentContext
{
get
{
var context = GetTestExecutionContext();
if (context == null) // This can happen on Mono
{
context = new TestExecutionContext();
CallContext.SetData(CONTEXT_KEY, context);
}
return context;
}
private set
{
if (value == null)
CallContext.FreeNamedDataSlot(CONTEXT_KEY);
else
CallContext.SetData(CONTEXT_KEY, value);
}
}
/// <summary>
/// Get the current context or return null if none is found.
/// </summary>
public static TestExecutionContext GetTestExecutionContext()
{
return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext;
}
#endif
/// <summary>
/// Clear the current context. This is provided to
/// prevent "leakage" of the CallContext containing
/// the current context back to any runners.
/// </summary>
public static void ClearCurrentContext()
{
CurrentContext = null;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the current test
/// </summary>
public Test CurrentTest { get; set; }
/// <summary>
/// The time the current test started execution
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// The time the current test started in Ticks
/// </summary>
public long StartTicks { get; set; }
/// <summary>
/// Gets or sets the current test result
/// </summary>
public TestResult CurrentResult
{
get { return _currentResult; }
set
{
_currentResult = value;
if (value != null)
OutWriter = value.OutWriter;
}
}
/// <summary>
/// Gets a TextWriter that will send output to the current test result.
/// </summary>
public TextWriter OutWriter { get; private set; }
/// <summary>
/// The current test object - that is the user fixture
/// object on which tests are being executed.
/// </summary>
public object TestObject { get; set; }
/// <summary>
/// Get or set the working directory
/// </summary>
public string WorkDirectory { get; set; }
/// <summary>
/// Get or set indicator that run should stop on the first error
/// </summary>
public bool StopOnError { get; set; }
/// <summary>
/// Gets an enum indicating whether a stop has been requested.
/// </summary>
public TestExecutionStatus ExecutionStatus
{
get
{
// ExecutionStatus may have been set to StopRequested or AbortRequested
// in a prior context. If so, reflect the same setting in this context.
if (_executionStatus == TestExecutionStatus.Running && _priorContext != null)
_executionStatus = _priorContext.ExecutionStatus;
return _executionStatus;
}
set
{
_executionStatus = value;
// Push the same setting up to all prior contexts
if (_priorContext != null)
_priorContext.ExecutionStatus = value;
}
}
/// <summary>
/// The current test event listener
/// </summary>
internal ITestListener Listener
{
get { return _listener; }
set { _listener = value; }
}
/// <summary>
/// The current WorkItemDispatcher. Made public for
/// use by nunitlite.tests
/// </summary>
public IWorkItemDispatcher Dispatcher { get; set; }
/// <summary>
/// The ParallelScope to be used by tests running in this context.
/// For builds with out the parallel feature, it has no effect.
/// </summary>
public ParallelScope ParallelScope { get; set; }
/// <summary>
/// The unique name of the worker that spawned the context.
/// For builds with out the parallel feature, it is null.
/// </summary>
public string WorkerId {get; internal set;}
/// <summary>
/// Gets the RandomGenerator specific to this Test
/// </summary>
public Randomizer RandomGenerator
{
get
{
if (_randomGenerator == null)
_randomGenerator = new Randomizer(CurrentTest.Seed);
return _randomGenerator;
}
}
/// <summary>
/// Gets the assert count.
/// </summary>
/// <value>The assert count.</value>
internal int AssertCount
{
get { return _assertCount; }
}
/// <summary>
/// Gets or sets the test case timeout value
/// </summary>
public int TestCaseTimeout { get; set; }
/// <summary>
/// Gets a list of ITestActions set by upstream tests
/// </summary>
public List<ITestAction> UpstreamActions { get; private set; }
// TODO: Put in checks on all of these settings
// with side effects so we only change them
// if the value is different
/// <summary>
/// Saves or restores the CurrentCulture
/// </summary>
public CultureInfo CurrentCulture
{
get { return _currentCulture; }
set
{
_currentCulture = value;
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentCulture = _currentCulture;
#endif
}
}
/// <summary>
/// Saves or restores the CurrentUICulture
/// </summary>
public CultureInfo CurrentUICulture
{
get { return _currentUICulture; }
set
{
_currentUICulture = value;
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentUICulture = _currentUICulture;
#endif
}
}
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// Gets or sets the current <see cref="IPrincipal"/> for the Thread.
/// </summary>
public IPrincipal CurrentPrincipal
{
get { return _currentPrincipal; }
set
{
_currentPrincipal = value;
Thread.CurrentPrincipal = _currentPrincipal;
}
}
#endif
/// <summary>
/// The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter
/// </summary>
public ValueFormatter CurrentValueFormatter { get; private set; }
/// <summary>
/// If true, all tests must run on the same thread. No new thread may be spawned.
/// </summary>
public bool IsSingleThreaded { get; set; }
#endregion
#region Instance Methods
/// <summary>
/// Record any changes in the environment made by
/// the test code in the execution context so it
/// will be passed on to lower level tests.
/// </summary>
public void UpdateContextFromEnvironment()
{
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !NETCF && !SILVERLIGHT && !PORTABLE
_currentPrincipal = Thread.CurrentPrincipal;
#endif
}
/// <summary>
/// Set up the execution environment to match a context.
/// Note that we may be running on the same thread where the
/// context was initially created or on a different thread.
/// </summary>
public void EstablishExecutionEnvironment()
{
#if !NETCF && !PORTABLE
Thread.CurrentThread.CurrentCulture = _currentCulture;
Thread.CurrentThread.CurrentUICulture = _currentUICulture;
#endif
#if !NETCF && !SILVERLIGHT && !PORTABLE
Thread.CurrentPrincipal = _currentPrincipal;
#endif
CurrentContext = this;
}
/// <summary>
/// Increments the assert count by one.
/// </summary>
public void IncrementAssertCount()
{
Interlocked.Increment(ref _assertCount);
}
/// <summary>
/// Increments the assert count by a specified amount.
/// </summary>
public void IncrementAssertCount(int count)
{
// TODO: Temporary implementation
while (count-- > 0)
Interlocked.Increment(ref _assertCount);
}
/// <summary>
/// Adds a new ValueFormatterFactory to the chain of formatters
/// </summary>
/// <param name="formatterFactory">The new factory</param>
public void AddFormatter(ValueFormatterFactory formatterFactory)
{
CurrentValueFormatter = formatterFactory(CurrentValueFormatter);
}
#endregion
#region InitializeLifetimeService
#if !SILVERLIGHT && !NETCF && !PORTABLE
/// <summary>
/// Obtain lifetime service object
/// </summary>
/// <returns></returns>
public override object InitializeLifetimeService()
{
return null;
}
#endif
#endregion
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using App.Data;
namespace App.Data.Migrations
{
[DbContext(typeof(LibraryDbContext))]
[Migration("20151124204545_Initial")]
partial class Initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348");
modelBuilder.Entity("App.Models.Category", b =>
{
b.Property<short>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<DateTime?>("DeletedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("Description")
.HasAnnotation("Relational:ColumnType", "nvarchar(1024)");
b.Property<string>("Name")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(255)");
b.Property<short?>("ParentCategoryId");
b.Property<DateTime?>("UpdatedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "Categories");
});
modelBuilder.Entity("App.Models.Comment", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Body")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(65536)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<DateTime?>("DeletedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("Description")
.HasAnnotation("Relational:ColumnType", "nvarchar(1024)");
b.Property<int?>("ParentCommentId");
b.Property<int>("PostId");
b.Property<DateTime?>("UpdatedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "Comments");
});
modelBuilder.Entity("App.Models.FAQ", b =>
{
b.Property<short>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Answer")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(4096)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<DateTime?>("DeletedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("Description")
.HasAnnotation("Relational:ColumnType", "nvarchar(1024)");
b.Property<short?>("LibraryId");
b.Property<string>("Question")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(1024)");
b.Property<DateTime?>("UpdatedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "Faqs");
});
modelBuilder.Entity("App.Models.Identity.ApplicationRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreatedAt");
b.Property<DateTime?>("DeletedAt");
b.Property<string>("Description");
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.Property<DateTime?>("UpdatedAt");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("App.Models.Identity.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreatedAt");
b.Property<DateTime?>("DeletedAt");
b.Property<string>("Description");
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<DateTime?>("UpdatedAt");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("App.Models.Library", b =>
{
b.Property<short>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "char(3)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<DateTime?>("DeletedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("Description")
.HasAnnotation("Relational:ColumnType", "nvarchar(1024)");
b.Property<string>("Name")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(128)");
b.Property<DateTime?>("UpdatedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("Url")
.HasAnnotation("Relational:ColumnType", "nvarchar(512)");
b.Property<string>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "Libraries");
});
modelBuilder.Entity("App.Models.LibraryItemAction", b =>
{
b.Property<int>("LibraryItemId")
.ValueGeneratedOnAdd();
b.Property<int>("Action");
b.Property<DateTime>("CreatedAt");
b.Property<short?>("Rating");
b.Property<string>("UserAgent");
b.Property<string>("UserId");
b.HasKey("LibraryItemId");
});
modelBuilder.Entity("App.Models.Post", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Body")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(65536)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<DateTime?>("DeletedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("Description")
.HasAnnotation("Relational:ColumnType", "nvarchar(1024)");
b.Property<short?>("LibraryId");
b.Property<string>("Synopsis")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(1024)");
b.Property<string>("Title")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(128)");
b.Property<DateTime?>("UpdatedAt")
.HasAnnotation("Relational:ColumnType", "datetime");
b.Property<string>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "Posts");
});
modelBuilder.Entity("App.Models.PostCategory", b =>
{
b.Property<int>("PostId");
b.Property<short>("CategoryId");
b.HasKey("PostId", "CategoryId");
b.HasAnnotation("Relational:TableName", "PostCategories");
});
modelBuilder.Entity("App.Models.Profile", b =>
{
b.Property<string>("UserId");
b.Property<string>("FirstName")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(64)");
b.Property<string>("PictureLarge");
b.Property<string>("PictureMedium");
b.Property<string>("PictureSmall");
b.Property<string>("SurName")
.IsRequired()
.HasAnnotation("Relational:ColumnType", "nvarchar(128)");
b.HasKey("UserId");
b.HasAnnotation("Relational:TableName", "Profiles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("App.Models.Category", b =>
{
b.HasOne("App.Models.Category")
.WithMany()
.HasForeignKey("ParentCategoryId");
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("App.Models.Comment", b =>
{
b.HasOne("App.Models.Comment")
.WithMany()
.HasForeignKey("ParentCommentId");
b.HasOne("App.Models.Post")
.WithMany()
.HasForeignKey("PostId");
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("App.Models.FAQ", b =>
{
b.HasOne("App.Models.Library")
.WithMany()
.HasForeignKey("LibraryId");
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("App.Models.Library", b =>
{
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("App.Models.LibraryItemAction", b =>
{
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("App.Models.Post", b =>
{
b.HasOne("App.Models.Library")
.WithMany()
.HasForeignKey("LibraryId");
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("App.Models.PostCategory", b =>
{
b.HasOne("App.Models.Category")
.WithMany()
.HasForeignKey("CategoryId");
b.HasOne("App.Models.Post")
.WithMany()
.HasForeignKey("PostId");
});
modelBuilder.Entity("App.Models.Profile", b =>
{
b.HasOne("App.Models.Identity.ApplicationUser")
.WithOne()
.HasForeignKey("App.Models.Profile", "UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("App.Models.Identity.ApplicationRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("App.Models.Identity.ApplicationRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("App.Models.Identity.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="StateMachineTest.cs" company="Appccelerate">
// Copyright (c) 2008-2015
//
// 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>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Machine
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Appccelerate.StateMachine.Persistence;
using FakeItEasy;
using FluentAssertions;
using Xunit;
/// <summary>
/// Tests state machine initialization and state switching.
/// </summary>
public class StateMachineTest
{
/// <summary>
/// Object under test.
/// </summary>
private readonly StateMachine<StateMachine.States, StateMachine.Events> testee;
/// <summary>
/// The list of recorded actions.
/// </summary>
private readonly List<Record> records;
/// <summary>
/// Initializes a new instance of the <see cref="StateMachineTest"/> class.
/// </summary>
public StateMachineTest()
{
this.records = new List<Record>();
this.testee = new StateMachine<StateMachine.States, StateMachine.Events>();
this.testee.DefineHierarchyOn(StateMachine.States.B)
.WithHistoryType(HistoryType.None)
.WithInitialSubState(StateMachine.States.B1)
.WithSubState(StateMachine.States.B2);
this.testee.DefineHierarchyOn(StateMachine.States.C)
.WithHistoryType(HistoryType.Shallow)
.WithInitialSubState(StateMachine.States.C2)
.WithSubState(StateMachine.States.C1);
this.testee.DefineHierarchyOn(StateMachine.States.C1)
.WithHistoryType(HistoryType.Shallow)
.WithInitialSubState(StateMachine.States.C1A)
.WithSubState(StateMachine.States.C1B);
this.testee.DefineHierarchyOn(StateMachine.States.D)
.WithHistoryType(HistoryType.Deep)
.WithInitialSubState(StateMachine.States.D1)
.WithSubState(StateMachine.States.D2);
this.testee.DefineHierarchyOn(StateMachine.States.D1)
.WithHistoryType(HistoryType.Deep)
.WithInitialSubState(StateMachine.States.D1A)
.WithSubState(StateMachine.States.D1B);
this.testee.In(StateMachine.States.A)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.A))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.A))
.On(StateMachine.Events.B).Goto(StateMachine.States.B)
.On(StateMachine.Events.C).Goto(StateMachine.States.C)
.On(StateMachine.Events.D).Goto(StateMachine.States.D)
.On(StateMachine.Events.A);
this.testee.In(StateMachine.States.B)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.B))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.B))
.On(StateMachine.Events.D).Goto(StateMachine.States.D);
this.testee.In(StateMachine.States.B1)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.B1))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.B1))
.On(StateMachine.Events.B2).Goto(StateMachine.States.B2);
this.testee.In(StateMachine.States.B2)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.B2))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.B2))
.On(StateMachine.Events.A).Goto(StateMachine.States.A)
.On(StateMachine.Events.C1B).Goto(StateMachine.States.C1B);
this.testee.In(StateMachine.States.C)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.C))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.C))
.On(StateMachine.Events.A).Goto(StateMachine.States.A);
this.testee.In(StateMachine.States.C1)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.C1))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.C1))
.On(StateMachine.Events.C1B).Goto(StateMachine.States.C1B);
this.testee.In(StateMachine.States.C2)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.C2))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.C2));
this.testee.In(StateMachine.States.C1A)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.C1A))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.C1A));
this.testee.In(StateMachine.States.C1B)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.C1B))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.C1B));
this.testee.In(StateMachine.States.D)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.D))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.D));
this.testee.In(StateMachine.States.D1)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.D1))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.D1));
this.testee.In(StateMachine.States.D1A)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.D1A))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.D1A));
this.testee.In(StateMachine.States.D1B)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.D1B))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.D1B))
.On(StateMachine.Events.A).Goto(StateMachine.States.A)
.On(StateMachine.Events.B1).Goto(StateMachine.States.B1);
this.testee.In(StateMachine.States.D2)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.D2))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.D2))
.On(StateMachine.Events.A).Goto(StateMachine.States.A);
this.testee.In(StateMachine.States.E)
.ExecuteOnEntry(() => this.RecordEntry(StateMachine.States.E))
.ExecuteOnExit(() => this.RecordExit(StateMachine.States.E))
.On(StateMachine.Events.A).Goto(StateMachine.States.A)
.On(StateMachine.Events.E).Goto(StateMachine.States.E);
}
[Fact]
public void InitializationWhenInitialStateIsNotYetEnteredThenNoActionIsPerformed()
{
this.testee.Initialize(StateMachine.States.A);
this.CheckNoRemainingRecords();
}
/// <summary>
/// After initialization the state machine is in the initial state and the initial state is entered.
/// </summary>
[Fact]
public void InitializeToTopLevelState()
{
this.testee.Initialize(StateMachine.States.A);
this.testee.EnterInitialState();
this.testee.CurrentStateId.Should().Be(StateMachine.States.A);
this.CheckRecord<EntryRecord>(StateMachine.States.A);
this.CheckNoRemainingRecords();
}
/// <summary>
/// After initialization the state machine is in the initial state and the initial state is entered.
/// All states up in the hierarchy of the initial state are entered, too.
/// </summary>
[Fact]
public void InitializeToNestedState()
{
this.testee.Initialize(StateMachine.States.D1B);
this.testee.EnterInitialState();
this.testee.CurrentStateId.Should().Be(StateMachine.States.D1B);
this.CheckRecord<EntryRecord>(StateMachine.States.D);
this.CheckRecord<EntryRecord>(StateMachine.States.D1);
this.CheckRecord<EntryRecord>(StateMachine.States.D1B);
this.CheckNoRemainingRecords();
}
/// <summary>
/// When the state machine is initializes to a state with sub-states then the hierarchy is recursively
/// traversed to the most nested state along the chain of initial states.
/// </summary>
[Fact]
public void InitializeStateWithSubStates()
{
this.testee.Initialize(StateMachine.States.D);
this.testee.EnterInitialState();
this.testee.CurrentStateId.Should().Be(StateMachine.States.D1A);
this.CheckRecord<EntryRecord>(StateMachine.States.D);
this.CheckRecord<EntryRecord>(StateMachine.States.D1);
this.CheckRecord<EntryRecord>(StateMachine.States.D1A);
this.CheckNoRemainingRecords();
}
[Fact]
public void SetsCurrentStateOnLoadingFromPersistedState()
{
var loader = A.Fake<IStateMachineLoader<StateMachine.States>>();
A.CallTo(() => loader.LoadCurrentState())
.Returns(new Initializable<StateMachine.States> { Value = StateMachine.States.C });
this.testee.Load(loader);
this.testee.CurrentStateId
.Should().Be(StateMachine.States.C);
}
[Fact]
public void SetsHistoryStatesOnLoadingFromPersistedState()
{
var loader = A.Fake<IStateMachineLoader<StateMachine.States>>();
A.CallTo(() => loader.LoadHistoryStates())
.Returns(new Dictionary<StateMachine.States, StateMachine.States>
{
{ StateMachine.States.D, StateMachine.States.D2 }
});
this.testee.Load(loader);
this.testee.Initialize(StateMachine.States.A);
this.testee.EnterInitialState();
this.testee.Fire(StateMachine.Events.D); // should go to loaded last active state D2, not initial state D1
this.ClearRecords();
this.testee.Fire(StateMachine.Events.A);
this.CheckRecord<ExitRecord>(StateMachine.States.D2);
}
/// <summary>
/// When a transition between two states at the top level then the
/// exit action of the source state is executed, then the action is performed
/// and the entry action of the target state is executed.
/// Finally, the current state is the target state.
/// </summary>
[Fact]
public void ExecuteTransition()
{
this.testee.Initialize(StateMachine.States.E);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.A);
this.testee.CurrentStateId.Should().Be(StateMachine.States.A);
this.CheckRecord<ExitRecord>(StateMachine.States.E);
this.CheckRecord<EntryRecord>(StateMachine.States.A);
this.CheckNoRemainingRecords();
}
/// <summary>
/// When a transition between two states with the same super state is executed then
/// the exit action of source state, the transition action and the entry action of
/// the target state are executed.
/// </summary>
[Fact]
public void ExecuteTransitionBetweenStatesWithSameSuperState()
{
this.testee.Initialize(StateMachine.States.B1);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.B2);
this.testee.CurrentStateId.Should().Be(StateMachine.States.B2);
this.CheckRecord<ExitRecord>(StateMachine.States.B1);
this.CheckRecord<EntryRecord>(StateMachine.States.B2);
this.CheckNoRemainingRecords();
}
/// <summary>
/// When a transition between two states in different super states on different levels is executed
/// then all states from the source up to the common super-state are exited and all states down to
/// the target state are entered. In this case the target state is lower than the source state.
/// </summary>
[Fact]
public void ExecuteTransitionBetweenStatesOnDifferentLevelsDownwards()
{
this.testee.Initialize(StateMachine.States.B2);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.C1B);
this.testee.CurrentStateId.Should().Be(StateMachine.States.C1B);
this.CheckRecord<ExitRecord>(StateMachine.States.B2);
this.CheckRecord<ExitRecord>(StateMachine.States.B);
this.CheckRecord<EntryRecord>(StateMachine.States.C);
this.CheckRecord<EntryRecord>(StateMachine.States.C1);
this.CheckRecord<EntryRecord>(StateMachine.States.C1B);
this.CheckNoRemainingRecords();
}
/// <summary>
/// When a transition between two states in different super states on different levels is executed
/// then all states from the source up to the common super-state are exited and all states down to
/// the target state are entered. In this case the target state is higher than the source state.
/// </summary>
[Fact]
public void ExecuteTransitionBetweenStatesOnDifferentLevelsUpwards()
{
this.testee.Initialize(StateMachine.States.D1B);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.B1);
this.testee.CurrentStateId.Should().Be(StateMachine.States.B1);
this.CheckRecord<ExitRecord>(StateMachine.States.D1B);
this.CheckRecord<ExitRecord>(StateMachine.States.D1);
this.CheckRecord<ExitRecord>(StateMachine.States.D);
this.CheckRecord<EntryRecord>(StateMachine.States.B);
this.CheckRecord<EntryRecord>(StateMachine.States.B1);
this.CheckNoRemainingRecords();
}
/// <summary>
/// When a transition targets a super-state then the initial-state of this super-state is entered recursively
/// down to the most nested state. No history here!
/// </summary>
[Fact]
public void ExecuteTransitionWithInitialSubState()
{
this.testee.Initialize(StateMachine.States.A);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.B);
this.testee.CurrentStateId.Should().Be(StateMachine.States.B1);
this.CheckRecord<ExitRecord>(StateMachine.States.A);
this.CheckRecord<EntryRecord>(StateMachine.States.B);
this.CheckRecord<EntryRecord>(StateMachine.States.B1);
this.CheckNoRemainingRecords();
}
/// <summary>
/// When a transition targets a super-state with <see cref="HistoryType.None"/> then the initial
/// sub-state is entered whatever sub.state was last active.
/// </summary>
[Fact]
public void ExecuteTransitionWithHistoryTypeNone()
{
this.testee.Initialize(StateMachine.States.B2);
this.testee.EnterInitialState();
this.testee.Fire(StateMachine.Events.A);
this.ClearRecords();
this.testee.Fire(StateMachine.Events.B);
this.CheckRecord<ExitRecord>(StateMachine.States.A);
this.CheckRecord<EntryRecord>(StateMachine.States.B);
this.CheckRecord<EntryRecord>(StateMachine.States.B1);
this.CheckNoRemainingRecords();
}
/// <summary>
/// When a transition targets a super-state with <see cref="HistoryType.Shallow"/> then the last
/// active sub-state is entered and the initial-state of the entered sub-state is entered (no recursive history).
/// </summary>
[Fact]
public void ExecuteTransitionWithHistoryTypeShallow()
{
this.testee.Initialize(StateMachine.States.C1B);
this.testee.EnterInitialState();
this.testee.Fire(StateMachine.Events.A);
this.ClearRecords();
this.testee.Fire(StateMachine.Events.C);
this.testee.CurrentStateId.Should().Be(StateMachine.States.C1A);
this.CheckRecord<ExitRecord>(StateMachine.States.A);
this.CheckRecord<EntryRecord>(StateMachine.States.C);
this.CheckRecord<EntryRecord>(StateMachine.States.C1);
this.CheckRecord<EntryRecord>(StateMachine.States.C1A);
this.CheckNoRemainingRecords();
}
/// <summary>
/// When a transition targets a super-state with <see cref="HistoryType.Deep"/> then the last
/// active sub-state is entered recursively down to the most nested state.
/// </summary>
[Fact]
public void ExecuteTransitionWithHistoryTypeDeep()
{
this.testee.Initialize(StateMachine.States.D1B);
this.testee.EnterInitialState();
this.testee.Fire(StateMachine.Events.A);
this.ClearRecords();
this.testee.Fire(StateMachine.Events.D);
this.testee.CurrentStateId.Should().Be(StateMachine.States.D1B);
this.CheckRecord<ExitRecord>(StateMachine.States.A);
this.CheckRecord<EntryRecord>(StateMachine.States.D);
this.CheckRecord<EntryRecord>(StateMachine.States.D1);
this.CheckRecord<EntryRecord>(StateMachine.States.D1B);
this.CheckNoRemainingRecords();
}
/// <summary>
/// The state hierarchy is recursively walked up until a state can handle the event.
/// </summary>
[Fact]
public void ExecuteTransitionHandledBySuperState()
{
this.testee.Initialize(StateMachine.States.C1B);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.A);
this.testee.CurrentStateId.Should().Be(StateMachine.States.A);
this.CheckRecord<ExitRecord>(StateMachine.States.C1B);
this.CheckRecord<ExitRecord>(StateMachine.States.C1);
this.CheckRecord<ExitRecord>(StateMachine.States.C);
this.CheckRecord<EntryRecord>(StateMachine.States.A);
this.CheckNoRemainingRecords();
}
/// <summary>
/// Internal transitions do not trigger any exit or entry actions and the state machine remains in the same state.
/// </summary>
[Fact]
public void InternalTransition()
{
this.testee.Initialize(StateMachine.States.A);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.A);
this.testee.CurrentStateId.Should().Be(StateMachine.States.A);
}
[Fact]
public void ExecuteSelfTransition()
{
this.testee.Initialize(StateMachine.States.E);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.E);
this.testee.CurrentStateId.Should().Be(StateMachine.States.E);
this.CheckRecord<ExitRecord>(StateMachine.States.E);
this.CheckRecord<EntryRecord>(StateMachine.States.E);
this.CheckNoRemainingRecords();
}
[Fact]
public void ExecuteTransitionToNephew()
{
this.testee.Initialize(StateMachine.States.C1A);
this.testee.EnterInitialState();
this.ClearRecords();
this.testee.Fire(StateMachine.Events.C1B);
this.testee.CurrentStateId.Should().Be(StateMachine.States.C1B);
this.CheckRecord<ExitRecord>(StateMachine.States.C1A);
this.CheckRecord<EntryRecord>(StateMachine.States.C1B);
this.CheckNoRemainingRecords();
}
[Fact]
public void ExtensionsWhenExtensionsAreClearedThenNoExtensionIsRegistered()
{
bool executed = false;
var extension = A.Fake<IExtension<StateMachine.States, StateMachine.Events>>();
this.testee.AddExtension(extension);
this.testee.ClearExtensions();
this.testee.ForEach(e => executed = true);
executed
.Should().BeFalse();
}
/// <summary>
/// Records the entry into a state
/// </summary>
/// <param name="state">The state.</param>
private void RecordEntry(StateMachine.States state)
{
this.records.Add(new EntryRecord { State = state });
}
/// <summary>
/// Records the exit out of a state.
/// </summary>
/// <param name="state">The state.</param>
private void RecordExit(StateMachine.States state)
{
this.records.Add(new ExitRecord { State = state });
}
/// <summary>
/// Clears the records.
/// </summary>
private void ClearRecords()
{
this.records.Clear();
}
/// <summary>
/// Checks that the first record in the list of records is of type <typeparamref name="T"/> and involves the specified state.
/// The record is removed after the check.
/// </summary>
/// <typeparam name="T">Type of the record.</typeparam>
/// <param name="state">The state.</param>
private void CheckRecord<T>(StateMachine.States state) where T : Record
{
Record record = this.records.FirstOrDefault();
record.Should().NotBeNull();
record.Should().BeAssignableTo<T>();
// ReSharper disable once PossibleNullReferenceException
record.State.Should().Be(state, record.Message);
this.records.RemoveAt(0);
}
/// <summary>
/// Checks that no remaining records are present.
/// </summary>
private void CheckNoRemainingRecords()
{
if (this.records.Count == 0)
{
return;
}
var sb = new StringBuilder("there are additional records:");
foreach (string s in from record in this.records select record.GetType().Name + "-" + record.State)
{
sb.AppendLine();
sb.Append(s);
}
this.records.Should().BeEmpty(sb.ToString());
}
/// <summary>
/// A record of something that happened.
/// </summary>
[DebuggerDisplay("Message = {Message}")]
private abstract class Record
{
/// <summary>
/// Gets or sets the state.
/// </summary>
/// <value>The state.</value>
public StateMachine.States State { get; set; }
/// <summary>
/// Gets the message.
/// </summary>
/// <value>The message.</value>
public abstract string Message { get; }
}
/// <summary>
/// Record of a state entry.
/// </summary>
private class EntryRecord : Record
{
/// <summary>
/// Gets the message.
/// </summary>
/// <value>The message.</value>
public override string Message
{
get { return "State " + this.State + " not entered."; }
}
}
/// <summary>
/// Record of a state exit.
/// </summary>
private class ExitRecord : Record
{
/// <summary>
/// Gets the message.
/// </summary>
/// <value>The message.</value>
public override string Message
{
get { return "State " + this.State + " not exited."; }
}
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Index
{
/*
* 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 IBits = Lucene.Net.Util.IBits;
using MultiSortedDocValues = Lucene.Net.Index.MultiDocValues.MultiSortedDocValues;
using MultiSortedSetDocValues = Lucene.Net.Index.MultiDocValues.MultiSortedSetDocValues;
using OrdinalMap = Lucene.Net.Index.MultiDocValues.OrdinalMap;
/// <summary>
/// This class forces a composite reader (eg a
/// <see cref="MultiReader"/> or <see cref="DirectoryReader"/>) to emulate an
/// atomic reader. This requires implementing the postings
/// APIs on-the-fly, using the static methods in
/// <see cref="MultiFields"/>, <see cref="MultiDocValues"/>, by stepping through
/// the sub-readers to merge fields/terms, appending docs, etc.
///
/// <para/><b>NOTE</b>: This class almost always results in a
/// performance hit. If this is important to your use case,
/// you'll get better performance by gathering the sub readers using
/// <see cref="IndexReader.Context"/> to get the
/// atomic leaves and then operate per-AtomicReader,
/// instead of using this class.
/// </summary>
public sealed class SlowCompositeReaderWrapper : AtomicReader
{
private readonly CompositeReader @in;
private readonly Fields fields;
private readonly IBits liveDocs;
/// <summary>
/// This method is sugar for getting an <see cref="AtomicReader"/> from
/// an <see cref="IndexReader"/> of any kind. If the reader is already atomic,
/// it is returned unchanged, otherwise wrapped by this class.
/// </summary>
public static AtomicReader Wrap(IndexReader reader)
{
CompositeReader compositeReader = reader as CompositeReader;
if (compositeReader != null)
{
return new SlowCompositeReaderWrapper(compositeReader);
}
else
{
Debug.Assert(reader is AtomicReader);
return (AtomicReader)reader;
}
}
private SlowCompositeReaderWrapper(CompositeReader reader)
: base()
{
@in = reader;
fields = MultiFields.GetFields(@in);
liveDocs = MultiFields.GetLiveDocs(@in);
@in.RegisterParentReader(this);
}
public override string ToString()
{
return "SlowCompositeReaderWrapper(" + @in + ")";
}
public override Fields Fields
{
get
{
EnsureOpen();
return fields;
}
}
public override NumericDocValues GetNumericDocValues(string field)
{
EnsureOpen();
return MultiDocValues.GetNumericValues(@in, field);
}
public override IBits GetDocsWithField(string field)
{
EnsureOpen();
return MultiDocValues.GetDocsWithField(@in, field);
}
public override BinaryDocValues GetBinaryDocValues(string field)
{
EnsureOpen();
return MultiDocValues.GetBinaryValues(@in, field);
}
public override SortedDocValues GetSortedDocValues(string field)
{
EnsureOpen();
OrdinalMap map = null;
lock (cachedOrdMaps)
{
if (!cachedOrdMaps.TryGetValue(field, out map))
{
// uncached, or not a multi dv
SortedDocValues dv = MultiDocValues.GetSortedValues(@in, field);
MultiSortedDocValues docValues = dv as MultiSortedDocValues;
if (docValues != null)
{
map = docValues.Mapping;
if (map.owner == CoreCacheKey)
{
cachedOrdMaps[field] = map;
}
}
return dv;
}
}
// cached ordinal map
if (FieldInfos.FieldInfo(field).DocValuesType != DocValuesType.SORTED)
{
return null;
}
int size = @in.Leaves.Count;
SortedDocValues[] values = new SortedDocValues[size];
int[] starts = new int[size + 1];
for (int i = 0; i < size; i++)
{
AtomicReaderContext context = @in.Leaves[i];
SortedDocValues v = context.AtomicReader.GetSortedDocValues(field) ?? DocValues.EMPTY_SORTED;
values[i] = v;
starts[i] = context.DocBase;
}
starts[size] = MaxDoc;
return new MultiSortedDocValues(values, starts, map);
}
public override SortedSetDocValues GetSortedSetDocValues(string field)
{
EnsureOpen();
OrdinalMap map = null;
lock (cachedOrdMaps)
{
if (!cachedOrdMaps.TryGetValue(field, out map))
{
// uncached, or not a multi dv
SortedSetDocValues dv = MultiDocValues.GetSortedSetValues(@in, field);
MultiSortedSetDocValues docValues = dv as MultiSortedSetDocValues;
if (docValues != null)
{
map = docValues.Mapping;
if (map.owner == CoreCacheKey)
{
cachedOrdMaps[field] = map;
}
}
return dv;
}
}
// cached ordinal map
if (FieldInfos.FieldInfo(field).DocValuesType != DocValuesType.SORTED_SET)
{
return null;
}
Debug.Assert(map != null);
int size = @in.Leaves.Count;
var values = new SortedSetDocValues[size];
int[] starts = new int[size + 1];
for (int i = 0; i < size; i++)
{
AtomicReaderContext context = @in.Leaves[i];
SortedSetDocValues v = context.AtomicReader.GetSortedSetDocValues(field) ?? DocValues.EMPTY_SORTED_SET;
values[i] = v;
starts[i] = context.DocBase;
}
starts[size] = MaxDoc;
return new MultiSortedSetDocValues(values, starts, map);
}
// TODO: this could really be a weak map somewhere else on the coreCacheKey,
// but do we really need to optimize slow-wrapper any more?
private readonly IDictionary<string, OrdinalMap> cachedOrdMaps = new Dictionary<string, OrdinalMap>();
public override NumericDocValues GetNormValues(string field)
{
EnsureOpen();
return MultiDocValues.GetNormValues(@in, field);
}
public override Fields GetTermVectors(int docID)
{
EnsureOpen();
return @in.GetTermVectors(docID);
}
public override int NumDocs =>
// Don't call ensureOpen() here (it could affect performance)
@in.NumDocs;
public override int MaxDoc =>
// Don't call ensureOpen() here (it could affect performance)
@in.MaxDoc;
public override void Document(int docID, StoredFieldVisitor visitor)
{
EnsureOpen();
@in.Document(docID, visitor);
}
public override IBits LiveDocs
{
get
{
EnsureOpen();
return liveDocs;
}
}
public override FieldInfos FieldInfos
{
get
{
EnsureOpen();
return MultiFields.GetMergedFieldInfos(@in);
}
}
public override object CoreCacheKey => @in.CoreCacheKey;
public override object CombinedCoreAndDeletesKey => @in.CombinedCoreAndDeletesKey;
protected internal override void DoClose()
{
// TODO: as this is a wrapper, should we really close the delegate?
@in.Dispose();
}
public override void CheckIntegrity()
{
EnsureOpen();
foreach (AtomicReaderContext ctx in @in.Leaves)
{
ctx.AtomicReader.CheckIntegrity();
}
}
}
}
| |
using System;
using System.Collections;
using System.Reflection;
namespace CodeBureau
{
#region Class StringEnum
/// <summary>
/// Helper class for working with 'extended' enums using <see cref="StringValueAttribute"/> attributes.
/// </summary>
public class StringEnum
{
#region Instance implementation
private Type _enumType;
private static Hashtable _stringValues = new Hashtable();
/// <summary>
/// Creates a new <see cref="StringEnum"/> instance.
/// </summary>
/// <param name="enumType">Enum type.</param>
public StringEnum(Type enumType)
{
if (!enumType.IsEnum)
throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", enumType.ToString()));
_enumType = enumType;
}
/// <summary>
/// Gets the string value associated with the given enum value.
/// </summary>
/// <param name="valueName">Name of the enum value.</param>
/// <returns>String Value</returns>
public string GetStringValue(string valueName)
{
Enum enumType;
string stringValue = null;
try
{
enumType = (Enum) Enum.Parse(_enumType, valueName);
stringValue = GetStringValue(enumType);
}
catch (Exception) { }//Swallow!
return stringValue;
}
/// <summary>
/// Gets the string values associated with the enum.
/// </summary>
/// <returns>String value array</returns>
public Array GetStringValues()
{
ArrayList values = new ArrayList();
//Look for our string value associated with fields in this enum
foreach (FieldInfo fi in _enumType.GetFields())
{
//Check for our custom attribute
StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs.Length > 0)
values.Add(attrs[0].Value);
}
return values.ToArray();
}
/// <summary>
/// Gets the values as a 'bindable' list datasource.
/// </summary>
/// <returns>IList for data binding</returns>
public IList GetListValues()
{
Type underlyingType = Enum.GetUnderlyingType(_enumType);
ArrayList values = new ArrayList();
//Look for our string value associated with fields in this enum
foreach (FieldInfo fi in _enumType.GetFields())
{
//Check for our custom attribute
StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs.Length > 0)
values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));
}
return values;
}
/// <summary>
/// Return the existence of the given string value within the enum.
/// </summary>
/// <param name="stringValue">String value.</param>
/// <returns>Existence of the string value</returns>
public bool IsStringDefined(string stringValue)
{
return Parse(_enumType, stringValue) != null;
}
/// <summary>
/// Return the existence of the given string value within the enum.
/// </summary>
/// <param name="stringValue">String value.</param>
/// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
/// <returns>Existence of the string value</returns>
public bool IsStringDefined(string stringValue, bool ignoreCase)
{
return Parse(_enumType, stringValue, ignoreCase) != null;
}
/// <summary>
/// Gets the underlying enum type for this instance.
/// </summary>
/// <value></value>
public Type EnumType
{
get { return _enumType; }
}
#endregion
#region Static implementation
/// <summary>
/// Gets a string value for a particular enum value.
/// </summary>
/// <param name="value">Value.</param>
/// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns>
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
if (_stringValues.ContainsKey(value))
output = (_stringValues[value] as StringValueAttribute).Value;
else
{
//Look for our 'StringValueAttribute' in the field's custom attributes
FieldInfo fi = type.GetField(value.ToString());
StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs.Length > 0)
{
_stringValues.Add(value, attrs[0]);
output = attrs[0].Value;
}
}
return output;
}
/// <summary>
/// Parses the supplied enum and string value to find an associated enum value (case sensitive).
/// </summary>
/// <param name="type">Type.</param>
/// <param name="stringValue">String value.</param>
/// <returns>Enum value associated with the string value, or null if not found.</returns>
public static object Parse(Type type, string stringValue)
{
return Parse(type, stringValue, false);
}
/// <summary>
/// Parses the supplied enum and string value to find an associated enum value.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="stringValue">String value.</param>
/// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
/// <returns>Enum value associated with the string value, or null if not found.</returns>
public static object Parse(Type type, string stringValue, bool ignoreCase)
{
object output = null;
string enumStringValue = null;
if (!type.IsEnum)
throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", type.ToString()));
//Look for our string value associated with fields in this enum
foreach (FieldInfo fi in type.GetFields())
{
//Check for our custom attribute
StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs.Length > 0)
enumStringValue = attrs[0].Value;
//Check for equality then select actual enum value.
if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
{
output = Enum.Parse(type, fi.Name);
break;
}
}
return output;
}
/// <summary>
/// Return the existence of the given string value within the enum.
/// </summary>
/// <param name="stringValue">String value.</param>
/// <param name="enumType">Type of enum</param>
/// <returns>Existence of the string value</returns>
public static bool IsStringDefined(Type enumType, string stringValue)
{
return Parse(enumType, stringValue) != null;
}
/// <summary>
/// Return the existence of the given string value within the enum.
/// </summary>
/// <param name="stringValue">String value.</param>
/// <param name="enumType">Type of enum</param>
/// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
/// <returns>Existence of the string value</returns>
public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)
{
return Parse(enumType, stringValue, ignoreCase) != null;
}
#endregion
}
#endregion
#region Class StringValueAttribute
/// <summary>
/// Simple attribute class for storing String Values
/// </summary>
public class StringValueAttribute : Attribute
{
private string _value;
/// <summary>
/// Creates a new <see cref="StringValueAttribute"/> instance.
/// </summary>
/// <param name="value">Value.</param>
public StringValueAttribute(string value)
{
_value = value;
}
/// <summary>
/// Gets the value.
/// </summary>
/// <value></value>
public string Value
{
get { return _value; }
}
}
#endregion
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcav = Google.Cloud.AutoML.V1;
using sys = System;
namespace Google.Cloud.AutoML.V1
{
/// <summary>Resource name for the <c>AnnotationSpec</c> resource.</summary>
public sealed partial class AnnotationSpecName : gax::IResourceName, sys::IEquatable<AnnotationSpecName>
{
/// <summary>The possible contents of <see cref="AnnotationSpecName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </summary>
ProjectLocationDatasetAnnotationSpec = 1,
}
private static gax::PathTemplate s_projectLocationDatasetAnnotationSpec = new gax::PathTemplate("projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}");
/// <summary>Creates a <see cref="AnnotationSpecName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AnnotationSpecName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AnnotationSpecName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AnnotationSpecName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AnnotationSpecName"/> with the pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecId">The <c>AnnotationSpec</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AnnotationSpecName"/> constructed from the provided ids.</returns>
public static AnnotationSpecName FromProjectLocationDatasetAnnotationSpec(string projectId, string locationId, string datasetId, string annotationSpecId) =>
new AnnotationSpecName(ResourceNameType.ProjectLocationDatasetAnnotationSpec, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), annotationSpecId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecId, nameof(annotationSpecId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AnnotationSpecName"/> with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecId">The <c>AnnotationSpec</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AnnotationSpecName"/> with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string datasetId, string annotationSpecId) =>
FormatProjectLocationDatasetAnnotationSpec(projectId, locationId, datasetId, annotationSpecId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AnnotationSpecName"/> with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecId">The <c>AnnotationSpec</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AnnotationSpecName"/> with pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>.
/// </returns>
public static string FormatProjectLocationDatasetAnnotationSpec(string projectId, string locationId, string datasetId, string annotationSpecId) =>
s_projectLocationDatasetAnnotationSpec.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecId, nameof(annotationSpecId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AnnotationSpecName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="annotationSpecName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AnnotationSpecName"/> if successful.</returns>
public static AnnotationSpecName Parse(string annotationSpecName) => Parse(annotationSpecName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AnnotationSpecName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="annotationSpecName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AnnotationSpecName"/> if successful.</returns>
public static AnnotationSpecName Parse(string annotationSpecName, bool allowUnparsed) =>
TryParse(annotationSpecName, allowUnparsed, out AnnotationSpecName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AnnotationSpecName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="annotationSpecName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AnnotationSpecName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string annotationSpecName, out AnnotationSpecName result) =>
TryParse(annotationSpecName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AnnotationSpecName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="annotationSpecName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AnnotationSpecName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string annotationSpecName, bool allowUnparsed, out AnnotationSpecName result)
{
gax::GaxPreconditions.CheckNotNull(annotationSpecName, nameof(annotationSpecName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationDatasetAnnotationSpec.TryParseName(annotationSpecName, out resourceName))
{
result = FromProjectLocationDatasetAnnotationSpec(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(annotationSpecName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AnnotationSpecName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string annotationSpecId = null, string datasetId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AnnotationSpecId = annotationSpecId;
DatasetId = datasetId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AnnotationSpecName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecId">The <c>AnnotationSpec</c> ID. Must not be <c>null</c> or empty.</param>
public AnnotationSpecName(string projectId, string locationId, string datasetId, string annotationSpecId) : this(ResourceNameType.ProjectLocationDatasetAnnotationSpec, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), annotationSpecId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecId, nameof(annotationSpecId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AnnotationSpec</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string AnnotationSpecId { get; }
/// <summary>
/// The <c>Dataset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DatasetId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationDatasetAnnotationSpec: return s_projectLocationDatasetAnnotationSpec.Expand(ProjectId, LocationId, DatasetId, AnnotationSpecId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AnnotationSpecName);
/// <inheritdoc/>
public bool Equals(AnnotationSpecName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AnnotationSpecName a, AnnotationSpecName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AnnotationSpecName a, AnnotationSpecName b) => !(a == b);
}
public partial class AnnotationSpec
{
/// <summary>
/// <see cref="gcav::AnnotationSpecName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::AnnotationSpecName AnnotationSpecName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::AnnotationSpecName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace ProjectWithSecurity.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Diagnostics;
namespace Maziacs
{
public class Maze
{
//public Cell[,] Cells;
public Cell[] Cells;
public Cell StartCell;
public Cell GoalCell;
public Cell LastRebuildTarget;
List<Cell> visitedCells;
public List<Cell> solutionPath;
int width;
int height;
int difficulty;
public enum State
{
Wall,
Out,
Frontier,
Path,
Prisoner,
Sword,
Food,
Treasure,
Start
}
Random random = new Random();
public void Initialize(int width, int height, int difficulty)
{
this.width = width;
this.height = height;
this.difficulty = difficulty;
Cells = new Cell[this.width * this.height];
visitedCells = new List<Cell>();
solutionPath = new List<Cell>();
}
private int[] PickRandomCell()
{
int x, y;
x = random.Next(1, width - 2);
y = random.Next(1, height - 2);
if (x % 2 == 0)
{
x = (x > width / 2) ? x - 1 : x + 1;
}
if (y % 2 == 0)
{
y = (y > height / 2) ? y - 1 : y + 1;
}
return new int[2] { x, y };
}
private List<int[]> FindNeighbours(int x, int y, State state)
{
int d;
int[] dx = { 0, 0, -2, 2 };
int[] dy = { -2, 2, 0, 0 };
List<int[]> neighbours = new List<int[]>();
for (d = 0; d < 4; d++)
{
if (x + dx[d] > 0 && x + dx[d] < width - 1 && y + dy[d] > 0 && y + dy[d] < height - 1 && Cells[(x + dx[d]) + (y + dy[d]) * width].State == state)
{
neighbours.Add(new int[] { x + dx[d], y + dy[d] });
}
}
return neighbours;
}
private List<Cell> FindNeighbours(Cell t, State state)
{
int d;
int[] dx = { 0, 0, -1, 1 };
int[] dy = { -1, 1, 0, 0 };
List<Cell> neighbours = new List<Cell>();
for (d = 0; d < 4; d++)
{
if (t.X + dx[d] > 0 && t.X + dx[d] < width - 1 && t.Y + dy[d] > 0 && t.Y + dy[d] < height - 1 && Cells[(t.X + dx[d]) + (t.Y + dy[d]) * width].State == state)
{
Cell o = Cells[(t.X + dx[d]) + (t.Y + dy[d]) * width];
if (o.Visited == false)
{
neighbours.Add(o);
}
}
}
return neighbours;
}
private int[] FindRandomNeighbour(int x, int y, State state)
{
int d;
int[] dx = { 0, 0, -2, 2 };
int[] dy = { -2, 2, 0, 0 };
do
{
d = random.Next(4);
}
while (x + dx[d] < 0 || x + dx[d] > width - 1 || y + dy[d] < 0 || y + dy[d] > height - 1 || Cells[(x + dx[d]) + (y + dy[d]) * width].State < state);
return new int[] { dx[d], dy[d] };
}
private Cell FindRandomStart()
{
DateTime tstart = DateTime.Now;
int x, y;
Cell start = new Cell();
bool found = false;
do
{
int[] randomCell = PickRandomCell();
x = randomCell[0];
y = randomCell[1];
List<Cell> neighbours = FindNeighbours(Cells[x + y * width], State.Wall);
if (neighbours.Count == 3 && Cells[x + y * width].Distance > GameSettings.MinimumDistance[difficulty] && Cells[x + y * width].Distance < GameSettings.MaximumDistance[difficulty])
{
start = Cells[x + y * width];
start.State = State.Start;
found = true;
}
}
while (found == false);
return start;
}
private Cell FindRandomGoal()
{
int x, y;
Cell goal = new Cell();
bool found = false;
do
{
int[] randomCell = PickRandomCell();
x = randomCell[0];
y = randomCell[1];
List<Cell> neighbours = FindNeighbours(Cells[x + y * width], State.Wall);
if (neighbours.Count == 3)
{
goal = Cells[x + y * width];
goal.State = State.Treasure;
found = true;
}
}
while (found == false);
return goal;
}
public void PlaceRandomItems()
{
List<Cell> itemCells = new List<Cell>();
int x, y, count, rnd;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
if (Cells[x + y * width].State == State.Wall)
{
List<Cell> neighbours = FindNeighbours(Cells[x + y * width], State.Path);
if (neighbours.Count > 0)
{
itemCells.Add(Cells[x + y * width]);
}
}
}
}
count = 0;
while (count < GameSettings.Prisoners[difficulty])
{
rnd = random.Next(0, itemCells.Count);
Cell c = itemCells[rnd];
c.State = State.Prisoner;
itemCells.RemoveAt(rnd);
count++;
}
count = 0;
while (count < GameSettings.Swords[difficulty])
{
rnd = random.Next(0, itemCells.Count);
Cell c = itemCells[rnd];
c.State = State.Sword;
itemCells.RemoveAt(rnd);
count++;
}
count = 0;
while (count < GameSettings.Food[difficulty])
{
rnd = random.Next(0, itemCells.Count);
Cell c = itemCells[rnd];
c.State = State.Food;
itemCells.RemoveAt(rnd);
count++;
}
}
public void Generate()
{
int x, y, n;
int[][] todo = new int[width * height][];
int todonum = 0;
Cells = new Cell[width * height];
List<int[]> neighbours;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
// Mark all even cells as Wall.
if (x % 2 == 0 || y % 2 == 0)
{
Cells[x + y * width] = new Cell();
Cells[x + y * width].X = x;
Cells[x + y * width].Y = y;
Cells[x + y * width].State = State.Wall;
}
// Mark the rest as Out.
else
{
Cells[x + y * width] = new Cell();
Cells[x + y * width].X = x;
Cells[x + y * width].Y = y;
Cells[x + y * width].State = State.Out;
}
}
}
// Pick a random cell and mark it Path.
int[] randomCell = PickRandomCell();
x = randomCell[0];
y = randomCell[1];
Cells[x + y * width].X = x;
Cells[x + y * width].Y = y;
Cells[x + y * width].State = State.Path;
// Mark all neighbours of current cell as Frontier.
neighbours = FindNeighbours(x, y, State.Out);
foreach (int[] neighbour in neighbours)
{
todo[todonum++] = neighbour;
Cells[neighbour[0] + neighbour[1] * width].State = State.Frontier;
}
while (todonum > 0)
{
// Pick a random cell from Frontier and mark it as Path.
n = random.Next(todonum);
x = todo[n][0];
y = todo[n][1];
todo[n] = todo[--todonum];
// Mark current cell as State.Path
Cells[x + y * width].State = State.Path;
// Pick a random neighbour of current cell that is Path and mark the cell between it as Path.
int[] randomNeighbour = FindRandomNeighbour(x, y, State.Path);
Cells[(((x + randomNeighbour[0] / 2) + (y + randomNeighbour[1] / 2) * width))].State = State.Path;
// Mark all neighbours of current cell as State.Frontier
neighbours = FindNeighbours(x, y, State.Out);
foreach (int[] neighbour in neighbours)
{
todo[todonum++] = neighbour;
Cells[neighbour[0] + neighbour[1] * width].State = State.Frontier;
}
}
PlaceRandomItems();
// Find random goal location enclosed with 3 walls
GoalCell = FindRandomGoal();
BuildDistanceTable(GoalCell);
// Find random starting location enclosed with 3 walls
StartCell = FindRandomStart();
}
public void BuildDistanceTable(Cell start)
{
LastRebuildTarget = start;
List<Cell>[] distanceTable = new List<Cell>[width * height];
int i = 0;
start.Visited = true;
start.Distance = i;
distanceTable[i] = new List<Cell>();
distanceTable[i].Add(start);
while (distanceTable[i].Count > 0)
{
distanceTable[i + 1] = new List<Cell>();
foreach (Cell t in distanceTable[i])
{
List<Cell> neighbours = FindNeighbours(t, State.Path);
foreach (Cell o in neighbours)
{
o.Visited = true;
o.Distance = i + 1;
distanceTable[i + 1].Add(o);
}
}
i++;
}
i = 0;
while (distanceTable[i].Count > 0)
{
foreach (Cell t in distanceTable[i])
{
t.Visited = false;
}
distanceTable[i].Clear();
i++;
}
}
public void ClearPath()
{
foreach (Cell o in solutionPath)
{
o.IsSolution = false;
}
solutionPath.Clear();
}
public void FindPath(Cell start, Cell goal)
{
int i;
// Clear previous path.
ClearPath();
if (start == goal)
{
return;
}
i = goal.Distance;
Cell c = goal;
solutionPath.Add(c);
while (i >= 0)
{
c.IsSolution = true;
List<Cell> neighbours = FindNeighbours(c, State.Path);
foreach (Cell o in neighbours)
{
if (o.Distance < i)
{
solutionPath.Add(o);
c = o;
break;
}
}
i--;
}
}
}
}
| |
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* This public class is a modified version of Robert Penner's Actionscript 2 easing equations
* which are available under the following licence from http://www.robertpenner.com/easing/
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright (c) 2001 Robert Penner
* 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 the author nor the names of 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.
*
* ==================================================
*
* Modifications:
*
* Author: Richard Lord (Big Room)
* C# Port: Ben Baker (HeadSoft)
* Copyright (c) Big Room Ventures Ltd. 2008
* http://flintparticles.org
*
*
* Used in the Flint Particle System which is licenced under the MIT license. As per the
* original license for Robert Penner's public classes, these specific public classes are released under
* the BSD License.
*/
using FlintSharp.Behaviours;
using FlintSharp.Activities;
using FlintSharp.Counters;
using FlintSharp.Easing;
using FlintSharp.Emitters;
using FlintSharp.EnergyEasing;
using FlintSharp.Initializers;
using FlintSharp.Particles;
using FlintSharp.Zones;
namespace FlintSharp.EnergyEasing
{
public delegate double EnergyEasingDelegate(double age, double lifetime);
public static class EasingFunction
{
public static EnergyEasingDelegate GetEasingFunction(EaseCategory easeCategory, EaseType easeType)
{
switch (easeCategory)
{
case EaseCategory.Linear:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Linear.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Linear.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Linear.EaseInOut);
case EaseType.None:
return new EnergyEasingDelegate(Linear.EaseNone);
}
break;
case EaseCategory.Quadratic:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Quadratic.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Quadratic.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Quadratic.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Cubic:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Cubic.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Cubic.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Cubic.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Quartic:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Quartic.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Quartic.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Quartic.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Quintic:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Quintic.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Quintic.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Quintic.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Sine:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Sine.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Sine.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Sine.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Exponential:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Exponential.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Exponential.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Exponential.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Circular:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Circular.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Circular.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Circular.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Elastic:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Elastic.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Elastic.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Elastic.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Back:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Back.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Back.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Back.EaseInOut);
case EaseType.None:
break;
}
break;
case EaseCategory.Bounce:
switch (easeType)
{
case EaseType.In:
return new EnergyEasingDelegate(Bounce.EaseIn);
case EaseType.Out:
return new EnergyEasingDelegate(Bounce.EaseOut);
case EaseType.InOut:
return new EnergyEasingDelegate(Bounce.EaseInOut);
case EaseType.None:
break;
}
break;
}
return new EnergyEasingDelegate(Linear.EaseNone);
}
}
}
| |
using System;
namespace Renci.SshNet.Security.Org.BouncyCastle.Math.EC.Abc
{
/**
* Class holding methods for point multiplication based on the window
* τ-adic nonadjacent form (WTNAF). The algorithms are based on the
* paper "Improved Algorithms for Arithmetic on Anomalous Binary Curves"
* by Jerome A. Solinas. The paper first appeared in the Proceedings of
* Crypto 1997.
*/
internal class Tnaf
{
private static readonly BigInteger MinusOne = BigInteger.One.Negate();
private static readonly BigInteger MinusTwo = BigInteger.Two.Negate();
private static readonly BigInteger MinusThree = BigInteger.Three.Negate();
private static readonly BigInteger Four = BigInteger.ValueOf(4);
/**
* The window width of WTNAF. The standard value of 4 is slightly less
* than optimal for running time, but keeps space requirements for
* precomputation low. For typical curves, a value of 5 or 6 results in
* a better running time. When changing this value, the
* <code>α<sub>u</sub></code>'s must be computed differently, see
* e.g. "Guide to Elliptic Curve Cryptography", Darrel Hankerson,
* Alfred Menezes, Scott Vanstone, Springer-Verlag New York Inc., 2004,
* p. 121-122
*/
public const sbyte Width = 4;
/**
* 2<sup>4</sup>
*/
public const sbyte Pow2Width = 16;
/**
* The <code>α<sub>u</sub></code>'s for <code>a=0</code> as an array
* of <code>ZTauElement</code>s.
*/
public static readonly ZTauElement[] Alpha0 =
{
null,
new ZTauElement(BigInteger.One, BigInteger.Zero), null,
new ZTauElement(MinusThree, MinusOne), null,
new ZTauElement(MinusOne, MinusOne), null,
new ZTauElement(BigInteger.One, MinusOne), null
};
/**
* The <code>α<sub>u</sub></code>'s for <code>a=0</code> as an array
* of TNAFs.
*/
public static readonly sbyte[][] Alpha0Tnaf =
{
null, new sbyte[]{1}, null, new sbyte[]{-1, 0, 1}, null, new sbyte[]{1, 0, 1}, null, new sbyte[]{-1, 0, 0, 1}
};
/**
* The <code>α<sub>u</sub></code>'s for <code>a=1</code> as an array
* of <code>ZTauElement</code>s.
*/
public static readonly ZTauElement[] Alpha1 =
{
null,
new ZTauElement(BigInteger.One, BigInteger.Zero), null,
new ZTauElement(MinusThree, BigInteger.One), null,
new ZTauElement(MinusOne, BigInteger.One), null,
new ZTauElement(BigInteger.One, BigInteger.One), null
};
/**
* The <code>α<sub>u</sub></code>'s for <code>a=1</code> as an array
* of TNAFs.
*/
public static readonly sbyte[][] Alpha1Tnaf =
{
null, new sbyte[]{1}, null, new sbyte[]{-1, 0, 1}, null, new sbyte[]{1, 0, 1}, null, new sbyte[]{-1, 0, 0, -1}
};
/**
* Computes the norm of an element <code>λ</code> of
* <code><b>Z</b>[τ]</code>.
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param lambda The element <code>λ</code> of
* <code><b>Z</b>[τ]</code>.
* @return The norm of <code>λ</code>.
*/
public static BigInteger Norm(sbyte mu, ZTauElement lambda)
{
BigInteger norm;
// s1 = u^2
BigInteger s1 = lambda.u.Multiply(lambda.u);
// s2 = u * v
BigInteger s2 = lambda.u.Multiply(lambda.v);
// s3 = 2 * v^2
BigInteger s3 = lambda.v.Multiply(lambda.v).ShiftLeft(1);
if (mu == 1)
{
norm = s1.Add(s2).Add(s3);
}
else if (mu == -1)
{
norm = s1.Subtract(s2).Add(s3);
}
else
{
throw new ArgumentException("mu must be 1 or -1");
}
return norm;
}
/**
* Computes the norm of an element <code>λ</code> of
* <code><b>R</b>[τ]</code>, where <code>λ = u + vτ</code>
* and <code>u</code> and <code>u</code> are real numbers (elements of
* <code><b>R</b></code>).
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param u The real part of the element <code>λ</code> of
* <code><b>R</b>[τ]</code>.
* @param v The <code>τ</code>-adic part of the element
* <code>λ</code> of <code><b>R</b>[τ]</code>.
* @return The norm of <code>λ</code>.
*/
public static SimpleBigDecimal Norm(sbyte mu, SimpleBigDecimal u, SimpleBigDecimal v)
{
SimpleBigDecimal norm;
// s1 = u^2
SimpleBigDecimal s1 = u.Multiply(u);
// s2 = u * v
SimpleBigDecimal s2 = u.Multiply(v);
// s3 = 2 * v^2
SimpleBigDecimal s3 = v.Multiply(v).ShiftLeft(1);
if (mu == 1)
{
norm = s1.Add(s2).Add(s3);
}
else if (mu == -1)
{
norm = s1.Subtract(s2).Add(s3);
}
else
{
throw new ArgumentException("mu must be 1 or -1");
}
return norm;
}
/**
* Rounds an element <code>λ</code> of <code><b>R</b>[τ]</code>
* to an element of <code><b>Z</b>[τ]</code>, such that their difference
* has minimal norm. <code>λ</code> is given as
* <code>λ = λ<sub>0</sub> + λ<sub>1</sub>τ</code>.
* @param lambda0 The component <code>λ<sub>0</sub></code>.
* @param lambda1 The component <code>λ<sub>1</sub></code>.
* @param mu The parameter <code>μ</code> of the elliptic curve. Must
* equal 1 or -1.
* @return The rounded element of <code><b>Z</b>[τ]</code>.
* @throws ArgumentException if <code>lambda0</code> and
* <code>lambda1</code> do not have same scale.
*/
public static ZTauElement Round(SimpleBigDecimal lambda0,
SimpleBigDecimal lambda1, sbyte mu)
{
int scale = lambda0.Scale;
if (lambda1.Scale != scale)
throw new ArgumentException("lambda0 and lambda1 do not have same scale");
if (!((mu == 1) || (mu == -1)))
throw new ArgumentException("mu must be 1 or -1");
BigInteger f0 = lambda0.Round();
BigInteger f1 = lambda1.Round();
SimpleBigDecimal eta0 = lambda0.Subtract(f0);
SimpleBigDecimal eta1 = lambda1.Subtract(f1);
// eta = 2*eta0 + mu*eta1
SimpleBigDecimal eta = eta0.Add(eta0);
if (mu == 1)
{
eta = eta.Add(eta1);
}
else
{
// mu == -1
eta = eta.Subtract(eta1);
}
// check1 = eta0 - 3*mu*eta1
// check2 = eta0 + 4*mu*eta1
SimpleBigDecimal threeEta1 = eta1.Add(eta1).Add(eta1);
SimpleBigDecimal fourEta1 = threeEta1.Add(eta1);
SimpleBigDecimal check1;
SimpleBigDecimal check2;
if (mu == 1)
{
check1 = eta0.Subtract(threeEta1);
check2 = eta0.Add(fourEta1);
}
else
{
// mu == -1
check1 = eta0.Add(threeEta1);
check2 = eta0.Subtract(fourEta1);
}
sbyte h0 = 0;
sbyte h1 = 0;
// if eta >= 1
if (eta.CompareTo(BigInteger.One) >= 0)
{
if (check1.CompareTo(MinusOne) < 0)
{
h1 = mu;
}
else
{
h0 = 1;
}
}
else
{
// eta < 1
if (check2.CompareTo(BigInteger.Two) >= 0)
{
h1 = mu;
}
}
// if eta < -1
if (eta.CompareTo(MinusOne) < 0)
{
if (check1.CompareTo(BigInteger.One) >= 0)
{
h1 = (sbyte)-mu;
}
else
{
h0 = -1;
}
}
else
{
// eta >= -1
if (check2.CompareTo(MinusTwo) < 0)
{
h1 = (sbyte)-mu;
}
}
BigInteger q0 = f0.Add(BigInteger.ValueOf(h0));
BigInteger q1 = f1.Add(BigInteger.ValueOf(h1));
return new ZTauElement(q0, q1);
}
/**
* Approximate division by <code>n</code>. For an integer
* <code>k</code>, the value <code>λ = s k / n</code> is
* computed to <code>c</code> bits of accuracy.
* @param k The parameter <code>k</code>.
* @param s The curve parameter <code>s<sub>0</sub></code> or
* <code>s<sub>1</sub></code>.
* @param vm The Lucas Sequence element <code>V<sub>m</sub></code>.
* @param a The parameter <code>a</code> of the elliptic curve.
* @param m The bit length of the finite field
* <code><b>F</b><sub>m</sub></code>.
* @param c The number of bits of accuracy, i.e. the scale of the returned
* <code>SimpleBigDecimal</code>.
* @return The value <code>λ = s k / n</code> computed to
* <code>c</code> bits of accuracy.
*/
public static SimpleBigDecimal ApproximateDivisionByN(BigInteger k,
BigInteger s, BigInteger vm, sbyte a, int m, int c)
{
int _k = (m + 5)/2 + c;
BigInteger ns = k.ShiftRight(m - _k - 2 + a);
BigInteger gs = s.Multiply(ns);
BigInteger hs = gs.ShiftRight(m);
BigInteger js = vm.Multiply(hs);
BigInteger gsPlusJs = gs.Add(js);
BigInteger ls = gsPlusJs.ShiftRight(_k-c);
if (gsPlusJs.TestBit(_k-c-1))
{
// round up
ls = ls.Add(BigInteger.One);
}
return new SimpleBigDecimal(ls, c);
}
/**
* Computes the <code>τ</code>-adic NAF (non-adjacent form) of an
* element <code>λ</code> of <code><b>Z</b>[τ]</code>.
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param lambda The element <code>λ</code> of
* <code><b>Z</b>[τ]</code>.
* @return The <code>τ</code>-adic NAF of <code>λ</code>.
*/
public static sbyte[] TauAdicNaf(sbyte mu, ZTauElement lambda)
{
if (!((mu == 1) || (mu == -1)))
throw new ArgumentException("mu must be 1 or -1");
BigInteger norm = Norm(mu, lambda);
// Ceiling of log2 of the norm
int log2Norm = norm.BitLength;
// If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52
int maxLength = log2Norm > 30 ? log2Norm + 4 : 34;
// The array holding the TNAF
sbyte[] u = new sbyte[maxLength];
int i = 0;
// The actual length of the TNAF
int length = 0;
BigInteger r0 = lambda.u;
BigInteger r1 = lambda.v;
while(!((r0.Equals(BigInteger.Zero)) && (r1.Equals(BigInteger.Zero))))
{
// If r0 is odd
if (r0.TestBit(0))
{
u[i] = (sbyte) BigInteger.Two.Subtract((r0.Subtract(r1.ShiftLeft(1))).Mod(Four)).IntValue;
// r0 = r0 - u[i]
if (u[i] == 1)
{
r0 = r0.ClearBit(0);
}
else
{
// u[i] == -1
r0 = r0.Add(BigInteger.One);
}
length = i;
}
else
{
u[i] = 0;
}
BigInteger t = r0;
BigInteger s = r0.ShiftRight(1);
if (mu == 1)
{
r0 = r1.Add(s);
}
else
{
// mu == -1
r0 = r1.Subtract(s);
}
r1 = t.ShiftRight(1).Negate();
i++;
}
length++;
// Reduce the TNAF array to its actual length
sbyte[] tnaf = new sbyte[length];
Array.Copy(u, 0, tnaf, 0, length);
return tnaf;
}
/**
* Applies the operation <code>τ()</code> to an
* <code>AbstractF2mPoint</code>.
* @param p The AbstractF2mPoint to which <code>τ()</code> is applied.
* @return <code>τ(p)</code>
*/
public static AbstractF2mPoint Tau(AbstractF2mPoint p)
{
return p.Tau();
}
/**
* Returns the parameter <code>μ</code> of the elliptic curve.
* @param curve The elliptic curve from which to obtain <code>μ</code>.
* The curve must be a Koblitz curve, i.e. <code>a</code> Equals
* <code>0</code> or <code>1</code> and <code>b</code> Equals
* <code>1</code>.
* @return <code>μ</code> of the elliptic curve.
* @throws ArgumentException if the given ECCurve is not a Koblitz
* curve.
*/
public static sbyte GetMu(AbstractF2mCurve curve)
{
BigInteger a = curve.A.ToBigInteger();
sbyte mu;
if (a.SignValue == 0)
{
mu = -1;
}
else if (a.Equals(BigInteger.One))
{
mu = 1;
}
else
{
throw new ArgumentException("No Koblitz curve (ABC), TNAF multiplication not possible");
}
return mu;
}
public static sbyte GetMu(ECFieldElement curveA)
{
return (sbyte)(curveA.IsZero ? -1 : 1);
}
public static sbyte GetMu(int curveA)
{
return (sbyte)(curveA == 0 ? -1 : 1);
}
/**
* Calculates the Lucas Sequence elements <code>U<sub>k-1</sub></code> and
* <code>U<sub>k</sub></code> or <code>V<sub>k-1</sub></code> and
* <code>V<sub>k</sub></code>.
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param k The index of the second element of the Lucas Sequence to be
* returned.
* @param doV If set to true, computes <code>V<sub>k-1</sub></code> and
* <code>V<sub>k</sub></code>, otherwise <code>U<sub>k-1</sub></code> and
* <code>U<sub>k</sub></code>.
* @return An array with 2 elements, containing <code>U<sub>k-1</sub></code>
* and <code>U<sub>k</sub></code> or <code>V<sub>k-1</sub></code>
* and <code>V<sub>k</sub></code>.
*/
public static BigInteger[] GetLucas(sbyte mu, int k, bool doV)
{
if (!(mu == 1 || mu == -1))
throw new ArgumentException("mu must be 1 or -1");
BigInteger u0;
BigInteger u1;
BigInteger u2;
if (doV)
{
u0 = BigInteger.Two;
u1 = BigInteger.ValueOf(mu);
}
else
{
u0 = BigInteger.Zero;
u1 = BigInteger.One;
}
for (int i = 1; i < k; i++)
{
// u2 = mu*u1 - 2*u0;
BigInteger s = null;
if (mu == 1)
{
s = u1;
}
else
{
// mu == -1
s = u1.Negate();
}
u2 = s.Subtract(u0.ShiftLeft(1));
u0 = u1;
u1 = u2;
// System.out.println(i + ": " + u2);
// System.out.println();
}
BigInteger[] retVal = {u0, u1};
return retVal;
}
/**
* Computes the auxiliary value <code>t<sub>w</sub></code>. If the width is
* 4, then for <code>mu = 1</code>, <code>t<sub>w</sub> = 6</code> and for
* <code>mu = -1</code>, <code>t<sub>w</sub> = 10</code>
* @param mu The parameter <code>μ</code> of the elliptic curve.
* @param w The window width of the WTNAF.
* @return the auxiliary value <code>t<sub>w</sub></code>
*/
public static BigInteger GetTw(sbyte mu, int w)
{
if (w == 4)
{
if (mu == 1)
{
return BigInteger.ValueOf(6);
}
else
{
// mu == -1
return BigInteger.ValueOf(10);
}
}
else
{
// For w <> 4, the values must be computed
BigInteger[] us = GetLucas(mu, w, false);
BigInteger twoToW = BigInteger.Zero.SetBit(w);
BigInteger u1invert = us[1].ModInverse(twoToW);
BigInteger tw;
tw = BigInteger.Two.Multiply(us[0]).Multiply(u1invert).Mod(twoToW);
//System.out.println("mu = " + mu);
//System.out.println("tw = " + tw);
return tw;
}
}
/**
* Computes the auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code> used for partial modular reduction.
* @param curve The elliptic curve for which to compute
* <code>s<sub>0</sub></code> and <code>s<sub>1</sub></code>.
* @throws ArgumentException if <code>curve</code> is not a
* Koblitz curve (Anomalous Binary Curve, ABC).
*/
public static BigInteger[] GetSi(AbstractF2mCurve curve)
{
if (!curve.IsKoblitz)
throw new ArgumentException("si is defined for Koblitz curves only");
int m = curve.FieldSize;
int a = curve.A.ToBigInteger().IntValue;
sbyte mu = GetMu(a);
int shifts = GetShiftsForCofactor(curve.Cofactor);
int index = m + 3 - a;
BigInteger[] ui = GetLucas(mu, index, false);
if (mu == 1)
{
ui[0] = ui[0].Negate();
ui[1] = ui[1].Negate();
}
BigInteger dividend0 = BigInteger.One.Add(ui[1]).ShiftRight(shifts);
BigInteger dividend1 = BigInteger.One.Add(ui[0]).ShiftRight(shifts).Negate();
return new BigInteger[] { dividend0, dividend1 };
}
public static BigInteger[] GetSi(int fieldSize, int curveA, BigInteger cofactor)
{
sbyte mu = GetMu(curveA);
int shifts = GetShiftsForCofactor(cofactor);
int index = fieldSize + 3 - curveA;
BigInteger[] ui = GetLucas(mu, index, false);
if (mu == 1)
{
ui[0] = ui[0].Negate();
ui[1] = ui[1].Negate();
}
BigInteger dividend0 = BigInteger.One.Add(ui[1]).ShiftRight(shifts);
BigInteger dividend1 = BigInteger.One.Add(ui[0]).ShiftRight(shifts).Negate();
return new BigInteger[] { dividend0, dividend1 };
}
protected static int GetShiftsForCofactor(BigInteger h)
{
if (h != null && h.BitLength < 4)
{
int hi = h.IntValue;
if (hi == 2)
return 1;
if (hi == 4)
return 2;
}
throw new ArgumentException("h (Cofactor) must be 2 or 4");
}
/**
* Partial modular reduction modulo
* <code>(τ<sup>m</sup> - 1)/(τ - 1)</code>.
* @param k The integer to be reduced.
* @param m The bitlength of the underlying finite field.
* @param a The parameter <code>a</code> of the elliptic curve.
* @param s The auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code>.
* @param mu The parameter μ of the elliptic curve.
* @param c The precision (number of bits of accuracy) of the partial
* modular reduction.
* @return <code>ρ := k partmod (τ<sup>m</sup> - 1)/(τ - 1)</code>
*/
public static ZTauElement PartModReduction(BigInteger k, int m, sbyte a,
BigInteger[] s, sbyte mu, sbyte c)
{
// d0 = s[0] + mu*s[1]; mu is either 1 or -1
BigInteger d0;
if (mu == 1)
{
d0 = s[0].Add(s[1]);
}
else
{
d0 = s[0].Subtract(s[1]);
}
BigInteger[] v = GetLucas(mu, m, true);
BigInteger vm = v[1];
SimpleBigDecimal lambda0 = ApproximateDivisionByN(
k, s[0], vm, a, m, c);
SimpleBigDecimal lambda1 = ApproximateDivisionByN(
k, s[1], vm, a, m, c);
ZTauElement q = Round(lambda0, lambda1, mu);
// r0 = n - d0*q0 - 2*s1*q1
BigInteger r0 = k.Subtract(d0.Multiply(q.u)).Subtract(
BigInteger.ValueOf(2).Multiply(s[1]).Multiply(q.v));
// r1 = s1*q0 - s0*q1
BigInteger r1 = s[1].Multiply(q.u).Subtract(s[0].Multiply(q.v));
return new ZTauElement(r0, r1);
}
/**
* Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
* by a <code>BigInteger</code> using the reduced <code>τ</code>-adic
* NAF (RTNAF) method.
* @param p The AbstractF2mPoint to Multiply.
* @param k The <code>BigInteger</code> by which to Multiply <code>p</code>.
* @return <code>k * p</code>
*/
public static AbstractF2mPoint MultiplyRTnaf(AbstractF2mPoint p, BigInteger k)
{
AbstractF2mCurve curve = (AbstractF2mCurve)p.Curve;
int m = curve.FieldSize;
int a = curve.A.ToBigInteger().IntValue;
sbyte mu = GetMu(a);
BigInteger[] s = curve.GetSi();
ZTauElement rho = PartModReduction(k, m, (sbyte)a, s, mu, (sbyte)10);
return MultiplyTnaf(p, rho);
}
/**
* Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
* by an element <code>λ</code> of <code><b>Z</b>[τ]</code>
* using the <code>τ</code>-adic NAF (TNAF) method.
* @param p The AbstractF2mPoint to Multiply.
* @param lambda The element <code>λ</code> of
* <code><b>Z</b>[τ]</code>.
* @return <code>λ * p</code>
*/
public static AbstractF2mPoint MultiplyTnaf(AbstractF2mPoint p, ZTauElement lambda)
{
AbstractF2mCurve curve = (AbstractF2mCurve)p.Curve;
sbyte mu = GetMu(curve.A);
sbyte[] u = TauAdicNaf(mu, lambda);
AbstractF2mPoint q = MultiplyFromTnaf(p, u);
return q;
}
/**
* Multiplies a {@link org.bouncycastle.math.ec.AbstractF2mPoint AbstractF2mPoint}
* by an element <code>λ</code> of <code><b>Z</b>[τ]</code>
* using the <code>τ</code>-adic NAF (TNAF) method, given the TNAF
* of <code>λ</code>.
* @param p The AbstractF2mPoint to Multiply.
* @param u The the TNAF of <code>λ</code>..
* @return <code>λ * p</code>
*/
public static AbstractF2mPoint MultiplyFromTnaf(AbstractF2mPoint p, sbyte[] u)
{
ECCurve curve = p.Curve;
AbstractF2mPoint q = (AbstractF2mPoint)curve.Infinity;
AbstractF2mPoint pNeg = (AbstractF2mPoint)p.Negate();
int tauCount = 0;
for (int i = u.Length - 1; i >= 0; i--)
{
++tauCount;
sbyte ui = u[i];
if (ui != 0)
{
q = q.TauPow(tauCount);
tauCount = 0;
ECPoint x = ui > 0 ? p : pNeg;
q = (AbstractF2mPoint)q.Add(x);
}
}
if (tauCount > 0)
{
q = q.TauPow(tauCount);
}
return q;
}
/**
* Computes the <code>[τ]</code>-adic window NAF of an element
* <code>λ</code> of <code><b>Z</b>[τ]</code>.
* @param mu The parameter μ of the elliptic curve.
* @param lambda The element <code>λ</code> of
* <code><b>Z</b>[τ]</code> of which to compute the
* <code>[τ]</code>-adic NAF.
* @param width The window width of the resulting WNAF.
* @param pow2w 2<sup>width</sup>.
* @param tw The auxiliary value <code>t<sub>w</sub></code>.
* @param alpha The <code>α<sub>u</sub></code>'s for the window width.
* @return The <code>[τ]</code>-adic window NAF of
* <code>λ</code>.
*/
public static sbyte[] TauAdicWNaf(sbyte mu, ZTauElement lambda,
sbyte width, BigInteger pow2w, BigInteger tw, ZTauElement[] alpha)
{
if (!((mu == 1) || (mu == -1)))
throw new ArgumentException("mu must be 1 or -1");
BigInteger norm = Norm(mu, lambda);
// Ceiling of log2 of the norm
int log2Norm = norm.BitLength;
// If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52
int maxLength = log2Norm > 30 ? log2Norm + 4 + width : 34 + width;
// The array holding the TNAF
sbyte[] u = new sbyte[maxLength];
// 2^(width - 1)
BigInteger pow2wMin1 = pow2w.ShiftRight(1);
// Split lambda into two BigIntegers to simplify calculations
BigInteger r0 = lambda.u;
BigInteger r1 = lambda.v;
int i = 0;
// while lambda <> (0, 0)
while (!((r0.Equals(BigInteger.Zero))&&(r1.Equals(BigInteger.Zero))))
{
// if r0 is odd
if (r0.TestBit(0))
{
// uUnMod = r0 + r1*tw Mod 2^width
BigInteger uUnMod
= r0.Add(r1.Multiply(tw)).Mod(pow2w);
sbyte uLocal;
// if uUnMod >= 2^(width - 1)
if (uUnMod.CompareTo(pow2wMin1) >= 0)
{
uLocal = (sbyte) uUnMod.Subtract(pow2w).IntValue;
}
else
{
uLocal = (sbyte) uUnMod.IntValue;
}
// uLocal is now in [-2^(width-1), 2^(width-1)-1]
u[i] = uLocal;
bool s = true;
if (uLocal < 0)
{
s = false;
uLocal = (sbyte)-uLocal;
}
// uLocal is now >= 0
if (s)
{
r0 = r0.Subtract(alpha[uLocal].u);
r1 = r1.Subtract(alpha[uLocal].v);
}
else
{
r0 = r0.Add(alpha[uLocal].u);
r1 = r1.Add(alpha[uLocal].v);
}
}
else
{
u[i] = 0;
}
BigInteger t = r0;
if (mu == 1)
{
r0 = r1.Add(r0.ShiftRight(1));
}
else
{
// mu == -1
r0 = r1.Subtract(r0.ShiftRight(1));
}
r1 = t.ShiftRight(1).Negate();
i++;
}
return u;
}
/**
* Does the precomputation for WTNAF multiplication.
* @param p The <code>ECPoint</code> for which to do the precomputation.
* @param a The parameter <code>a</code> of the elliptic curve.
* @return The precomputation array for <code>p</code>.
*/
public static AbstractF2mPoint[] GetPreComp(AbstractF2mPoint p, sbyte a)
{
sbyte[][] alphaTnaf = (a == 0) ? Tnaf.Alpha0Tnaf : Tnaf.Alpha1Tnaf;
AbstractF2mPoint[] pu = new AbstractF2mPoint[(uint)(alphaTnaf.Length + 1) >> 1];
pu[0] = p;
uint precompLen = (uint)alphaTnaf.Length;
for (uint i = 3; i < precompLen; i += 2)
{
pu[i >> 1] = Tnaf.MultiplyFromTnaf(p, alphaTnaf[i]);
}
p.Curve.NormalizeAll(pu);
return pu;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using OpenSim.Region.DataSnapshot.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace OpenSim.Region.DataSnapshot
{
public class SnapshotStore
{
#region Class Members
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_cacheEnabled = true;
private String m_directory = "unyuu"; //not an attempt at adding RM references to core SVN, honest
private Dictionary<String, String> m_gridinfo = null;
private string m_hostname = "127.0.0.1";
private string m_listener_port = "9000";
private List<IDataSnapshotProvider> m_providers = null;
private Dictionary<Scene, bool> m_scenes = null;
//TODO: Set default port over 9000
#endregion Class Members
public SnapshotStore(string directory, Dictionary<String, String> gridinfo, string port, string hostname)
{
m_directory = directory;
m_scenes = new Dictionary<Scene, bool>();
m_providers = new List<IDataSnapshotProvider>();
m_gridinfo = gridinfo;
m_listener_port = port;
m_hostname = hostname;
if (Directory.Exists(m_directory))
{
m_log.Info("[DATASNAPSHOT]: Response and fragment cache directory already exists.");
}
else
{
// Try to create the directory.
m_log.Info("[DATASNAPSHOT]: Creating directory " + m_directory);
try
{
Directory.CreateDirectory(m_directory);
}
catch (Exception e)
{
m_log.Error("[DATASNAPSHOT]: Failed to create directory " + m_directory, e);
//This isn't a horrible problem, just disable cacheing.
m_cacheEnabled = false;
m_log.Error("[DATASNAPSHOT]: Could not create directory, response cache has been disabled.");
}
}
}
public void ForceSceneStale(Scene scene)
{
m_scenes[scene] = true;
}
#region Fragment storage
public XmlNode GetFragment(IDataSnapshotProvider provider, XmlDocument factory)
{
XmlNode data = null;
if (provider.Stale || !m_cacheEnabled)
{
data = provider.RequestSnapshotData(factory);
if (m_cacheEnabled)
{
String path = DataFileNameFragment(provider.GetParentScene, provider.Name);
try
{
using (XmlTextWriter snapXWriter = new XmlTextWriter(path, Encoding.Default))
{
snapXWriter.Formatting = Formatting.Indented;
snapXWriter.WriteStartDocument();
data.WriteTo(snapXWriter);
snapXWriter.WriteEndDocument();
}
}
catch (Exception e)
{
m_log.WarnFormat("[DATASNAPSHOT]: Exception on writing to file {0}: {1}", path, e.Message);
}
}
//mark provider as not stale, parent scene as stale
provider.Stale = false;
m_scenes[provider.GetParentScene] = true;
m_log.Debug("[DATASNAPSHOT]: Generated fragment response for provider type " + provider.Name);
}
else
{
String path = DataFileNameFragment(provider.GetParentScene, provider.Name);
XmlDocument fragDocument = new XmlDocument();
fragDocument.PreserveWhitespace = true;
fragDocument.Load(path);
foreach (XmlNode node in fragDocument)
{
data = factory.ImportNode(node, true);
}
m_log.Debug("[DATASNAPSHOT]: Retrieved fragment response for provider type " + provider.Name);
}
return data;
}
#endregion Fragment storage
#region Response storage
public XmlNode GetScene(Scene scene, XmlDocument factory)
{
m_log.Debug("[DATASNAPSHOT]: Data requested for scene " + scene.RegionInfo.RegionName);
if (!m_scenes.ContainsKey(scene))
{
m_scenes.Add(scene, true); //stale by default
}
XmlNode regionElement = null;
if (!m_scenes[scene])
{
m_log.Debug("[DATASNAPSHOT]: Attempting to retrieve snapshot from cache.");
//get snapshot from cache
String path = DataFileNameScene(scene);
XmlDocument fragDocument = new XmlDocument();
fragDocument.PreserveWhitespace = true;
fragDocument.Load(path);
foreach (XmlNode node in fragDocument)
{
regionElement = factory.ImportNode(node, true);
}
m_log.Debug("[DATASNAPSHOT]: Obtained snapshot from cache for " + scene.RegionInfo.RegionName);
}
else
{
m_log.Debug("[DATASNAPSHOT]: Attempting to generate snapshot.");
//make snapshot
regionElement = MakeRegionNode(scene, factory);
regionElement.AppendChild(GetGridSnapshotData(factory));
XmlNode regionData = factory.CreateNode(XmlNodeType.Element, "data", "");
foreach (IDataSnapshotProvider dataprovider in m_providers)
{
if (dataprovider.GetParentScene == scene)
{
regionData.AppendChild(GetFragment(dataprovider, factory));
}
}
regionElement.AppendChild(regionData);
factory.AppendChild(regionElement);
//save snapshot
String path = DataFileNameScene(scene);
try
{
using (XmlTextWriter snapXWriter = new XmlTextWriter(path, Encoding.Default))
{
snapXWriter.Formatting = Formatting.Indented;
snapXWriter.WriteStartDocument();
regionElement.WriteTo(snapXWriter);
snapXWriter.WriteEndDocument();
}
}
catch (Exception e)
{
m_log.WarnFormat("[DATASNAPSHOT]: Exception on writing to file {0}: {1}", path, e.Message);
}
m_scenes[scene] = false;
m_log.Debug("[DATASNAPSHOT]: Generated new snapshot for " + scene.RegionInfo.RegionName);
}
return regionElement;
}
#endregion Response storage
#region Helpers
private static string Sanitize(string name)
{
string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
string invalidReStr = string.Format(@"[{0}]", invalidChars);
string newname = Regex.Replace(name, invalidReStr, "_");
return newname.Replace('.', '_');
}
private string DataFileNameFragment(Scene scene, String fragmentName)
{
return Path.Combine(m_directory, Path.ChangeExtension(Sanitize(scene.RegionInfo.RegionName + "_" + fragmentName), "xml"));
}
private string DataFileNameScene(Scene scene)
{
return Path.Combine(m_directory, Path.ChangeExtension(Sanitize(scene.RegionInfo.RegionName), "xml"));
//return (m_snapsDir + Path.DirectorySeparatorChar + scene.RegionInfo.RegionName + ".xml");
}
private XmlNode GetGridSnapshotData(XmlDocument factory)
{
XmlNode griddata = factory.CreateNode(XmlNodeType.Element, "grid", "");
foreach (KeyValuePair<String, String> GridData in m_gridinfo)
{
//TODO: make it lowercase tag names for diva
XmlNode childnode = factory.CreateNode(XmlNodeType.Element, GridData.Key, "");
childnode.InnerText = GridData.Value;
griddata.AppendChild(childnode);
}
m_log.Debug("[DATASNAPSHOT]: Got grid snapshot data");
return griddata;
}
private String GetRegionCategory(Scene scene)
{
if (scene.RegionInfo.RegionSettings.Maturity == 0)
return "PG";
if (scene.RegionInfo.RegionSettings.Maturity == 1)
return "Mature";
if (scene.RegionInfo.RegionSettings.Maturity == 2)
return "Adult";
return "Unknown";
}
private XmlNode MakeRegionNode(Scene scene, XmlDocument basedoc)
{
XmlNode docElement = basedoc.CreateNode(XmlNodeType.Element, "region", "");
XmlAttribute attr = basedoc.CreateAttribute("category");
attr.Value = GetRegionCategory(scene);
docElement.Attributes.Append(attr);
attr = basedoc.CreateAttribute("entities");
attr.Value = scene.Entities.Count.ToString();
docElement.Attributes.Append(attr);
//attr = basedoc.CreateAttribute("parcels");
//attr.Value = scene.LandManager.landList.Count.ToString();
//docElement.Attributes.Append(attr);
XmlNode infoblock = basedoc.CreateNode(XmlNodeType.Element, "info", "");
XmlNode infopiece = basedoc.CreateNode(XmlNodeType.Element, "uuid", "");
infopiece.InnerText = scene.RegionInfo.RegionID.ToString();
infoblock.AppendChild(infopiece);
infopiece = basedoc.CreateNode(XmlNodeType.Element, "url", "");
infopiece.InnerText = "http://" + m_hostname + ":" + m_listener_port;
infoblock.AppendChild(infopiece);
infopiece = basedoc.CreateNode(XmlNodeType.Element, "name", "");
infopiece.InnerText = scene.RegionInfo.RegionName;
infoblock.AppendChild(infopiece);
infopiece = basedoc.CreateNode(XmlNodeType.Element, "handle", "");
infopiece.InnerText = scene.RegionInfo.RegionHandle.ToString();
infoblock.AppendChild(infopiece);
docElement.AppendChild(infoblock);
m_log.Debug("[DATASNAPSHOT]: Generated region node");
return docElement;
}
#endregion Helpers
#region Manage internal collections
public void AddProvider(IDataSnapshotProvider newProvider)
{
m_providers.Add(newProvider);
}
public void AddScene(Scene newScene)
{
m_scenes.Add(newScene, true);
}
public void RemoveProvider(IDataSnapshotProvider deadProvider)
{
m_providers.Remove(deadProvider);
}
public void RemoveScene(Scene deadScene)
{
m_scenes.Remove(deadScene);
}
#endregion Manage internal collections
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
/*
Verify we can read the pre-2.1 file format, do searches
against it, and add documents to it.
*/
[TestFixture]
public class TestIndexFileDeleter : LuceneTestCase
{
[Test]
public virtual void TestDeleteLeftoverFiles()
{
Directory dir = NewDirectory();
if (dir is MockDirectoryWrapper)
{
((MockDirectoryWrapper)dir).PreventDoubleWrite = false;
}
MergePolicy mergePolicy = NewLogMergePolicy(true, 10);
// this test expects all of its segments to be in CFS
mergePolicy.NoCFSRatio = 1.0;
mergePolicy.MaxCFSSegmentSizeMB = double.PositiveInfinity;
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10).SetMergePolicy(mergePolicy).SetUseCompoundFile(true));
int i;
for (i = 0; i < 35; i++)
{
AddDoc(writer, i);
}
writer.Config.MergePolicy.NoCFSRatio = 0.0;
writer.Config.SetUseCompoundFile(false);
for (; i < 45; i++)
{
AddDoc(writer, i);
}
writer.Dispose();
// Delete one doc so we get a .del file:
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES).SetUseCompoundFile(true));
Term searchTerm = new Term("id", "7");
writer.DeleteDocuments(searchTerm);
writer.Dispose();
// Now, artificially create an extra .del file & extra
// .s0 file:
string[] files = dir.ListAll();
/*
for(int j=0;j<files.Length;j++) {
System.out.println(j + ": " + files[j]);
}
*/
// TODO: fix this test better
string ext = Codec.Default.Name.Equals("SimpleText") ? ".liv" : ".del";
// Create a bogus separate del file for a
// segment that already has a separate del file:
CopyFile(dir, "_0_1" + ext, "_0_2" + ext);
// Create a bogus separate del file for a
// segment that does not yet have a separate del file:
CopyFile(dir, "_0_1" + ext, "_1_1" + ext);
// Create a bogus separate del file for a
// non-existent segment:
CopyFile(dir, "_0_1" + ext, "_188_1" + ext);
// Create a bogus segment file:
CopyFile(dir, "_0.cfs", "_188.cfs");
// Create a bogus fnm file when the CFS already exists:
CopyFile(dir, "_0.cfs", "_0.fnm");
// Create some old segments file:
CopyFile(dir, "segments_2", "segments");
CopyFile(dir, "segments_2", "segments_1");
// Create a bogus cfs file shadowing a non-cfs segment:
// TODO: assert is bogus (relies upon codec-specific filenames)
Assert.IsTrue(SlowFileExists(dir, "_3.fdt") || SlowFileExists(dir, "_3.fld"));
Assert.IsTrue(!SlowFileExists(dir, "_3.cfs"));
CopyFile(dir, "_1.cfs", "_3.cfs");
string[] filesPre = dir.ListAll();
// Open & close a writer: it should delete the above 4
// files and nothing more:
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND));
writer.Dispose();
string[] files2 = dir.ListAll();
dir.Dispose();
Array.Sort(files);
Array.Sort(files2);
HashSet<string> dif = DifFiles(files, files2);
if (!Arrays.Equals(files, files2))
{
Assert.Fail("IndexFileDeleter failed to delete unreferenced extra files: should have deleted " + (filesPre.Length - files.Length) + " files but only deleted " + (filesPre.Length - files2.Length) + "; expected files:\n " + AsString(files) + "\n actual files:\n " + AsString(files2) + "\ndiff: " + dif);
}
}
private static HashSet<string> DifFiles(string[] files1, string[] files2)
{
HashSet<string> set1 = new HashSet<string>();
HashSet<string> set2 = new HashSet<string>();
HashSet<string> extra = new HashSet<string>();
for (int x = 0; x < files1.Length; x++)
{
set1.Add(files1[x]);
}
for (int x = 0; x < files2.Length; x++)
{
set2.Add(files2[x]);
}
IEnumerator<string> i1 = set1.GetEnumerator();
while (i1.MoveNext())
{
string o = i1.Current;
if (!set2.Contains(o))
{
extra.Add(o);
}
}
IEnumerator<string> i2 = set2.GetEnumerator();
while (i2.MoveNext())
{
string o = i2.Current;
if (!set1.Contains(o))
{
extra.Add(o);
}
}
return extra;
}
private string AsString(string[] l)
{
string s = "";
for (int i = 0; i < l.Length; i++)
{
if (i > 0)
{
s += "\n ";
}
s += l[i];
}
return s;
}
public virtual void CopyFile(Directory dir, string src, string dest)
{
IndexInput @in = dir.OpenInput(src, NewIOContext(Random()));
IndexOutput @out = dir.CreateOutput(dest, NewIOContext(Random()));
var b = new byte[1024];
long remainder = @in.Length();
while (remainder > 0)
{
int len = (int)Math.Min(b.Length, remainder);
@in.ReadBytes(b, 0, len);
@out.WriteBytes(b, len);
remainder -= len;
}
@in.Dispose();
@out.Dispose();
}
private void AddDoc(IndexWriter writer, int id)
{
Document doc = new Document();
doc.Add(NewTextField("content", "aaa", Field.Store.NO));
doc.Add(NewStringField("id", Convert.ToString(id), Field.Store.NO));
writer.AddDocument(doc);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
internal partial class SafeCloseSocket :
#if DEBUG
DebugSafeHandleMinusOneIsInvalid
#else
SafeHandleMinusOneIsInvalid
#endif
{
private ThreadPoolBoundHandle _iocpBoundHandle;
private bool _skipCompletionPortOnSuccess;
private object _iocpBindingLock = new object();
public void SetExposed() { /* nop */ }
public ThreadPoolBoundHandle IOCPBoundHandle
{
get
{
return _iocpBoundHandle;
}
}
// Binds the Socket Win32 Handle to the ThreadPool's CompletionPort.
public ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle(bool trySkipCompletionPortOnSuccess)
{
if (_released)
{
// Keep the exception message pointing at the external type.
throw new ObjectDisposedException(typeof(Socket).FullName);
}
// Check to see if the socket native _handle is already
// bound to the ThreadPool's completion port.
if (_iocpBoundHandle == null)
{
lock (_iocpBindingLock)
{
if (_iocpBoundHandle == null)
{
// Bind the socket native _handle to the ThreadPool.
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "calling ThreadPool.BindHandle()");
ThreadPoolBoundHandle boundHandle;
try
{
// The handle (this) may have been already released:
// E.g.: The socket has been disposed in the main thread. A completion callback may
// attempt starting another operation.
boundHandle = ThreadPoolBoundHandle.BindHandle(this);
}
catch (Exception exception)
{
if (ExceptionCheck.IsFatal(exception)) throw;
CloseAsIs();
throw;
}
// Try to disable completions for synchronous success, if requested
if (trySkipCompletionPortOnSuccess &&
CompletionPortHelper.SkipCompletionPortOnSuccess(boundHandle.Handle))
{
_skipCompletionPortOnSuccess = true;
}
// Don't set this until after we've configured the handle above (if we did)
_iocpBoundHandle = boundHandle;
}
}
}
return _iocpBoundHandle;
}
public bool SkipCompletionPortOnSuccess
{
get
{
Debug.Assert(_iocpBoundHandle != null);
return _skipCompletionPortOnSuccess;
}
}
internal static unsafe SafeCloseSocket CreateWSASocket(byte* pinnedBuffer)
{
return CreateSocket(InnerSafeCloseSocket.CreateWSASocket(pinnedBuffer));
}
internal static SafeCloseSocket CreateWSASocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
return CreateSocket(InnerSafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType));
}
internal static SafeCloseSocket Accept(
SafeCloseSocket socketHandle,
byte[] socketAddress,
ref int socketAddressSize)
{
return CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize));
}
private void InnerReleaseHandle()
{
// Keep m_IocpBoundHandle around after disposing it to allow freeing NativeOverlapped.
// ThreadPoolBoundHandle allows FreeNativeOverlapped even after it has been disposed.
if (_iocpBoundHandle != null)
{
_iocpBoundHandle.Dispose();
}
}
internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid
{
private SocketError InnerReleaseHandle()
{
SocketError errorCode;
// If _blockable was set in BlockingRelease, it's safe to block here, which means
// we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which
// case we need to do some recovery.
if (_blockable)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, Following 'blockable' branch");
errorCode = Interop.Winsock.closesocket(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = errorCode;
#endif
if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket()#1:{errorCode}");
// If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != SocketError.WouldBlock)
{
return errorCode;
}
// The socket must be non-blocking with a linger timeout set.
// We have to set the socket to blocking.
int nonBlockCmd = 0;
errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONBIO,
ref nonBlockCmd);
if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, ioctlsocket()#1:{errorCode}");
// If that succeeded, try again.
if (errorCode == SocketError.Success)
{
errorCode = Interop.Winsock.closesocket(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = errorCode;
#endif
if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket#2():{errorCode}");
// If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != SocketError.WouldBlock)
{
return errorCode;
}
}
// It failed. Fall through to the regular abortive close.
}
// By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST).
Interop.Winsock.Linger lingerStruct;
lingerStruct.OnOff = 1;
lingerStruct.Time = 0;
errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
ref lingerStruct,
4);
#if DEBUG
_closeSocketLinger = errorCode;
#endif
if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}");
if (errorCode != SocketError.Success && errorCode != SocketError.InvalidArgument && errorCode != SocketError.ProtocolOption)
{
// Too dangerous to try closesocket() - it might block!
return errorCode;
}
errorCode = Interop.Winsock.closesocket(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = errorCode;
#endif
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, closesocket#3():{(errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode)}");
return errorCode;
}
internal static unsafe InnerSafeCloseSocket CreateWSASocket(byte* pinnedBuffer)
{
// NOTE: -1 is the value for FROM_PROTOCOL_INFO.
InnerSafeCloseSocket result = Interop.Winsock.WSASocketW((AddressFamily)(-1), (SocketType)(-1), (ProtocolType)(-1), pinnedBuffer, 0, Interop.Winsock.SocketConstructorFlags.WSA_FLAG_OVERLAPPED);
if (result.IsInvalid)
{
result.SetHandleAsInvalid();
}
return result;
}
internal static InnerSafeCloseSocket CreateWSASocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
InnerSafeCloseSocket result = Interop.Winsock.WSASocketW(addressFamily, socketType, protocolType, IntPtr.Zero, 0, Interop.Winsock.SocketConstructorFlags.WSA_FLAG_OVERLAPPED);
if (result.IsInvalid)
{
result.SetHandleAsInvalid();
}
return result;
}
internal static InnerSafeCloseSocket Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize)
{
InnerSafeCloseSocket result = Interop.Winsock.accept(socketHandle.DangerousGetHandle(), socketAddress, ref socketAddressSize);
if (result.IsInvalid)
{
result.SetHandleAsInvalid();
}
return result;
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;
using System.Security.AccessControl;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The FileSystemProvider provides stateless namespace navigation
/// of the file system.
/// </summary>
///
public sealed partial class FileSystemProvider : NavigationCmdletProvider, IContentCmdletProvider, IPropertyCmdletProvider, ISecurityDescriptorCmdletProvider
{
#region ISecurityDescriptorCmdletProvider members
/// <summary>
/// Gets the SecurityDescriptor at the specified path, including only the specified
/// AccessControlSections.
/// </summary>
///
/// <param name="path">
/// The path of the item to retrieve. It may be a drive or provider-qualified path and may include.
/// glob characters.
/// </param>
///
/// <param name="sections">
/// The sections of the security descriptor to include.
/// </param>
///
/// <returns>
/// Nothing. An object that represents the security descriptor for the item
/// specified by path is written to the context's pipeline.
/// </returns>
///
/// <exception cref="System.ArgumentException">
/// path is null or empty.
/// path doesn't exist
/// sections is not valid.
/// </exception>
public void GetSecurityDescriptor(string path,
AccessControlSections sections)
{
ObjectSecurity sd = null;
path = NormalizePath(path);
if (String.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentNullException("path");
}
if ((sections & ~AccessControlSections.All) != 0)
{
throw PSTraceSource.NewArgumentException("sections");
}
var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE();
try
{
PlatformInvokes.EnableTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState);
if (Directory.Exists(path))
{
sd = new DirectorySecurity(path, sections);
}
else
{
sd = new FileSecurity(path, sections);
}
}
catch (System.Security.SecurityException e)
{
WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
}
finally
{
PlatformInvokes.RestoreTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState);
}
WriteSecurityDescriptorObject(sd, path);
}
/// <summary>
/// Sets the SecurityDescriptor at the specified path.
/// </summary>
///
/// <param name="path">
/// The path of the item to set the security descriptor on.
/// It may be a drive or provider-qualified path and may include.
/// glob characters.
/// </param>
///
/// <param name="securityDescriptor">
/// The new security descriptor for the item.
/// </param>
///
/// <exception cref="System.ArgumentException">
/// path is null or empty.
/// </exception>
///
/// <exception cref="System.ArgumentNullException">
/// securitydescriptor is null.
/// </exception>
public void SetSecurityDescriptor(
string path,
ObjectSecurity securityDescriptor)
{
if (String.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentException("path");
}
path = NormalizePath(path);
if (securityDescriptor == null)
{
throw PSTraceSource.NewArgumentNullException("securityDescriptor");
}
if (!File.Exists(path) && !Directory.Exists(path))
{
ThrowTerminatingError(CreateErrorRecord(path,
"SetSecurityDescriptor_FileNotFound"));
}
FileSystemSecurity sd = securityDescriptor as FileSystemSecurity;
if (sd == null)
{
throw PSTraceSource.NewArgumentException("securityDescriptor");
}
else
{
// This algorithm works around the following security descriptor complexities:
//
// - In order to copy an ACL between files, you need to use the
// binary form, and transfer all sections. If you don't use the binary form,
// then the FileSystem only applies changes that have happened to that specific
// ACL object -- which will not be present if you are just stamping a specific
// ACL on a lot of files.
// - Copying a full ACL means copying its Audit section, which normal users
// don't have access to.
//
// In order to make this cmdlet support regular users modifying their own files,
// the solution is to:
//
// - First attempt to copy the entire security descriptor as we did in V1.
// This ensures backward compatability for administrator scripts that currently
// work.
// - If the attempt fails due to a PrivilegeNotHeld exception, try again with
// an estimate of the minimum required subset. This is an estimate, since the
// ACL object doesn't tell you exactly what's changed.
// - If their ACL doesn't include any audit rules, don't try to set the
// audit section. If it does contain Audit rules, continue to try and
// set the section, so they get an appropriate error message.
// - If their ACL has the same Owner / Group as the destination file,
// also don't try to set those sections.
// If they added audit rules, or made changes to the Owner / Group, they will
// still get an error message.
//
// We can't roll the two steps into one, as the second step can't handle the
// situation where an admin wants to _clear_ the audit entries. It would be nice to
// detect a difference in audit entries (like we do with Owner and Group,) but
// retrieving the Audit entries requires SeSecurityPrivilege as well.
try
{
// Try to set the entire security descriptor
SetSecurityDescriptor(path, sd, AccessControlSections.All);
}
catch (PrivilegeNotHeldException)
{
// Get the security descriptor of the destination path
ObjectSecurity existingDescriptor = new FileInfo(path).GetAccessControl();
Type ntAccountType = typeof(System.Security.Principal.NTAccount);
AccessControlSections sections = AccessControlSections.All;
// If they didn't modify any audit information, don't try to set
// the audit section.
int auditRuleCount = sd.GetAuditRules(true, true, ntAccountType).Count;
if ((auditRuleCount == 0) &&
(sd.AreAuditRulesProtected == existingDescriptor.AreAccessRulesProtected))
{
sections &= ~AccessControlSections.Audit;
}
// If they didn't modify the owner, don't try to set that section.
if (sd.GetOwner(ntAccountType) == existingDescriptor.GetOwner(ntAccountType))
{
sections &= ~AccessControlSections.Owner;
}
// If they didn't modify the group, don't try to set that section.
if (sd.GetGroup(ntAccountType) == existingDescriptor.GetGroup(ntAccountType))
{
sections &= ~AccessControlSections.Group;
}
// Try to set the security descriptor again, this time with a reduced set
// of sections.
SetSecurityDescriptor(path, sd, sections);
}
}
} // SetSecurityDescriptor
private void SetSecurityDescriptor(string path, ObjectSecurity sd, AccessControlSections sections)
{
var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE();
byte[] securityDescriptorBinary = null;
try
{
// Get the binary form of the descriptor.
PlatformInvokes.EnableTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState);
securityDescriptorBinary = sd.GetSecurityDescriptorBinaryForm();
}
finally
{
PlatformInvokes.RestoreTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState);
}
try
{
PlatformInvokes.EnableTokenPrivilege("SeRestorePrivilege", ref currentPrivilegeState);
// Transfer it to the new file / directory.
// We keep these two code branches so that we can have more
// granular information when we ouput the object type via
// WriteSecurityDescriptorObject.
if (Directory.Exists(path))
{
DirectorySecurity newDescriptor = new DirectorySecurity();
newDescriptor.SetSecurityDescriptorBinaryForm(securityDescriptorBinary, sections);
new DirectoryInfo(path).SetAccessControl(newDescriptor);
WriteSecurityDescriptorObject(newDescriptor, path);
}
else
{
FileSecurity newDescriptor = new FileSecurity();
newDescriptor.SetSecurityDescriptorBinaryForm(securityDescriptorBinary, sections);
new FileInfo(path).SetAccessControl(newDescriptor);
WriteSecurityDescriptorObject(newDescriptor, path);
}
}
finally
{
PlatformInvokes.RestoreTokenPrivilege("SeRestorePrivilege", ref currentPrivilegeState);
}
}
/// <summary>
/// Creates a new empty security descriptor of the same type as
/// the item specified by the path. If "path" points to a file system directory,
/// then the descriptor returned will be of type DirectorySecurity.
/// </summary>
///
/// <param name="path">
/// Path of the item to use to determine the type of resulting
/// SecurityDescriptor.
/// </param>
///
/// <param name="sections">
/// The sections of the security descriptor to create.
/// </param>
///
/// <returns>
/// A new ObjectSecurity object of the same type as
/// the item specified by the path.
/// </returns>
public ObjectSecurity NewSecurityDescriptorFromPath(
string path,
AccessControlSections sections)
{
ItemType itemType = ItemType.Unknown;
if (IsItemContainer(path))
{
itemType = ItemType.Directory;
}
else
{
itemType = ItemType.File;
}
return NewSecurityDescriptor(itemType);
}
/// <summary>
/// Creates a new empty security descriptor of the specified type.
/// </summary>
///
/// <param name="type">
/// The type of Security Descriptor to create. Valid types are
/// "file", "directory," and "container."
/// </param>
///
/// <param name="sections">
/// The sections of the security descriptor to create.
/// </param>
///
/// <returns>
/// A new ObjectSecurity object of the specified type.
/// </returns>
///
public ObjectSecurity NewSecurityDescriptorOfType(
string type,
AccessControlSections sections)
{
ItemType itemType = ItemType.Unknown;
itemType = GetItemType(type);
return NewSecurityDescriptor(itemType);
}
private static ObjectSecurity NewSecurityDescriptor(
ItemType itemType)
{
ObjectSecurity sd = null;
switch (itemType)
{
case ItemType.File:
sd = new FileSecurity();
break;
case ItemType.Directory:
sd = new DirectorySecurity();
break;
}
return sd;
}
private static ErrorRecord CreateErrorRecord(string path,
string errorId)
{
string message = null;
message = StringUtil.Format(FileSystemProviderStrings.FileNotFound, path);
ErrorRecord er =
new ErrorRecord(new FileNotFoundException(message),
errorId,
ErrorCategory.ObjectNotFound,
null);
return er;
}
#endregion ISecurityDescriptorCmdletProvider members
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace DeOps.Implementation.Protocol
{
public enum G2ReadResult { PACKET_GOOD, PACKET_INCOMPLETE, PACKET_ERROR, STREAM_END };
/// <summary>
/// Summary description for G2Protocol.
/// </summary>
public class G2Protocol
{
const int MAX_FRAMES = 500;
const int MAX_WRITE_SIZE = 32768;
const int MAX_FINAL_SIZE = 65536;
const int G2_PACKET_BUFF = (65536+1024);
int WriteOffset;
byte[] WriteData = new byte[MAX_WRITE_SIZE];
LinkedList<G2Frame> Frames = new LinkedList<G2Frame>();
int FinalSize;
byte[] FinalPacket = new byte[MAX_FINAL_SIZE];
public object WriteSection = new object();
public G2Protocol()
{
}
public G2Frame WritePacket(G2Frame root, byte name, byte[] payload)
{
// If new packet
if(root == null)
{
if(WriteOffset != 0)
{
Frames.Clear();
WriteOffset = 0;
// caused by error building packet before
throw new Exception("Packet Frames not clear");//Debug.Assert(false); // Careful, can be caused by previous assert further down call stack
}
FinalSize = 0;
}
if(Frames.Count > MAX_FRAMES)
{
Debug.Assert(false);
return null;
}
// Create new frame
G2Frame packet = new G2Frame();
packet.Parent = root;
packet.Name = name;
if(payload != null)
{
if(WriteOffset + payload.Length > MAX_WRITE_SIZE)
{
Debug.Assert(false);
return null;
}
packet.PayloadLength = payload.Length;
packet.PayloadPos = WriteOffset;
payload.CopyTo(WriteData, WriteOffset);
WriteOffset += payload.Length;
}
Frames.AddLast(packet);
return packet;
}
public byte[] WriteFinish()
{
// Reverse iterate through packet structure backwards, set lengths
LinkedListNode<G2Frame> current = Frames.Last;
while(current != null)
{
G2Frame packet = current.Value;
if (packet.InternalLength > 0 && packet.PayloadLength > 0)
packet.InternalLength += 1; // For endstream byte
packet.PayloadOffset = packet.InternalLength;
packet.InternalLength += packet.PayloadLength;
packet.LenLen = 0;
while (packet.InternalLength >= Math.Pow(256, packet.LenLen))
packet.LenLen++;
Debug.Assert(packet.LenLen < 8);
packet.HeaderLength = 1 + packet.LenLen + 1;
if (packet.Parent != null)
{
packet.Parent.InternalLength += packet.HeaderLength + packet.InternalLength;
packet.Parent.Compound = 1;
}
current = current.Previous;
}
// Iterate through packet stucture forwards, build packet
foreach(G2Frame packet in Frames)
{
int nextByte = 0;
if( packet.Parent != null)
{
Debug.Assert(packet.Parent.NextChild != 0);
nextByte = packet.Parent.NextChild;
packet.Parent.NextChild += packet.HeaderLength + packet.InternalLength;
}
else // beginning of packet
{
FinalSize = packet.HeaderLength + packet.InternalLength;
}
byte control = 0;
control |= (byte) (packet.LenLen << 5);
control |= (byte) (1 << 3);
control |= (byte) (packet.Compound << 2);
Buffer.SetByte(FinalPacket, nextByte, control);
nextByte += 1;
// DNA should not pass packets greater than 4096, though pass through packets could be bigger
if(packet.HeaderLength + packet.InternalLength > MAX_WRITE_SIZE)
{
Debug.Assert(false);
Frames.Clear();
WriteOffset = 0;
FinalSize = 0;
return null;
}
byte [] lenData = BitConverter.GetBytes(packet.InternalLength);
Buffer.BlockCopy(lenData, 0, FinalPacket, nextByte, packet.LenLen);
nextByte += packet.LenLen;
FinalPacket[nextByte] = packet.Name;
nextByte += 1;
if(packet.Compound == 1)
packet.NextChild = nextByte;
if( packet.PayloadLength != 0)
{
int finalPos = nextByte + packet.PayloadOffset;
Buffer.BlockCopy(WriteData, packet.PayloadPos, FinalPacket, finalPos, packet.PayloadLength);
if(packet.Compound == 1) // Set stream end
{
finalPos -= 1;
Buffer.SetByte(FinalPacket, finalPos, 0);
}
}
}
Debug.Assert(FinalSize != 0);
Frames.Clear();
WriteOffset = 0;
return Utilities.ExtractBytes(FinalPacket, 0, FinalSize);
}
public static G2ReadResult ReadNextPacket( G2Header packet, ref int readPos, ref int readSize )
{
if( readSize == 0 )
return G2ReadResult.PACKET_INCOMPLETE;
int beginPos = readPos;
int beginSize = readSize;
packet.PacketPos = readPos;
// Read Control Byte
byte control = Buffer.GetByte(packet.Data, readPos);
readPos += 1;
readSize -= 1;
if ( control == 0 )
return G2ReadResult.STREAM_END;
byte lenLen = (byte) ( (control & 0xE0) >> 5); // 11100000
byte nameLen = (byte) ( (control & 0x18) >> 3); // 00011000
byte flags = (byte) (control & 0x07); // 00000111
bool bigEndian = (flags & 0x02) != 0;
bool isCompound = (flags & 0x04) != 0;
if( bigEndian )
return G2ReadResult.PACKET_ERROR;
packet.HasChildren = isCompound;
// Read Packet Length
packet.InternalSize = 0;
if( lenLen != 0)
{
if(readSize < lenLen)
{
readPos = beginPos;
readSize = beginSize;
return G2ReadResult.PACKET_INCOMPLETE;
}
byte[] lenData = new byte[8]; // create here because lenLen is less than 8 in size
Buffer.BlockCopy(packet.Data, readPos, lenData, 0, lenLen);
packet.InternalSize = BitConverter.ToInt32(lenData, 0); // only 4 bytes supported so far
Debug.Assert(MAX_FINAL_SIZE < G2_PACKET_BUFF);
if (packet.InternalSize < 0 || MAX_FINAL_SIZE < packet.InternalSize)
{
Debug.Assert(false);
return G2ReadResult.PACKET_ERROR;
}
readPos += lenLen;
readSize -= lenLen;
}
// Read Packet Name
if(readSize < nameLen)
{
readPos = beginPos;
readSize = beginSize;
return G2ReadResult.PACKET_INCOMPLETE;
}
if(nameLen != 1)
return G2ReadResult.PACKET_ERROR;
/*if(packet.Name.Length + 1 + nameLen > MAX_NAME_SIZE - 1)
{
Debug.Assert(false);
packet.Name = "ERROR";
}
else
{
packet.Name += "/" + StringEnc.GetString(packet.Data, readPos, nameLen);
}*/
packet.Name = packet.Data[readPos];
readPos += nameLen;
readSize -= nameLen;
// Check if full packet length available in stream
if(readSize < packet.InternalSize)
{
readPos = beginPos;
readSize = beginSize;
return G2ReadResult.PACKET_INCOMPLETE;
}
packet.InternalPos = (packet.InternalSize > 0) ? readPos : 0;
packet.NextBytePos = packet.InternalPos;
packet.NextBytesLeft = packet.InternalSize;
readPos += packet.InternalSize;
readSize -= packet.InternalSize;
packet.PacketSize = 1 + lenLen + nameLen + packet.InternalSize;
return G2ReadResult.PACKET_GOOD;
}
public static bool ReadPayload(G2Header packet)
{
ResetPacket(packet);
G2Header child = new G2Header(packet.Data);
G2ReadResult streamStatus = G2ReadResult.PACKET_GOOD;
while( streamStatus == G2ReadResult.PACKET_GOOD )
streamStatus = ReadNextChild(packet, child);
if(streamStatus == G2ReadResult.STREAM_END)
{
if( packet.NextBytesLeft > 0)
{
packet.PayloadPos = packet.NextBytePos;
packet.PayloadSize = packet.NextBytesLeft;
return true;
}
}
else if( packet.NextBytesLeft > 0)
{
// Payload Read Error
//m_pG2Comm->m_pCore->DebugLog("G2 Network", "Payload Read Error: " + HexDump(packet.Packet, packet.PacketSize));
}
return false;
}
public static void ResetPacket(G2Header packet)
{
packet.NextBytePos = packet.InternalPos;
packet.NextBytesLeft = packet.InternalSize;
packet.PayloadPos = 0;
packet.PayloadSize = 0;
}
public static G2ReadResult ReadNextChild( G2Header root, G2Header child)
{
if( !root.HasChildren )
return G2ReadResult.STREAM_END;
return ReadNextPacket(child, ref root.NextBytePos, ref root.NextBytesLeft);
}
public static bool ReadPacket(G2Header root)
{
int start = 0;
int length = root.Data.Length;
if (G2ReadResult.PACKET_GOOD == ReadNextPacket(root, ref start, ref length))
return true;
return false;
}
public int WriteToFile(G2Packet packet, Stream stream)
{
byte[] data = packet.Encode(this);
stream.Write(data, 0, data.Length);
return data.Length;
}
}
/// <summary>
/// Summary description for G2Frame.
/// </summary>
public class G2Frame
{
public G2Frame Parent;
public int HeaderLength;
public int InternalLength;
public byte Name;
public byte LenLen;
public byte Compound;
public int NextChild;
public int PayloadPos;
public int PayloadLength;
public int PayloadOffset;
public G2Frame()
{
}
}
public class G2Header
{
public byte[] Data;
public int PacketPos;
public int PacketSize;
public byte Name;
public bool HasChildren;
public int InternalPos;
public int InternalSize;
public int PayloadPos;
public int PayloadSize;
public int NextBytePos;
public int NextBytesLeft;
public G2Header(byte[] data)
{
Data = data;
}
}
public class G2Packet
{
public G2Packet()
{
}
public virtual byte[] Encode(G2Protocol protocol)
{
return null;
}
}
public class PacketStream
{
G2Protocol Protocol;
Stream ParentStream;
FileAccess Access;
byte[] ReadBuffer;
int ReadSize;
int Start;
int Pos;
public int ParentPos;
G2ReadResult ReadStatus = G2ReadResult.PACKET_INCOMPLETE;
public PacketStream(Stream stream, G2Protocol protocol, FileAccess access)
{
ParentStream = stream;
Protocol = protocol;
Access = access;
if(access == FileAccess.Read)
ReadBuffer = new byte[4096]; // break/resume relies on 4kb buffer
}
public bool ReadPacket(ref G2Header root)
{
root = new G2Header(ReadBuffer);
// continue from left off, read another goo packete
if (ReadNext(root))
return true;
if (ReadStatus != G2ReadResult.PACKET_INCOMPLETE)
return false;
// re-align
if (ReadSize > 0)
Buffer.BlockCopy(ReadBuffer, Start, ReadBuffer, 0, ReadSize);
// incomplete, or just started, read some more from file
Start = 0;
int read = ParentStream.Read(ReadBuffer, ReadSize, ReadBuffer.Length - ReadSize);
Pos += read;
ReadSize += read;
if (ReadNext(root))
return true;
return false;
}
private bool ReadNext(G2Header root)
{
if (ReadSize > 0)
{
int prevStart = Start;
ReadStatus = G2Protocol.ReadNextPacket(root, ref Start, ref ReadSize);
ParentPos += (Start - prevStart);
if (ReadStatus == G2ReadResult.PACKET_GOOD)
return true;
}
// hit the exact end of the buffer read in, signal to read the next buffer in
else
ReadStatus = G2ReadResult.PACKET_INCOMPLETE;
return false;
}
public int WritePacket(G2Packet packet)
{
byte[] data = packet.Encode(Protocol);
ParentStream.Write(data, 0, data.Length);
return data.Length;
}
public byte[] Break()
{
byte[] remaining = Utilities.ExtractBytes(ReadBuffer, Start, ReadSize);
ReadSize = 0;
ReadStatus = G2ReadResult.PACKET_INCOMPLETE;
return remaining;
}
public void Resume(byte[] data, int size)
{
Start = 0;
ReadSize = size;
data.CopyTo(ReadBuffer, 0);
ReadStatus = G2ReadResult.PACKET_INCOMPLETE;
}
}
public static class CompactNum
{
// unsigned to bytes
public static byte[] GetBytes(byte num)
{
return new byte[] { num };
}
public static byte[] GetBytes(ushort num)
{
if (byte.MinValue <= num && num <= byte.MaxValue)
return GetBytes((byte)num);
else
return BitConverter.GetBytes(num);
}
public static byte[] GetBytes(uint num)
{
if (ushort.MinValue <= num && num <= ushort.MaxValue)
return GetBytes((ushort)num);
else
return BitConverter.GetBytes(num);
}
public static byte[] GetBytes(ulong num)
{
if (uint.MinValue <= num && num <= uint.MaxValue)
return GetBytes((uint)num);
else
return BitConverter.GetBytes(num);
}
// signed to bytes
public static byte[] GetBytes(sbyte num)
{
return new byte[] { (byte) num };
}
public static byte[] GetBytes(short num)
{
if (sbyte.MinValue <= num && num <= sbyte.MaxValue)
return GetBytes((sbyte)num);
else
return BitConverter.GetBytes(num);
}
public static byte[] GetBytes(int num)
{
if (short.MinValue <= num && num <= short.MaxValue)
return GetBytes((short)num);
else
return BitConverter.GetBytes(num);
}
public static byte[] GetBytes(long num)
{
if (int.MinValue <= num && num <= int.MaxValue)
return GetBytes((int)num);
else
return BitConverter.GetBytes(num);
}
// unsigned from bytes
public static byte ToUInt8(byte[] data, int pos, int size)
{
return data[pos];
}
public static ushort ToUInt16(byte[] data, int pos, int size)
{
if (size == 1)
return ToUInt8(data, pos, size);
else
return BitConverter.ToUInt16(data, pos);
}
public static uint ToUInt32(byte[] data, int pos, int size)
{
if (size <= 2)
return ToUInt16(data, pos, size);
else
return BitConverter.ToUInt32(data, pos);
}
public static ulong ToUInt64(byte[] data, int pos, int size)
{
if (size <= 4)
return ToUInt32(data, pos, size);
else
return BitConverter.ToUInt64(data, pos);
}
// signed from bytes
public static sbyte ToInt8(byte[] data, int pos, int size)
{
return (sbyte) data[pos];
}
public static short ToInt16(byte[] data, int pos, int size)
{
if (size == 1)
return ToInt8(data, pos, size);
else
return BitConverter.ToInt16(data, pos);
}
public static int ToInt32(byte[] data, int pos, int size)
{
if (size <= 2)
return ToInt16(data, pos, size);
else
return BitConverter.ToInt32(data, pos);
}
public static long ToInt64(byte[] data, int pos, int size)
{
if (size <= 4)
return ToInt32(data, pos, size);
else
return BitConverter.ToInt64(data, pos);
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Container for the parameters to the CreateLaunchConfiguration operation.
/// Creates a launch configuration.
///
///
/// <para>
/// If you exceed your maximum limit of launch configurations, which by default is 100
/// per region, the call fails. For information about viewing and updating these limits,
/// see <a>DescribeAccountLimits</a>.
/// </para>
/// </summary>
public partial class CreateLaunchConfigurationRequest : AmazonAutoScalingRequest
{
private bool? _associatePublicIpAddress;
private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>();
private string _classicLinkVPCId;
private List<string> _classicLinkVPCSecurityGroups = new List<string>();
private bool? _ebsOptimized;
private string _iamInstanceProfile;
private string _imageId;
private string _instanceId;
private InstanceMonitoring _instanceMonitoring;
private string _instanceType;
private string _kernelId;
private string _keyName;
private string _launchConfigurationName;
private string _placementTenancy;
private string _ramdiskId;
private List<string> _securityGroups = new List<string>();
private string _spotPrice;
private string _userData;
/// <summary>
/// Gets and sets the property AssociatePublicIpAddress.
/// <para>
/// Used for groups that launch instances into a virtual private cloud (VPC). Specifies
/// whether to assign a public IP address to each instance. For more information, see
/// <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html">Auto
/// Scaling and Amazon VPC</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// <note>
/// <para>
/// If you specify a value for this parameter, be sure to specify at least one subnet
/// using the <i>VPCZoneIdentifier</i> parameter when you create your group.
/// </para>
/// </note>
/// <para>
/// Default: If the instance is launched into a default subnet, the default is <code>true</code>.
/// If the instance is launched into a nondefault subnet, the default is <code>false</code>.
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide//as-supported-platforms.html">Supported
/// Platforms</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public bool AssociatePublicIpAddress
{
get { return this._associatePublicIpAddress.GetValueOrDefault(); }
set { this._associatePublicIpAddress = value; }
}
// Check to see if AssociatePublicIpAddress property is set
internal bool IsSetAssociatePublicIpAddress()
{
return this._associatePublicIpAddress.HasValue;
}
/// <summary>
/// Gets and sets the property BlockDeviceMappings.
/// <para>
/// One or more mappings that specify how block devices are exposed to the instance. For
/// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block
/// Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public List<BlockDeviceMapping> BlockDeviceMappings
{
get { return this._blockDeviceMappings; }
set { this._blockDeviceMappings = value; }
}
// Check to see if BlockDeviceMappings property is set
internal bool IsSetBlockDeviceMappings()
{
return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property ClassicLinkVPCId.
/// <para>
/// The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. This parameter
/// can only be used if you are launching EC2-Classic instances. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a>
/// in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public string ClassicLinkVPCId
{
get { return this._classicLinkVPCId; }
set { this._classicLinkVPCId = value; }
}
// Check to see if ClassicLinkVPCId property is set
internal bool IsSetClassicLinkVPCId()
{
return this._classicLinkVPCId != null;
}
/// <summary>
/// Gets and sets the property ClassicLinkVPCSecurityGroups.
/// <para>
/// The IDs of one or more security groups for the VPC specified in <code>ClassicLinkVPCId</code>.
/// This parameter is required if <code>ClassicLinkVPCId</code> is specified, and cannot
/// be used otherwise. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a>
/// in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public List<string> ClassicLinkVPCSecurityGroups
{
get { return this._classicLinkVPCSecurityGroups; }
set { this._classicLinkVPCSecurityGroups = value; }
}
// Check to see if ClassicLinkVPCSecurityGroups property is set
internal bool IsSetClassicLinkVPCSecurityGroups()
{
return this._classicLinkVPCSecurityGroups != null && this._classicLinkVPCSecurityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property EbsOptimized.
/// <para>
/// Indicates whether the instance is optimized for Amazon EBS I/O. By default, the instance
/// is not optimized for EBS I/O. The optimization provides dedicated throughput to Amazon
/// EBS and an optimized configuration stack to provide optimal I/O performance. This
/// optimization is not available with all instance types. Additional usage charges apply.
/// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html">Amazon
/// EBS-Optimized Instances</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public bool EbsOptimized
{
get { return this._ebsOptimized.GetValueOrDefault(); }
set { this._ebsOptimized = value; }
}
// Check to see if EbsOptimized property is set
internal bool IsSetEbsOptimized()
{
return this._ebsOptimized.HasValue;
}
/// <summary>
/// Gets and sets the property IamInstanceProfile.
/// <para>
/// The name or the Amazon Resource Name (ARN) of the instance profile associated with
/// the IAM role for the instance.
/// </para>
///
/// <para>
/// Amazon EC2 instances launched with an IAM role will automatically have AWS security
/// credentials available. You can use IAM roles with Auto Scaling to automatically enable
/// applications running on your Amazon EC2 instances to securely access other AWS resources.
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/us-iam-role.html">Launch
/// Auto Scaling Instances with an IAM Role</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public string IamInstanceProfile
{
get { return this._iamInstanceProfile; }
set { this._iamInstanceProfile = value; }
}
// Check to see if IamInstanceProfile property is set
internal bool IsSetIamInstanceProfile()
{
return this._iamInstanceProfile != null;
}
/// <summary>
/// Gets and sets the property ImageId.
/// <para>
/// The ID of the Amazon Machine Image (AMI) to use to launch your EC2 instances. For
/// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding
/// an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public string ImageId
{
get { return this._imageId; }
set { this._imageId = value; }
}
// Check to see if ImageId property is set
internal bool IsSetImageId()
{
return this._imageId != null;
}
/// <summary>
/// Gets and sets the property InstanceId.
/// <para>
/// The ID of the EC2 instance to use to create the launch configuration.
/// </para>
///
/// <para>
/// The new launch configuration derives attributes from the instance, with the exception
/// of the block device mapping.
/// </para>
///
/// <para>
/// To create a launch configuration with a block device mapping or override any other
/// instance attributes, specify them as part of the same request.
/// </para>
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/create-lc-with-instanceID.html">Create
/// a Launch Configuration Using an EC2 Instance</a> in the <i>Auto Scaling Developer
/// Guide</i>.
/// </para>
/// </summary>
public string InstanceId
{
get { return this._instanceId; }
set { this._instanceId = value; }
}
// Check to see if InstanceId property is set
internal bool IsSetInstanceId()
{
return this._instanceId != null;
}
/// <summary>
/// Gets and sets the property InstanceMonitoring.
/// <para>
/// Enables detailed monitoring if it is disabled. Detailed monitoring is enabled by default.
/// </para>
///
/// <para>
/// When detailed monitoring is enabled, Amazon Cloudwatch generates metrics every minute
/// and your account is charged a fee. When you disable detailed monitoring, by specifying
/// <code>False</code>, Cloudwatch generates metrics every 5 minutes. For more information,
/// see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/as-instance-monitoring.html">Monitor
/// Your Auto Scaling Instances</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public InstanceMonitoring InstanceMonitoring
{
get { return this._instanceMonitoring; }
set { this._instanceMonitoring = value; }
}
// Check to see if InstanceMonitoring property is set
internal bool IsSetInstanceMonitoring()
{
return this._instanceMonitoring != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type of the Amazon EC2 instance. For information about available Amazon
/// EC2 instance types, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes">
/// Available Instance Types</a> in the <i>Amazon Elastic Cloud Compute User Guide.</i>
///
/// </para>
/// </summary>
public string InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property KernelId.
/// <para>
/// The ID of the kernel associated with the Amazon EC2 AMI.
/// </para>
/// </summary>
public string KernelId
{
get { return this._kernelId; }
set { this._kernelId = value; }
}
// Check to see if KernelId property is set
internal bool IsSetKernelId()
{
return this._kernelId != null;
}
/// <summary>
/// Gets and sets the property KeyName.
/// <para>
/// The name of the key pair. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon
/// EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public string KeyName
{
get { return this._keyName; }
set { this._keyName = value; }
}
// Check to see if KeyName property is set
internal bool IsSetKeyName()
{
return this._keyName != null;
}
/// <summary>
/// Gets and sets the property LaunchConfigurationName.
/// <para>
/// The name of the launch configuration. This name must be unique within the scope of
/// your AWS account.
/// </para>
/// </summary>
public string LaunchConfigurationName
{
get { return this._launchConfigurationName; }
set { this._launchConfigurationName = value; }
}
// Check to see if LaunchConfigurationName property is set
internal bool IsSetLaunchConfigurationName()
{
return this._launchConfigurationName != null;
}
/// <summary>
/// Gets and sets the property PlacementTenancy.
/// <para>
/// The tenancy of the instance. An instance with a tenancy of <code>dedicated</code>
/// runs on single-tenant hardware and can only be launched in a VPC.
/// </para>
///
/// <para>
/// You must set the value of this parameter to <code>dedicated</code> if want to launch
/// Dedicated Instances in a shared tenancy VPC (VPC with instance placement tenancy attribute
/// set to <code>default</code>).
/// </para>
///
/// <para>
/// If you specify a value for this parameter, be sure to specify at least one VPC subnet
/// using the <i>VPCZoneIdentifier</i> parameter when you create your group.
/// </para>
///
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html">Auto
/// Scaling and Amazon VPC</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
///
/// <para>
/// Valid values: <code>default</code> | <code>dedicated</code>
/// </para>
/// </summary>
public string PlacementTenancy
{
get { return this._placementTenancy; }
set { this._placementTenancy = value; }
}
// Check to see if PlacementTenancy property is set
internal bool IsSetPlacementTenancy()
{
return this._placementTenancy != null;
}
/// <summary>
/// Gets and sets the property RamdiskId.
/// <para>
/// The ID of the RAM disk associated with the Amazon EC2 AMI.
/// </para>
/// </summary>
public string RamdiskId
{
get { return this._ramdiskId; }
set { this._ramdiskId = value; }
}
// Check to see if RamdiskId property is set
internal bool IsSetRamdiskId()
{
return this._ramdiskId != null;
}
/// <summary>
/// Gets and sets the property SecurityGroups.
/// <para>
/// One or more security groups with which to associate the instances.
/// </para>
///
/// <para>
/// If your instances are launched in EC2-Classic, you can either specify security group
/// names or the security group IDs. For more information about security groups for EC2-Classic,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon
/// EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// If your instances are launched in a VPC, specify security group IDs. For more information,
/// see <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security
/// Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User Guide</i>.
/// </para>
/// </summary>
public List<string> SecurityGroups
{
get { return this._securityGroups; }
set { this._securityGroups = value; }
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this._securityGroups != null && this._securityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property SpotPrice.
/// <para>
/// The maximum hourly price to be paid for any Spot Instance launched to fulfill the
/// request. Spot Instances are launched when the price you specify exceeds the current
/// Spot market price. For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/US-SpotInstances.html">Launch
/// Spot Instances in Your Auto Scaling Group</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
/// </summary>
public string SpotPrice
{
get { return this._spotPrice; }
set { this._spotPrice = value; }
}
// Check to see if SpotPrice property is set
internal bool IsSetSpotPrice()
{
return this._spotPrice != null;
}
/// <summary>
/// Gets and sets the property UserData.
/// <para>
/// The user data to make available to the launched EC2 instances. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance
/// Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// <note>At this time, launch configurations don't support compressed (zipped) user
/// data files.</note>
/// </summary>
public string UserData
{
get { return this._userData; }
set { this._userData = value; }
}
// Check to see if UserData property is set
internal bool IsSetUserData()
{
return this._userData != null;
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// CESchedulerPairTests.cs
// Tests Ported from the TPL test bed
//
// Summary:
// Implements the tests for the new scheduler ConcurrentExclusiveSchedulerPair
//
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Security;
using Xunit;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public class TrackingTaskScheduler : TaskScheduler
{
public TrackingTaskScheduler(int maxConLevel)
{
//We need to set the value to 1 so that each time a scheduler is created, its tasks will start with one.
_counter = 1;
if (maxConLevel < 1 && maxConLevel != -1/*infinite*/)
throw new ArgumentException("Maximum concurrency level should between 1 and int32.Maxvalue");
_maxConcurrencyLevel = maxConLevel;
}
[SecurityCritical]
protected override void QueueTask(Task task)
{
if (task == null) throw new ArgumentNullException("When reqeusting to QueueTask, the input task can not be null");
Task.Factory.StartNew(() =>
{
lock (_lockObj) //Locking so that if mutliple threads in threadpool does not incorrectly increment the counter.
{
//store the current value of the counter (This becomes the unique ID for this scheduler's Task)
SchedulerID.Value = _counter;
_counter++;
}
ExecuteTask(task); //Extracted out due to security attribute reason.
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
[SecuritySafeCritical] //This has to be SecuritySafeCritical since its accesses TaskScheduler.TryExecuteTask (which is safecritical)
private void ExecuteTask(Task task)
{
base.TryExecuteTask(task);
}
[SecurityCritical]
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (taskWasPreviouslyQueued) return false;
return TryExecuteTask(task);
}
//public int SchedulerID
//{
// get;
// set;
//}
[SecurityCritical]
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
private Object _lockObj = new Object();
private int _counter = 1; //This is used ot keep track of how many scheduler tasks were created
public ThreadLocal<int> SchedulerID = new ThreadLocal<int>(); //This is the ID of the scheduler.
/// <summary>The maximum concurrency level for the scheduler.</summary>
private readonly int _maxConcurrencyLevel;
public override int MaximumConcurrencyLevel { get { return _maxConcurrencyLevel; } }
}
public class CESchedulerPairTests
{
#region Test cases
/// <summary>
/// Test to ensure that ConcurrentExclusiveSchedulerPair can be created using user defined parameters
/// and those parameters are respected when tasks are executed
/// </summary>
/// <remarks>maxItemsPerTask and which scheduler is used are verified in other testcases</remarks>
[Theory]
[InlineData("default")]
[InlineData("scheduler")]
[InlineData("maxconcurrent")]
[InlineData("all")]
public static void TestCreationOptions(String ctorType)
{
ConcurrentExclusiveSchedulerPair schedPair = null;
//Need to define the default values since these values are passed to the verification methods
TaskScheduler scheduler = TaskScheduler.Default;
int maxConcurrentLevel = Environment.ProcessorCount;
//Based on input args, use one of the ctor overloads
switch (ctorType.ToLower())
{
case "default":
schedPair = new ConcurrentExclusiveSchedulerPair();
break;
case "scheduler":
schedPair = new ConcurrentExclusiveSchedulerPair(scheduler);
break;
case "maxconcurrent":
maxConcurrentLevel = 2;
schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrentLevel);
break;
case "all":
maxConcurrentLevel = Int32.MaxValue;
schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, -1/*MaxConcurrentLevel*/, -1/*MaxItemsPerTask*/); //-1 gets converted to Int32.MaxValue
break;
default:
throw new NotImplementedException(String.Format("The option specified {0} to create the ConcurrentExclusiveSchedulerPair is invalid", ctorType));
}
//Create the factories that use the exclusive scheduler and the concurrent scheduler. We test to ensure
//that the ConcurrentExclusiveSchedulerPair created are valid by scheduling work on them.
TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler);
TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler);
List<Task> taskList = new List<Task>(); //Store all tasks created, to enable wait until all of them are finished
// Schedule some dummy work that should be run with as much parallelism as possible
for (int i = 0; i < 50; i++)
{
//In the current design, when there are no more tasks to execute, the Task used by concurrentexclusive scheduler dies
//by sleeping we simulate some non trival work that takes time and causes the concurrentexclusive scheduler Task
//to stay around for addition work.
taskList.Add(readers.StartNew(() => { new ManualResetEvent(false).WaitOne(10); }));
}
// Schedule work where each item must be run when no other items are running
for (int i = 0; i < 10; i++) taskList.Add(writers.StartNew(() => { new ManualResetEvent(false).WaitOne(5); }));
//Wait on the tasks to finish to ensure that the ConcurrentExclusiveSchedulerPair created can schedule and execute tasks without issues
foreach (var item in taskList)
{
item.Wait();
}
//verify that maxconcurrency was respected.
if (ctorType == "maxconcurrent")
{
Assert.Equal(maxConcurrentLevel, schedPair.ConcurrentScheduler.MaximumConcurrencyLevel);
}
Assert.Equal(1, schedPair.ExclusiveScheduler.MaximumConcurrencyLevel);
//verify that the schedulers have not completed
Assert.False(schedPair.Completion.IsCompleted, "The schedulers should not have completed as a completion request was not issued.");
//complete the scheduler and make sure it shuts down successfully
schedPair.Complete();
schedPair.Completion.Wait();
//make sure no additional work may be scheduled
foreach (var schedPairScheduler in new TaskScheduler[] { schedPair.ConcurrentScheduler, schedPair.ExclusiveScheduler })
{
Exception caughtException = null;
try
{
Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.None, schedPairScheduler);
}
catch (Exception exc)
{
caughtException = exc;
}
Assert.True(
caughtException is TaskSchedulerException && caughtException.InnerException is InvalidOperationException,
"Queueing after completion should fail");
}
}
/// <summary>
/// Test to verify that only upto maxItemsPerTask are executed by a single ConcurrentExclusiveScheduler Task
/// </summary>
/// <remarks>In ConcurrentExclusiveSchedulerPair, each tasks scheduled are run under an internal Task. The basic idea for the test
/// is that each time ConcurrentExclusiveScheduler is called QueueTasK a counter (which acts as scheduler's Task id) is incremented.
/// When a task executes, it observes the parent Task Id and if it matches the one its local cache, it increments its local counter (which tracks
/// the items executed by a ConcurrentExclusiveScheduler Task). At any given time the Task's local counter cant exceed maxItemsPerTask</remarks>
[Theory]
[InlineData(4, 1, true)]
[InlineData(1, 4, true)]
[InlineData(4, 1, false)]
[InlineData(1, 4, false)]
public static void TestMaxItemsPerTask(int maxConcurrency, int maxItemsPerTask, bool completeBeforeTaskWait)
{
//Create a custom TaskScheduler with specified max concurrency (TrackingTaskScheduler is defined in Common\tools\CommonUtils\TPLTestSchedulers.cs)
TrackingTaskScheduler scheduler = new TrackingTaskScheduler(maxConcurrency);
//We need to use the custom scheduler to achieve the results. As a by-product, we test to ensure custom schedulers are supported
ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrency, maxItemsPerTask);
TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); //get reader and writer schedulers
TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler);
//These are threadlocals to ensure that no concurrency side effects occur
ThreadLocal<int> itemsExecutedCount = new ThreadLocal<int>(); //Track the items executed by CEScheduler Task
ThreadLocal<int> schedulerIDInsideTask = new ThreadLocal<int>(); //Used to store the Scheduler ID observed by a Task Executed by CEScheduler Task
//Work done by both reader and writer tasks
Action work = () =>
{
//Get the id of the parent Task (which is the task created by the scheduler). Each task run by the scheduler task should
//see the same SchedulerID value since they are run on the same thread
int id = ((TrackingTaskScheduler)scheduler).SchedulerID.Value;
if (id == schedulerIDInsideTask.Value)
{ //since ids match, this is one more Task being executed by the CEScheduler Task
itemsExecutedCount.Value = ++itemsExecutedCount.Value;
//This does not need to be thread safe since we are looking to ensure that only n number of tasks were executed and not the order
//in which they were executed. Also asserting inside the thread is fine since we just want the test to be marked as failure
Assert.True(itemsExecutedCount.Value <= maxItemsPerTask, string.Format("itemsExecutedCount={0} cant be greater than maxValue={1}. Parent TaskID={2}",
itemsExecutedCount, maxItemsPerTask, id));
}
else
{ //Since ids don't match, this is the first Task being executed in the CEScheduler Task
schedulerIDInsideTask.Value = id; //cache the scheduler ID seen by the thread, so other tasks running in same thread can see this
itemsExecutedCount.Value = 1;
}
//Give enough time for a Task to stay around, so that other tasks will be executed by the same CEScheduler Task
//or else the CESchedulerTask will die and each Task might get executed by a different CEScheduler Task. This does not affect the
//verifications, but its increases the chance of finding a bug if the maxItemPerTask is not respected
new ManualResetEvent(false).WaitOne(20);
};
List<Task> taskList = new List<Task>();
int maxConcurrentTasks = maxConcurrency * maxItemsPerTask * 5;
int maxExclusiveTasks = maxConcurrency * maxItemsPerTask * 2;
// Schedule Tasks in both concurrent and exclusive mode
for (int i = 0; i < maxConcurrentTasks; i++)
taskList.Add(readers.StartNew(work));
for (int i = 0; i < maxExclusiveTasks; i++)
taskList.Add(writers.StartNew(work));
if (completeBeforeTaskWait)
{
schedPair.Complete();
schedPair.Completion.Wait();
Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete");
}
//finally wait for all of the tasks, to ensure they all executed properly
Task.WaitAll(taskList.ToArray());
if (!completeBeforeTaskWait)
{
schedPair.Complete();
schedPair.Completion.Wait();
Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete");
}
}
/// <summary>
/// When user specfices a concurrency level above the level allowed by the task scheduler, the concurrency level should be set
/// to the concurrencylevel specified in the taskscheduler. Also tests that the maxConcurrencyLevel specified was respected
/// </summary>
[Fact]
public static void TestLowerConcurrencyLevel()
{
//a custom scheduler with maxConcurrencyLevel of one
int customSchedulerConcurrency = 1;
TrackingTaskScheduler scheduler = new TrackingTaskScheduler(customSchedulerConcurrency);
// specify a maxConcurrencyLevel > TaskScheduler's maxconcurrencyLevel to ensure the pair takes the min of the two
ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, Int32.MaxValue);
Assert.Equal(scheduler.MaximumConcurrencyLevel, schedPair.ConcurrentScheduler.MaximumConcurrencyLevel);
//Now schedule a reader task that would block and verify that more reader tasks scheduled are not executed
//(as long as the first task is blocked)
TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler);
ManualResetEvent blockReaderTaskEvent = new ManualResetEvent(false);
ManualResetEvent blockMainThreadEvent = new ManualResetEvent(false);
//Add a reader tasks that would block
readers.StartNew(() => { blockMainThreadEvent.Set(); blockReaderTaskEvent.WaitOne(); });
blockMainThreadEvent.WaitOne(); // wait for the blockedTask to start execution
//Now add more reader tasks
int maxConcurrentTasks = Environment.ProcessorCount;
List<Task> taskList = new List<Task>();
for (int i = 0; i < maxConcurrentTasks; i++)
taskList.Add(readers.StartNew(() => { })); //schedule some dummy reader tasks
foreach (Task task in taskList)
{
bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion);
Assert.True(wasTaskStarted, string.Format("Additional reader tasks should not start when scheduler concurrency is {0} and a reader task is blocked", customSchedulerConcurrency));
}
//finally unblock the blocjedTask and wait for all of the tasks, to ensure they all executed properly
blockReaderTaskEvent.Set();
Task.WaitAll(taskList.ToArray());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestConcurrentBlockage(bool useReader)
{
ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair();
TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler);
TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler);
ManualResetEvent blockExclusiveTaskEvent = new ManualResetEvent(false);
ManualResetEvent blockMainThreadEvent = new ManualResetEvent(false);
ManualResetEvent blockMre = new ManualResetEvent(false);
//Schedule a concurrent task and ensure that it is executed, just for fun
Task<bool> conTask = readers.StartNew<bool>(() => { new ManualResetEvent(false).WaitOne(10); ; return true; });
conTask.Wait();
Assert.True(conTask.Result, "The concurrenttask when executed successfully should have returned true");
//Now scehdule a exclusive task that is blocked(thereby preventing other concurrent tasks to finish)
Task<bool> exclusiveTask = writers.StartNew<bool>(() => { blockMainThreadEvent.Set(); blockExclusiveTaskEvent.WaitOne(); return true; });
//With exclusive task in execution mode, schedule a number of concurrent tasks and ensure they are not executed
blockMainThreadEvent.WaitOne();
List<Task> taskList = new List<Task>();
for (int i = 0; i < 20; i++) taskList.Add(readers.StartNew<bool>(() => { blockMre.WaitOne(10); return true; }));
foreach (Task task in taskList)
{
bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion);
Assert.True(wasTaskStarted, "Concurrent tasks should not be executed when a exclusive task is getting executed");
}
blockExclusiveTaskEvent.Set();
Task.WaitAll(taskList.ToArray());
}
[Theory]
[MemberData(nameof(ApiType))]
public static void TestIntegration(String apiType, bool useReader)
{
Debug.WriteLine(string.Format(" Running apiType:{0} useReader:{1}", apiType, useReader));
int taskCount = Environment.ProcessorCount; //To get varying number of tasks as a function of cores
ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair();
CountdownEvent cde = new CountdownEvent(taskCount); //Used to track how many tasks were executed
Action work = () => { cde.Signal(); }; //Work done by all APIs
//Choose the right scheduler to use based on input parameter
TaskScheduler scheduler = useReader ? schedPair.ConcurrentScheduler : schedPair.ExclusiveScheduler;
SelectAPI2Target(apiType, taskCount, scheduler, work);
cde.Wait(); //This will cause the test to block (and timeout) until all tasks are finished
}
/// <summary>
/// Test to ensure that invalid parameters result in exceptions
/// </summary>
[Fact]
public static void TestInvalidParameters()
{
Assert.Throws<ArgumentNullException>(() => new ConcurrentExclusiveSchedulerPair(null)); //TargetScheduler is null
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 0)); //maxConcurrencyLevel is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -2)); //maxConcurrencyLevel is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -1, 0)); //maxItemsPerTask is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -1, -2)); //maxItemsPerTask is invalid
}
/// <summary>
/// Test to ensure completion task works successfully
/// </summary>
[Fact]
public static void TestCompletionTask()
{
// Completion tasks is valid after initialization
{
var cesp = new ConcurrentExclusiveSchedulerPair();
Assert.True(cesp.Completion != null, "CompletionTask should never be null (after initialization)");
Assert.True(!cesp.Completion.IsCompleted, "CompletionTask should not have completed");
}
// Completion task is valid after complete is called
{
var cesp = new ConcurrentExclusiveSchedulerPair();
cesp.Complete();
Assert.True(cesp.Completion != null, "CompletionTask should never be null (after complete)");
cesp.Completion.Wait();
}
// Complete method may be called multiple times, and CompletionTask still completes
{
var cesp = new ConcurrentExclusiveSchedulerPair();
for (int i = 0; i < 20; i++) cesp.Complete(); // ensure multiple calls to Complete succeed
Assert.True(cesp.Completion != null, "CompletionTask should never be null (after multiple completes)");
cesp.Completion.Wait();
}
// Can create a bunch of schedulers, do work on them all, complete them all, and they all complete
{
var cesps = new ConcurrentExclusiveSchedulerPair[100];
for (int i = 0; i < cesps.Length; i++)
{
cesps[i] = new ConcurrentExclusiveSchedulerPair();
}
for (int i = 0; i < cesps.Length; i++)
{
Action work = () => new ManualResetEvent(false).WaitOne(2); ;
Task.Factory.StartNew(work, CancellationToken.None, TaskCreationOptions.None, cesps[i].ConcurrentScheduler);
Task.Factory.StartNew(work, CancellationToken.None, TaskCreationOptions.None, cesps[i].ExclusiveScheduler);
}
for (int i = 0; i < cesps.Length; i++)
{
cesps[i].Complete();
cesps[i].Completion.Wait();
}
}
// Validate that CESP does not implement IDisposable
Assert.Equal(null, new ConcurrentExclusiveSchedulerPair() as IDisposable);
}
/// <summary>
/// Ensure that CESPs can be layered on other CESPs.
/// </summary
[Fact]
public static void TestSchedulerNesting()
{
// Create a hierarchical set of scheduler pairs
var cespParent = new ConcurrentExclusiveSchedulerPair();
var cespChild1 = new ConcurrentExclusiveSchedulerPair(cespParent.ConcurrentScheduler);
var cespChild1Child1 = new ConcurrentExclusiveSchedulerPair(cespChild1.ConcurrentScheduler);
var cespChild1Child2 = new ConcurrentExclusiveSchedulerPair(cespChild1.ExclusiveScheduler);
var cespChild2 = new ConcurrentExclusiveSchedulerPair(cespParent.ExclusiveScheduler);
var cespChild2Child1 = new ConcurrentExclusiveSchedulerPair(cespChild2.ConcurrentScheduler);
var cespChild2Child2 = new ConcurrentExclusiveSchedulerPair(cespChild2.ExclusiveScheduler);
// these are ordered such that we will complete the child schedulers before we complete their parents. That way
// we don't complete a parent that's still in use.
var cesps = new[] {
cespChild1Child1,
cespChild1Child2,
cespChild1,
cespChild2Child1,
cespChild2Child2,
cespChild2,
cespParent,
};
// Get the schedulers from all of the pairs
List<TaskScheduler> schedulers = new List<TaskScheduler>();
foreach (var s in cesps)
{
schedulers.Add(s.ConcurrentScheduler);
schedulers.Add(s.ExclusiveScheduler);
}
// Keep track of all created tasks
var tasks = new List<Task>();
// Queue lots of work to each scheduler
foreach (var scheduler in schedulers)
{
// Create a function that schedules and inlines recursively queued tasks
Action<int> recursiveWork = null;
recursiveWork = depth =>
{
if (depth > 0)
{
Action work = () =>
{
new ManualResetEvent(false).WaitOne(1);
recursiveWork(depth - 1);
};
TaskFactory factory = new TaskFactory(scheduler);
Debug.WriteLine(string.Format("Start tasks in scheduler {0}", scheduler.Id));
Task t1 = factory.StartNew(work); Task t2 = factory.StartNew(work); Task t3 = factory.StartNew(work);
Task.WaitAll(t1, t2, t3);
}
};
for (int i = 0; i < 2; i++)
{
tasks.Add(Task.Factory.StartNew(() => recursiveWork(2), CancellationToken.None, TaskCreationOptions.None, scheduler));
}
}
// Wait for all tasks to complete, then complete the schedulers
Task.WaitAll(tasks.ToArray());
foreach (var cesp in cesps)
{
cesp.Complete();
cesp.Completion.Wait();
}
}
/// <summary>
/// Ensure that continuations and parent/children which hop between concurrent and exclusive work correctly.
/// EH
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestConcurrentExclusiveChain(bool syncContinuations)
{
var scheduler = new TrackingTaskScheduler(Environment.ProcessorCount);
var cesp = new ConcurrentExclusiveSchedulerPair(scheduler);
// continuations
{
var starter = new Task(() => { });
var t = starter;
for (int i = 0; i < 10; i++)
{
t = t.ContinueWith(delegate { }, CancellationToken.None, syncContinuations ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None, cesp.ConcurrentScheduler);
t = t.ContinueWith(delegate { }, CancellationToken.None, syncContinuations ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None, cesp.ExclusiveScheduler);
}
starter.Start(cesp.ExclusiveScheduler);
t.Wait();
}
// parent/child
{
var errorString = "hello faulty world";
var root = Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
throw new InvalidOperationException(errorString);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler).Wait();
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ConcurrentScheduler);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ConcurrentScheduler);
}, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler);
}, CancellationToken.None, TaskCreationOptions.None, cesp.ConcurrentScheduler);
((IAsyncResult)root).AsyncWaitHandle.WaitOne();
Assert.True(root.IsFaulted, "Root should have been faulted by child's error");
var ae = root.Exception.Flatten();
Assert.True(ae.InnerException is InvalidOperationException && ae.InnerException.Message == errorString,
"Child's exception should have propagated to the root.");
}
}
#endregion
#region Helper Methods
public static void SelectAPI2Target(string apiType, int taskCount, TaskScheduler scheduler, Action work)
{
switch (apiType)
{
case "StartNew":
for (int i = 0; i < taskCount; i++) new TaskFactory(scheduler).StartNew(() => { work(); });
break;
case "Start":
for (int i = 0; i < taskCount; i++) new Task(() => { work(); }).Start(scheduler);
break;
case "ContinueWith":
for (int i = 0; i < taskCount; i++)
{
new TaskFactory().StartNew(() => { }).ContinueWith((t) => { work(); }, scheduler);
}
break;
case "FromAsync":
for (int i = 0; i < taskCount; i++)
{
new TaskFactory(scheduler).FromAsync(Task.Factory.StartNew(() => { }), (iar) => { work(); });
}
break;
case "ContinueWhenAll":
for (int i = 0; i < taskCount; i++)
{
new TaskFactory(scheduler).ContinueWhenAll(new Task[] { Task.Factory.StartNew(() => { }) }, (t) => { work(); });
}
break;
case "ContinueWhenAny":
for (int i = 0; i < taskCount; i++)
{
new TaskFactory(scheduler).ContinueWhenAny(new Task[] { Task.Factory.StartNew(() => { }) }, (t) => { work(); });
}
break;
default:
throw new ArgumentOutOfRangeException(String.Format("Api name specified {0} is invalid or is of incorrect case", apiType));
}
}
/// <summary>
/// Used to provide parameters for the TestIntegration test
/// </summary>
public static IEnumerable<object[]> ApiType
{
get
{
List<Object[]> values = new List<object[]>();
foreach (String apiType in new String[] {
"StartNew", "Start", "ContinueWith", /* FromAsync: Not supported in .NET Native */ "ContinueWhenAll", "ContinueWhenAny" })
{
foreach (bool useReader in new bool[] { true, false })
{
values.Add(new Object[] { apiType, useReader });
}
}
return values;
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class UserInfo : IEquatable<UserInfo>
{
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="userName", EmitDefaultValue=false)]
public string UserName { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="userId", EmitDefaultValue=false)]
public string UserId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="userType", EmitDefaultValue=false)]
public string UserType { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="userStatus", EmitDefaultValue=false)]
public string UserStatus { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="uri", EmitDefaultValue=false)]
public string Uri { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { 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 UserInfo {\n");
sb.Append(" UserName: ").Append(UserName).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" UserId: ").Append(UserId).Append("\n");
sb.Append(" UserType: ").Append(UserType).Append("\n");
sb.Append(" UserStatus: ").Append(UserStatus).Append("\n");
sb.Append(" Uri: ").Append(Uri).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).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 UserInfo);
}
/// <summary>
/// Returns true if UserInfo instances are equal
/// </summary>
/// <param name="other">Instance of UserInfo to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UserInfo other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.UserName == other.UserName ||
this.UserName != null &&
this.UserName.Equals(other.UserName)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.UserId == other.UserId ||
this.UserId != null &&
this.UserId.Equals(other.UserId)
) &&
(
this.UserType == other.UserType ||
this.UserType != null &&
this.UserType.Equals(other.UserType)
) &&
(
this.UserStatus == other.UserStatus ||
this.UserStatus != null &&
this.UserStatus.Equals(other.UserStatus)
) &&
(
this.Uri == other.Uri ||
this.Uri != null &&
this.Uri.Equals(other.Uri)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
);
}
/// <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.UserName != null)
hash = hash * 57 + this.UserName.GetHashCode();
if (this.Email != null)
hash = hash * 57 + this.Email.GetHashCode();
if (this.UserId != null)
hash = hash * 57 + this.UserId.GetHashCode();
if (this.UserType != null)
hash = hash * 57 + this.UserType.GetHashCode();
if (this.UserStatus != null)
hash = hash * 57 + this.UserStatus.GetHashCode();
if (this.Uri != null)
hash = hash * 57 + this.Uri.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 57 + this.ErrorDetails.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Security;
using MS.Internal;
using MS.Internal.PresentationCore; // SecurityHelper
using System.Security.Permissions;
using MS.Win32.Penimc;
using MS.Win32;
namespace System.Windows.Input
{
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Class that represents a physical digitizer connected to the system.
/// Tablets are the source of events for the Stylus devices.
/// </summary>
public sealed class TabletDevice : InputDevice
{
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <SecurityNote>
/// Critical: creates security critical data (IpimcTablet)
/// </SecurityNote>
[SecurityCritical]
internal TabletDevice(TabletDeviceInfo tabletInfo, PenThread penThread)
{
_tabletInfo = tabletInfo;
_penThread = penThread;
int count = tabletInfo.StylusDevicesInfo.Length;
StylusDevice[] styluses = new StylusDevice[count];
for ( int i = 0; i < count; i++ )
{
StylusDeviceInfo cursorInfo = tabletInfo.StylusDevicesInfo[i];
styluses[i] = new StylusDevice(
this,
cursorInfo.CursorName,
cursorInfo.CursorId,
cursorInfo.CursorInverted,
cursorInfo.ButtonCollection);
}
_stylusDeviceCollection = new StylusDeviceCollection(styluses);
if (_tabletInfo.DeviceType == TabletDeviceType.Touch)
{
//
_multiTouchSystemGestureLogic = new MultiTouchSystemGestureLogic();
}
}
/////////////////////////////////////////////////////////////////////
/// <SecurityNote>
/// Critical: calls SecurityCritical method _stylusDeviceCollection.Dispose.
/// </SecurityNote>
[SecurityCritical]
internal void Dispose()
{
_tabletInfo.PimcTablet = null;
if (_stylusDeviceCollection != null)
{
_stylusDeviceCollection.Dispose();
_stylusDeviceCollection = null;
}
_penThread = null;
}
/////////////////////////////////////////////////////////////////////
/// <SecurityNote>
/// Critical: - Calls unmanaged code that is SecurityCritical with SUC attribute.
/// - accesses security critical data _pimcTablet.Value
/// - called by constructor
/// </SecurityNote>
[SecurityCritical]
internal StylusDevice UpdateStylusDevices(int stylusId)
{
// REENTRANCY NOTE: Use PenThread to talk to wisptis.exe to make sure we are not reentrant!
// PenImc will cache all the stylus device info so we don't have
// any Out of Proc calls to wisptis.exe to get this info.
StylusDeviceInfo[] stylusDevicesInfo = _penThread.WorkerRefreshCursorInfo(_tabletInfo.PimcTablet.Value);
int cCursors = stylusDevicesInfo.Length;
if (cCursors > StylusDevices.Count)
{
for (int iCursor = 0; iCursor < cCursors; iCursor++)
{
StylusDeviceInfo stylusDeviceInfo = stylusDevicesInfo[iCursor];
// See if we found it. If so go and create the new StylusDevice and add it.
if ( stylusDeviceInfo.CursorId == stylusId )
{
StylusDevice newStylusDevice = new StylusDevice(
this,
stylusDeviceInfo.CursorName,
stylusDeviceInfo.CursorId,
stylusDeviceInfo.CursorInverted,
stylusDeviceInfo.ButtonCollection);
StylusDevices.AddStylusDevice(iCursor, newStylusDevice);
return newStylusDevice;
}
}
}
return null; // Nothing to add
}
/////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the element that input from this device is sent to.
/// </summary>
public override IInputElement Target
{
get
{
VerifyAccess();
StylusDevice stylusDevice = Stylus.CurrentStylusDevice;
if (stylusDevice == null)
return null;
return stylusDevice.Target;
}
}
/////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the PresentationSource that is reporting input for this device.
/// </summary>
/// <remarks>
/// Callers must have UIPermission(UIPermissionWindow.AllWindows) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical - accesses critical data (InputSource on StylusDevice)
/// PublicOK - there is a demand.
/// this is safe as:
/// there is a demand for the UI permissions in the code
/// </SecurityNote>
public override PresentationSource ActiveSource
{
[SecurityCritical]
get
{
SecurityHelper.DemandUIWindowPermission();
VerifyAccess();
StylusDevice stylusDevice = Stylus.CurrentStylusDevice;
if (stylusDevice == null)
return null;
return stylusDevice.ActiveSource; // This also does a security demand.
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns an id of the tablet object unique within the process.
/// </summary>
public int Id
{
get
{
VerifyAccess();
return _tabletInfo.Id;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the friendly name of the tablet.
/// </summary>
public string Name
{
get
{
VerifyAccess();
return _tabletInfo.Name;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the hardware Product ID of the tablet (was PlugAndPlayId).
/// </summary>
public string ProductId
{
get
{
VerifyAccess();
return _tabletInfo.PlugAndPlayId;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the maximum coordinate dimensions that the device can collect.
/// This value is in Tablet Coordinates
/// </summary>
internal Matrix TabletToScreen
{
get
{
return new Matrix( _tabletInfo.SizeInfo.ScreenSize.Width / _tabletInfo.SizeInfo.TabletSize.Width, 0,
0, _tabletInfo.SizeInfo.ScreenSize.Height / _tabletInfo.SizeInfo.TabletSize.Height,
0, 0);
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the size of the digitizer for this TabletDevice.
/// This value is in Tablet Coordinates.
/// </summary>
internal Size TabletSize
{
get
{
return _tabletInfo.SizeInfo.TabletSize;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the size for the display that this TabletDevice is
/// mapped to.
/// This value is in Screen Coordinates.
/// </summary>
internal Size ScreenSize
{
get
{
return _tabletInfo.SizeInfo.ScreenSize;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the capabilities of the tablet hardware.
/// </summary>
public TabletHardwareCapabilities TabletHardwareCapabilities
{
get
{
VerifyAccess();
return _tabletInfo.HardwareCapabilities;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the list of StylusPointProperties supported by this TabletDevice.
/// </summary>
public ReadOnlyCollection<StylusPointProperty> SupportedStylusPointProperties
{
get
{
VerifyAccess();
return _tabletInfo.StylusPointProperties;
}
}
// Helper to return a StylusPointDescription using the SupportedStylusProperties info.
internal StylusPointDescription StylusPointDescription
{
get
{
if (_stylusPointDescription == null)
{
ReadOnlyCollection<StylusPointProperty> properties = SupportedStylusPointProperties;
// InitializeSupportStylusPointProperties must be called first!
Debug.Assert(properties != null);
List<StylusPointPropertyInfo> propertyInfos = new List<StylusPointPropertyInfo>();
for (int i=0; i < properties.Count; i++)
{
propertyInfos.Add(new StylusPointPropertyInfo(properties[i]));
}
_stylusPointDescription = new StylusPointDescription(propertyInfos, _tabletInfo.PressureIndex);
}
return _stylusPointDescription;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the type of tablet device hardware (Stylus, Touch)
/// </summary>
public TabletDeviceType Type
{
get
{
VerifyAccess();
return _tabletInfo.DeviceType;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the friendly string representation of the Tablet object
/// </summary>
public override string ToString()
{
return String.Format(CultureInfo.CurrentCulture, "{0}({1})", base.ToString(), Name);
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the collection of StylusDevices defined on this tablet.
/// An Empty collection is returned if the device has not seen any Stylus Pointers.
/// </summary>
public StylusDeviceCollection StylusDevices
{
get
{
VerifyAccess();
Debug.Assert (_stylusDeviceCollection != null);
return _stylusDeviceCollection;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// </summary>
/// <SecurityNote>
/// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute.
/// - accesses security critical data _pimcTablet.Value
/// - takes in data that is potential security risk (hwnd)
/// </SecurityNote>
[SecurityCritical]
internal PenContext CreateContext(IntPtr hwnd, PenContexts contexts)
{
PenContext penContext;
bool supportInRange = (this.TabletHardwareCapabilities & TabletHardwareCapabilities.HardProximity) != 0;
bool isIntegrated = (this.TabletHardwareCapabilities & TabletHardwareCapabilities.Integrated) != 0;
// Use a PenThread to create a tablet context so we don't cause reentrancy.
PenContextInfo result = _penThread.WorkerCreateContext(hwnd, _tabletInfo.PimcTablet.Value);
penContext = new PenContext(result.PimcContext != null ? result.PimcContext.Value : null,
hwnd, contexts,
supportInRange, isIntegrated, result.ContextId,
result.CommHandle != null ? result.CommHandle.Value : IntPtr.Zero,
Id);
return penContext;
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// </summary>
/// <SecurityNote>
/// Critical: - returns data that is potential a security risk (PenThread)
/// </SecurityNote>
internal PenThread PenThread
{
[SecurityCritical]
get
{
return _penThread;
}
}
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// </summary>
/// <SecurityNote>
/// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute.
/// - accesses security critical data _pimcTablet.Value
/// </SecurityNote>
[SecurityCritical]
internal void UpdateScreenMeasurements()
{
Debug.Assert(CheckAccess());
// Update and reset these sizes to be recalculated the next time they are needed.
_cancelSize = Size.Empty;
_doubleTapSize = Size.Empty;
// Update the size info we use to map tablet coordinates to screen coordinates.
_tabletInfo.SizeInfo = _penThread.WorkerGetUpdatedSizes(_tabletInfo.PimcTablet.Value);
}
// NOTE: UpdateSizeDeltas MUST be called before the returned Size is valid.
// Since we currently only call this while processing Down stylus events
// after StylusDevice.UpdateState has been called it will always be initialized appropriately.
internal Size DoubleTapSize
{
get
{
return _doubleTapSize; // used for double tap detection - updating click count.
}
}
// NOTE: UpdateSizeDeltas MUST be called before the returned Size is valid.
// Since we currently only call this while processing Move stylus events
// after StylusDevice.UpdateState has been called it will always be initialized appropriately.
internal Size CancelSize
{
get
{
return _cancelSize; // Used for drag detection when double tapping.
}
}
// Forces the UpdateSizeDeltas to re-calc the sizes the next time it is called.
// NOTE: We don't invalidate the sizes and just leave them till the next time we
// UpdateSizeDeltas gets called.
internal void InvalidateSizeDeltas()
{
_forceUpdateSizeDeltas = true;
}
internal bool AreSizeDeltasValid()
{
return !(_doubleTapSize.IsEmpty || _cancelSize.IsEmpty);
}
/// <SecurityNote>
/// Critical as this uses SecurityCritical _stylusLogic variable.
///
/// At the top called from StylusLogic::PreProcessInput event which is SecurityCritical
/// </SecurityNote>
[SecurityCritical]
internal void UpdateSizeDeltas(StylusPointDescription description, StylusLogic stylusLogic)
{
if (_doubleTapSize.IsEmpty || _cancelSize.IsEmpty || _forceUpdateSizeDeltas)
{
// Query default settings for mouse drag and double tap (with minimum of 1x1 size).
Size mouseDragDefault = new Size(Math.Max(1, SafeSystemMetrics.DragDeltaX / 2),
Math.Max(1, SafeSystemMetrics.DragDeltaY / 2));
Size mouseDoubleTapDefault = new Size(Math.Max(1, SafeSystemMetrics.DoubleClickDeltaX / 2),
Math.Max(1, SafeSystemMetrics.DoubleClickDeltaY / 2));
StylusPointPropertyInfo xProperty = description.GetPropertyInfo(StylusPointProperties.X);
StylusPointPropertyInfo yProperty = description.GetPropertyInfo(StylusPointProperties.Y);
uint dwXValue = GetPropertyValue(xProperty);
uint dwYValue = GetPropertyValue(yProperty);
if (dwXValue != 0 && dwYValue != 0)
{
_cancelSize = new Size((int)Math.Round((ScreenSize.Width * stylusLogic.CancelDelta) / dwXValue),
(int)Math.Round((ScreenSize.Height * stylusLogic.CancelDelta) / dwYValue));
// Make sure we return whole numbers (pixels are whole numbers) and take the maximum
// value between mouse and stylus settings to be safe.
_cancelSize.Width = Math.Max(mouseDragDefault.Width, _cancelSize.Width);
_cancelSize.Height = Math.Max(mouseDragDefault.Height, _cancelSize.Height);
_doubleTapSize = new Size((int)Math.Round((ScreenSize.Width * stylusLogic.DoubleTapDelta) / dwXValue),
(int)Math.Round((ScreenSize.Height * stylusLogic.DoubleTapDelta) / dwYValue));
// Make sure we return whole numbers (pixels are whole numbers) and take the maximum
// value between mouse and stylus settings to be safe.
_doubleTapSize.Width = Math.Max(mouseDoubleTapDefault.Width, _doubleTapSize.Width);
_doubleTapSize.Height = Math.Max(mouseDoubleTapDefault.Height, _doubleTapSize.Height);
}
else
{
// If no info to do the calculation then use the mouse settings for the default.
_doubleTapSize = mouseDoubleTapDefault;
_cancelSize = mouseDragDefault;
}
_forceUpdateSizeDeltas = false;
}
}
private static uint GetPropertyValue(StylusPointPropertyInfo propertyInfo)
{
uint dw = 0;
switch (propertyInfo.Unit)
{
case StylusPointPropertyUnit.Inches:
if (propertyInfo.Resolution != 0)
dw = (uint) (((propertyInfo.Maximum - propertyInfo.Minimum) * 254) / propertyInfo.Resolution);
break;
case StylusPointPropertyUnit.Centimeters:
if (propertyInfo.Resolution != 0)
dw = (uint) (((propertyInfo.Maximum - propertyInfo.Minimum) * 100) / propertyInfo.Resolution);
break;
default:
dw = 1000;
break;
}
return dw;
}
/// <summary>
/// Sends input reports to the system gesture logic object.
/// </summary>
/// <param name="stylusInputReport">A new input report.</param>
/// <returns>A SystemGesture that was detected, null otherwise.</returns>
/// <SecurityNote>
/// Critical: The generated system gesture is posted back to the input system.
/// SystemGesture events need to be protected.
/// </SecurityNote>
[SecurityCritical]
internal SystemGesture? GenerateStaticGesture(RawStylusInputReport stylusInputReport)
{
if (_multiTouchSystemGestureLogic != null)
{
return _multiTouchSystemGestureLogic.GenerateStaticGesture(stylusInputReport);
}
return null;
}
/// <summary>
/// Accesses the GetLastTabletPoint value from the input report and converts
/// it from tablet device units into device-independent units.
/// </summary>
/// <SecurityNote>
/// Critical: Accesses InputManager and the StylusLogic.
/// TreatAsSafe: Doesn't expose that information.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal Point GetLastTabletPoint(RawStylusInputReport stylusInputReport)
{
var lastPoint = stylusInputReport.GetLastTabletPoint();
if (!_tabletToView.HasValue)
{
//
_tabletToView = InputManager.Current.StylusLogic.GetTabletToViewTransform(this);
}
return _tabletToView.Value.Transform(lastPoint);
}
/////////////////////////////////////////////////////////////////////////
TabletDeviceInfo _tabletInfo; // Hold the info about this tablet device.
/// <SecurityNote>
/// Critical to prevent accidental spread to transparent code
/// </SecurityNote>
[SecurityCritical]
PenThread _penThread; // Hold ref on worker thread we use to talk to wisptis.
StylusDeviceCollection _stylusDeviceCollection;
StylusPointDescription _stylusPointDescription;
// Calculated size in screen coordinates for Drag and DoubleTap detection.
private Size _cancelSize = Size.Empty;
private Size _doubleTapSize = Size.Empty;
private bool _forceUpdateSizeDeltas;
// Determines if recent input should be converted into a static gesture
private MultiTouchSystemGestureLogic _multiTouchSystemGestureLogic;
private Matrix? _tabletToView;
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using bv.common.Core;
using bv.common.Diagnostics;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using eidss.model.Enums;
using eidss.model.Reports;
using DataException = BLToolkit.Data.DataException;
using eidss.model.Core.Security;
using System.Web;
namespace eidss.model.Core
{
[Serializable]
public class EidssSiteContext
{
private long m_CountryID;
private string m_CountryName;
private long m_SiteID;
private long m_RegionID;
private string m_SiteCode;
private string m_SiteHascCode;
private string m_CountryHascCode;
private string m_SiteName;
private SiteType m_SiteType;
private string m_SiteTypeName;
private string m_OrganizationName;
private long m_OrganizationID;
private bool m_IsInitialized;
private static volatile EidssSiteContext m_Instance;
private List<EidssSiteOptions> m_SiteOptions;
private List<EidssSiteOptions> m_GlobalSiteOptions;
private List<CustomMandatoryField> m_CustomMandatoryFields;
private static IReportFactory m_ReportFactory;
private static IBarcodeFactory m_BarcodeFactory;
private static readonly object m_Lock = new object();
private EidssSiteContext()
{
}
#region Properties
public static EidssSiteContext Instance
{
get
{
EidssSiteContext ret = null;
lock (m_Lock)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
ret = HttpContext.Current.Session["SiteContext"] as EidssSiteContext;
if (ret == null)
{
ret = new EidssSiteContext();
HttpContext.Current.Session["SiteContext"] = ret;
}
}
else
{
if (m_Instance == null)
{
m_Instance = new EidssSiteContext();
}
ret = m_Instance;
}
}
return ret;
}
}
public long CountryID
{
get
{
GetSiteInfo();
return m_CountryID;
}
}
public string CountryName
{
get
{
GetSiteInfo();
return m_CountryName;
}
}
public string OrganizationName
{
get
{
GetSiteInfo();
return m_OrganizationName;
}
}
public long OrganizationID
{
get
{
GetSiteInfo();
return m_OrganizationID;
}
}
public string SiteABR
{
get
{
GetSiteInfo();
return m_SiteName;
}
}
public string SiteHASCCode
{
get
{
GetSiteInfo();
return m_SiteHascCode;
}
}
public string CountryHascCode
{
get
{
GetSiteInfo();
return m_CountryHascCode;
}
}
public long SiteID
{
get
{
GetSiteInfo();
return m_SiteID;
}
}
public string SiteCode
{
get
{
GetSiteInfo();
return m_SiteCode;
}
}
public SiteType SiteType
{
get
{
GetSiteInfo();
return m_SiteType;
}
}
public string SiteTypeName
{
get
{
GetSiteInfo();
return m_SiteTypeName;
}
}
public long RegionID
{
get
{
GetSiteInfo();
return m_RegionID;
}
}
public bool IsReadOnlySite
{
get
{
if (m_SiteType == SiteType.Undefined)
{
return false;
}
//TODO:[Mike] Get requirement for readonly site definition
//Return (m_SiteType = SiteType.CDR AndAlso SiteCode <> "001") OrElse (SiteCode >= "002" AndAlso SiteCode <= "009") '
return false;
}
}
public bool IsDTRACustomization
{
get
{
long customCountryID;
if (!Int64.TryParse(GetGlobalSiteOption("CustomizationCountry"), out customCountryID))
{
if (!Int64.TryParse(GetSiteOption("CustomizationCountry"), out customCountryID))
{
customCountryID = CountryID;
}
}
return customCountryID != CountryID;
}
}
public List<EidssSiteOptions> SiteOptions
{
get { return m_SiteOptions ?? (m_SiteOptions = GetSiteOptions("dbo.spLocalSiteOptions_SelectDetail")); }
}
public List<EidssSiteOptions> GlobalSiteOptions
{
get { return m_GlobalSiteOptions ?? (m_GlobalSiteOptions = GetSiteOptions("dbo.spGlobalSiteOptions_SelectDetail")); }
}
public List<CustomMandatoryField> CustomMandatoryFields
{
get
{
return m_CustomMandatoryFields ?? new List<CustomMandatoryField>();
}
}
public static IReportFactory ReportFactory
{
get
{
if (m_ReportFactory == null)
{
const string reportFactory = "ReportFactory";
var loadedObject = ClassLoader.LoadClass(reportFactory);
Dbg.Assert(loadedObject != null, "class {0} can't be loaded", reportFactory);
Dbg.Assert(loadedObject is IReportFactory, "{0} doesn't implement IReportFactory interface", reportFactory);
m_ReportFactory = (IReportFactory)loadedObject;
}
return m_ReportFactory;
}
}
public static IBarcodeFactory BarcodeFactory
{
get
{
if (m_BarcodeFactory == null)
{
const string barcodeFactory = "BarcodeFactory";
var loadedObject = ClassLoader.LoadClass(barcodeFactory);
Dbg.Assert(loadedObject != null, "class {0} can't be loaded", barcodeFactory);
Dbg.Assert(loadedObject is IBarcodeFactory, "{0} doesn't implement IBarcodeFactory interface", barcodeFactory);
m_BarcodeFactory = (IBarcodeFactory)loadedObject;
}
return m_BarcodeFactory;
}
}
#endregion
internal void SetCustomMandatoryFields(List<CustomMandatoryField> list = null, long? idfsCountry = null)
{
m_CustomMandatoryFields = list ?? (new EidssSecurityManager()).GetCustomMandatoryFields(idfsCountry);
}
public string GetSiteOption(string name)
{
return SiteOptions.Where(c => c.strName == name).Select(c => c.strValue).FirstOrDefault();
}
public string GetGlobalSiteOption(string name)
{
return GlobalSiteOptions.Where(c => c.strName == name).Select(c => c.strValue).FirstOrDefault();
}
public int GetGlobalSiteOptionAsInt(string name, int defValue)
{
var val = GlobalSiteOptions.Where(c => c.strName == name).Select(c => c.strValue).FirstOrDefault();
if (val == null) return defValue;
int ret;
if (!int.TryParse(val, out ret))
ret = defValue;
return ret;
}
public void Clear()
{
m_CountryID = 0;
m_CountryName = "";
m_CountryHascCode = "";
m_RegionID = 0;
m_SiteID = 0;
m_SiteCode = "";
m_SiteHascCode = "";
m_SiteType = SiteType.Undefined;
m_SiteName = "";
m_SiteTypeName = "";
m_OrganizationName = "";
m_OrganizationID = 0;
m_IsInitialized = false;
}
private void GetSiteInfo()
{
if (m_IsInitialized)
{
return;
}
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
{
try
{
using (DataTable dt = manager.SetSpCommand("dbo.spGetSiteInfo",
// todo: change to LangId when new database will be deployed
manager.Parameter("@LangID", ModelUserContext.CurrentLanguage)
).ExecuteDataTable())
{
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
m_CountryID = (long) (row["idfsCountry"] == DBNull.Value ? 0 : row["idfsCountry"]);
m_CountryHascCode = (row["strHASCCountry"] == DBNull.Value ? "" : row["strHASCCountry"]).ToString();
m_CountryName = (row["idfsRegion"] == DBNull.Value ? "" : row["strCountryName"]).ToString();
m_RegionID = (long) (row["idfsRegion"] == DBNull.Value ? 0 : row["idfsRegion"]);
m_SiteID = (long) (row["idfsSite"] == DBNull.Value ? 0 : row["idfsSite"]);
m_SiteCode = (row["strSiteID"] == DBNull.Value ? "" : row["strSiteID"]).ToString();
m_SiteHascCode = (row["strHASCsiteID"] == DBNull.Value ? "" : row["strHASCsiteID"]).ToString();
m_SiteType = row["idfsSiteType"] == DBNull.Value ? SiteType.Undefined : (SiteType) row["idfsSiteType"];
m_SiteName = (row["strSiteName"] == DBNull.Value ? "" : row["strSiteName"]).ToString();
m_SiteTypeName = (row["strSiteTypeName"] == DBNull.Value ? "" : row["strSiteTypeName"]).ToString();
m_OrganizationName = (row["strOrganizationName"] == DBNull.Value ? "" : row["strOrganizationName"]).ToString();
m_OrganizationID = (long) (row["idfOffice"] == DBNull.Value ? 0 : row["idfOffice"]);
m_IsInitialized = true;
}
else
{
Clear();
}
}
}
catch (Exception e)
{
if (e is DataException)
{
throw DbModelException.Create(e as DataException);
}
throw;
}
}
}
private List<EidssSiteOptions> GetSiteOptions(string spName)
{
Utils.CheckNotNullOrEmpty(spName, "spName");
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
{
try
{
List<EidssSiteOptions> eidssSiteOptionses = manager.SetSpCommand(spName).ExecuteList<EidssSiteOptions>();
return eidssSiteOptionses;
}
catch (Exception e)
{
if (e is DataException)
{
throw DbModelException.Create(e as DataException);
}
throw;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Administration;
using Microsoft.Extensions.Logging;
using NetFusion.Azure.ServiceBus.Namespaces.Internal;
using NetFusion.Azure.ServiceBus.Publisher;
using NetFusion.Azure.ServiceBus.Settings;
using NetFusion.Azure.ServiceBus.Subscriber;
using NetFusion.Azure.ServiceBus.Subscriber.Internal;
using NetFusion.Base.Logging;
namespace NetFusion.Azure.ServiceBus.Namespaces
{
/// <summary>
/// Class instance created for each configured Azure Service Bus Namespace.
/// Contains clients for sending/subscribing and creating Namespace entities.
/// </summary>
public class NamespaceConnection
{
private readonly IExtendedLogger _logger;
// Associated connection settings:
public NamespaceSettings NamespaceSettings { get; }
// Azure Service Bus clients:
public ServiceBusClient BusClient { get; private set; }
public ServiceBusAdministrationClient AdminClient { get; private set; }
internal NamespaceConnection(IExtendedLogger logger, NamespaceSettings namespaceSettings)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
NamespaceSettings = namespaceSettings ?? throw new ArgumentNullException(nameof(namespaceSettings));
}
// --------------------------------------------------------------------------
/// <summary>
/// Instantiates a client for creating namespace entities and a client for sending
/// and receiving messages from the created entities.
/// </summary>
public void CreateClients()
{
BusClient = new ServiceBusClient(NamespaceSettings.ConnString, BuildOptions());
AdminClient = new ServiceBusAdministrationClient(NamespaceSettings.ConnString);
}
private ServiceBusClientOptions BuildOptions()
{
var defaultOptions = new ServiceBusClientOptions();
defaultOptions.TransportType = NamespaceSettings.TransportType ?? defaultOptions.TransportType;
var retrySettings = NamespaceSettings.RetrySettings;
if (retrySettings != null)
{
var defaultRetryOptions = defaultOptions.RetryOptions;
defaultRetryOptions.Mode = retrySettings.Mode ?? defaultRetryOptions.Mode;
defaultRetryOptions.Delay = retrySettings.Delay ?? defaultRetryOptions.Delay;
defaultRetryOptions.MaxDelay = retrySettings.MaxDelay ?? defaultRetryOptions.MaxDelay;
defaultRetryOptions.MaxRetries = retrySettings.MaxRetries ?? defaultRetryOptions.MaxRetries;
defaultRetryOptions.TryTimeout = retrySettings.TryTimeout ?? defaultRetryOptions.TryTimeout;
}
return defaultOptions;
}
/// <summary>
/// Disposes clients with persistent connections.
/// </summary>
/// <returns>Future Task Result</returns>
public async Task CloseClientsAsync()
{
if (BusClient != null)
{
await BusClient.DisposeAsync().AsTask();
}
}
// ---------------------- Topics --------------------------------------
/// <summary>
/// Determines if the topic has already been created. If found, the properties
/// of the existing topic are updated. Otherwise, the topic is created.
/// </summary>
/// <param name="topicMeta">Metadata describing the topic.</param>
/// <returns>Future Result Task</returns>
public async Task CreateOrUpdateTopic(TopicMeta topicMeta)
{
if (! await UpdateExistingTopic(topicMeta))
{
try
{
LogEntity("Creating", "Topic", topicMeta);
await AdminClient.CreateTopicAsync(topicMeta.ToCreateOptions());
}
catch (ServiceBusException ex)
when (ex.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists)
{
await UpdateExistingTopic(topicMeta);
}
}
}
private async Task<bool> UpdateExistingTopic(TopicMeta topicMeta)
{
if (await AdminClient.TopicExistsAsync(topicMeta.EntityName))
{
LogEntity("Updating", "Topic", topicMeta);
TopicProperties topicProps = await AdminClient.GetTopicAsync(topicMeta.EntityName);
topicMeta.UpdateProperties(topicProps);
await AdminClient.UpdateTopicAsync(topicProps);
return true;
}
return false;
}
// ---------------------- Queues ---------------------------------
/// <summary>
/// Determines if the queue has already been created. If found, the properties
/// of the existing queue are updated. Otherwise, the queue is created.
/// </summary>
/// <param name="queueMeta">Metadata describing the queue.</param>
/// <returns>Future Result Task</returns>
public async Task CreateOrUpdateQueue(QueueMeta queueMeta)
{
if (! await UpdateExistingQueue(queueMeta))
{
try
{
LogEntity("Creating", "Queue", queueMeta);
await AdminClient.CreateQueueAsync(queueMeta.ToCreateOptions());
}
catch (ServiceBusException ex)
when (ex.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists)
{
await UpdateExistingQueue(queueMeta);
}
}
}
private async Task<bool> UpdateExistingQueue(QueueMeta queueMeta)
{
if (await AdminClient.QueueExistsAsync(queueMeta.EntityName))
{
LogEntity("Updating", "Queue", queueMeta);
QueueProperties queueProps = await AdminClient.GetQueueAsync(queueMeta.EntityName);
queueMeta.UpdateProperties(queueProps);
await AdminClient.UpdateQueueAsync(queueProps);
return true;
}
return false;
}
// ---------------------- Subscriptions --------------------------
/// <summary>
/// Determines if the subscription has already been created. If found, the properties
/// of the existing subscription and rules are updated. Otherwise, the subscription
/// with any configured rules is created.
/// </summary>
/// <param name="subscription">The subscription to be created or updated.</param>
/// <returns>Future Result Task</returns>
public async Task CreateOrUpdateSubscription(TopicSubscription subscription)
{
if (! await UpdateExistingSubscription(subscription))
{
try
{
LogSubscription("Creating", "Subscription", subscription);
await AdminClient.CreateSubscriptionAsync(subscription.ToCreateOptions());
await UpdateRules(subscription);
}
catch (ServiceBusException ex)
when (ex.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists)
{
await UpdateExistingSubscription(subscription);
}
}
}
private async Task<bool> UpdateExistingSubscription(TopicSubscription subscription)
{
if (await AdminClient.SubscriptionExistsAsync(subscription.EntityName, subscription.UniqueSubscriptionName))
{
LogSubscription("Updating", "Subscription", subscription);
SubscriptionProperties subscriptionProps = await AdminClient.GetSubscriptionAsync(
subscription.EntityName, subscription.UniqueSubscriptionName);
subscription.UpdateSubscriptionProperties(subscriptionProps);
await AdminClient.UpdateSubscriptionAsync(subscriptionProps);
await UpdateRules(subscription);
return true;
}
return false;
}
private async Task UpdateRules(TopicSubscription subscription)
{
await SyncRules(subscription);
await UpdateDefaultRule(subscription);
}
private async Task SyncRules(TopicSubscription subscription)
{
var existingRules = await ListRules(subscription).ToArrayAsync();
var rolesToDelete = existingRules.Where(r => !subscription.RuleOptions.Any(ro => ro.Name == r.Name));
foreach (var rule in rolesToDelete) await DeleteRule(subscription, rule.Name);
var rolesToAdd = subscription.RuleOptions.Where(ro => !existingRules.Any(r => r.Name == ro.Name));
foreach (var rule in rolesToAdd) await CreateRule(subscription, rule);
var rolesToUpdate = subscription.RuleOptions.Where(ro => existingRules.Count(r => r.Name == ro.Name) == 1);
foreach (var rule in rolesToUpdate) await UpdateRule(subscription, existingRules, rule);
}
private async Task DeleteRule(TopicSubscription subscription, string ruleName)
{
if (await AdminClient.RuleExistsAsync(subscription.EntityName, subscription.UniqueSubscriptionName, ruleName))
{
LogRule("Deleting", subscription, ruleName);
try { await AdminClient.DeleteRuleAsync(subscription.EntityName, subscription.UniqueSubscriptionName, ruleName); }
catch (ServiceBusException ex) when (ex.Reason == ServiceBusFailureReason.MessagingEntityNotFound) { }
}
}
private async Task CreateRule(TopicSubscription subscription, CreateRuleOptions rule)
{
if (! await AdminClient.RuleExistsAsync(subscription.EntityName, subscription.UniqueSubscriptionName, rule.Name))
{
LogRule("Creating", subscription, rule.Name);
try { await AdminClient.CreateRuleAsync(subscription.EntityName, subscription.UniqueSubscriptionName, rule); }
catch (ServiceBusException ex) when (ex.Reason == ServiceBusFailureReason.MessagingEntityAlreadyExists) { }
}
}
private async Task UpdateRule(TopicSubscription subscription, IEnumerable<RuleProperties> rules, CreateRuleOptions rule)
{
LogRule("Updating", subscription, rule.Name);
var existingRule = rules.First(er => er.Name == rule.Name);
existingRule.Filter = rule.Filter;
await AdminClient.UpdateRuleAsync(subscription.EntityName, subscription.UniqueSubscriptionName, existingRule);
}
// Based on the list of rules associated with a subscription, determines if the $Default rule applies.
// When custom rules are applied to a topic subscription, the $Default rule must be removed so only
// the custom rules apply. If no custom roles are specified, the $Default rule must either remain or
// be added back. The $Default rule is coded as (1=1) so all messages will apply.
private async Task UpdateDefaultRule(TopicSubscription subscription)
{
if (subscription.RuleOptions.Any())
{
LogRule("Deleting", subscription, CreateRuleOptions.DefaultRuleName);
await DeleteRule(subscription, CreateRuleOptions.DefaultRuleName);
}
else
{
LogRule("Creating", subscription, CreateRuleOptions.DefaultRuleName);
await CreateRule(subscription, new CreateRuleOptions(CreateRuleOptions.DefaultRuleName));
}
}
// Returns all the roles associated with a topic subscription. If there are that many rules
// that paging applies, then we surely have an issue!
private async IAsyncEnumerable<RuleProperties> ListRules(TopicSubscription subscription)
{
string token = null;
do
{
await foreach (var page in AdminClient
.GetRulesAsync(subscription.EntityName, subscription.UniqueSubscriptionName)
.AsPages(token))
{
token = page.ContinuationToken;
foreach (var rule in page.Values)
{
if (rule.Name != CreateRuleOptions.DefaultRuleName) yield return rule;
}
}
} while (token != null);
}
// -------------------------------- Logging ---------------------------------
private void LogEntity(string action, string entityType, NamespaceEntity entity)
{
_logger.Log<NamespaceConnection>(LogLevel.Debug, "{action} {entityType}: {entity}",
action,
entityType,
entity);
}
private void LogSubscription(string action, string entityType, EntitySubscription subscription)
{
_logger.Log<NamespaceConnection>(LogLevel.Debug, "{action} {entityType}: {subscription}",
action,
entityType,
subscription);
}
private void LogRule(string action, TopicSubscription subscription, string ruleName)
{
_logger.Log<NamespaceConnection>(LogLevel.Debug, "{action} Rule: {ruleName} on {subscription}",
action,
ruleName,
subscription);
}
}
}
| |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using FluentAssertions;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace YamlDotNet.Test.Serialization
{
public class SerializationTestHelper
{
private Serializer serializer;
private Deserializer deserializer;
protected T DoRoundtripFromObjectTo<T>(object obj)
{
return DoRoundtripFromObjectTo<T>(obj, Serializer);
}
protected T DoRoundtripFromObjectTo<T>(object obj, Serializer serializer)
{
return DoRoundtripFromObjectTo<T>(obj, serializer, Deserializer);
}
protected T DoRoundtripFromObjectTo<T>(object obj, Serializer serializer, Deserializer deserializer)
{
var writer = new StringWriter();
serializer.Serialize(writer, obj);
Dump.WriteLine(writer);
return deserializer.Deserialize<T>(UsingReaderFor(writer));
}
protected T DoRoundtripOn<T>(object obj)
{
return DoRoundtripOn<T>(obj, Serializer);
}
protected T DoRoundtripOn<T>(object obj, Serializer serializer)
{
var writer = new StringWriter();
serializer.Serialize(writer, obj, typeof(T));
Dump.WriteLine(writer);
return new Deserializer().Deserialize<T>(UsingReaderFor(writer));
}
protected Serializer Serializer
{
get { return CurrentOrNew(() => new Serializer()); }
}
protected Serializer RoundtripSerializer
{
get { return CurrentOrNew(() => new Serializer(SerializationOptions.Roundtrip)); }
}
protected Serializer EmitDefaultsSerializer
{
get { return CurrentOrNew(() => new Serializer(SerializationOptions.EmitDefaults)); }
}
protected Serializer RoundtripEmitDefaultsSerializer
{
get { return CurrentOrNew(() => new Serializer(SerializationOptions.Roundtrip | SerializationOptions.EmitDefaults)); }
}
protected Serializer EmitDefaultsJsonCompatibleSerializer
{
get { return CurrentOrNew(() => new Serializer(SerializationOptions.EmitDefaults | SerializationOptions.JsonCompatible)); }
}
protected Serializer RoundtripEmitDefaultsJsonCompatibleSerializer
{
get { return CurrentOrNew(() => new Serializer(SerializationOptions.EmitDefaults |
SerializationOptions.JsonCompatible |
SerializationOptions.Roundtrip));
}
}
private Serializer CurrentOrNew(Func<Serializer> serializerFactory)
{
return serializer = serializer ?? serializerFactory();
}
protected Deserializer Deserializer
{
get { return deserializer = deserializer ?? new Deserializer(); }
}
protected void AssumingDeserializerWith(IObjectFactory factory)
{
deserializer = new Deserializer(factory);
}
protected TextReader UsingReaderFor(TextWriter buffer)
{
return UsingReaderFor(buffer.ToString());
}
protected TextReader UsingReaderFor(string text)
{
return new StringReader(text);
}
protected static EventReader EventReaderFor(string yaml)
{
return new EventReader(new Parser(new StringReader(yaml)));
}
protected string Lines(params string[] lines)
{
return string.Join(Environment.NewLine, lines);
}
protected object Entry(string key, string value)
{
return new DictionaryEntry(key, value);
}
}
// ReSharper disable InconsistentNaming
[Flags]
public enum EnumExample
{
None,
One,
Two
}
public class CircularReference
{
public CircularReference Child1 { get; set; }
public CircularReference Child2 { get; set; }
}
[TypeConverter(typeof(ConvertibleConverter))]
public class Convertible : IConvertible
{
public string Left { get; set; }
public string Right { get; set; }
public object ToType(Type conversionType, IFormatProvider provider)
{
conversionType.Should().Be<string>();
return ToString(provider);
}
public string ToString(IFormatProvider provider)
{
provider.Should().Be(CultureInfo.InvariantCulture);
return string.Format(provider, "[{0}, {1}]", Left, Right);
}
#region Unsupported Members
public System.TypeCode GetTypeCode()
{
throw new NotSupportedException();
}
public bool ToBoolean(IFormatProvider provider)
{
throw new NotSupportedException();
}
public byte ToByte(IFormatProvider provider)
{
throw new NotSupportedException();
}
public char ToChar(IFormatProvider provider)
{
throw new NotSupportedException();
}
public DateTime ToDateTime(IFormatProvider provider)
{
throw new NotSupportedException();
}
public decimal ToDecimal(IFormatProvider provider)
{
throw new NotSupportedException();
}
public double ToDouble(IFormatProvider provider)
{
throw new NotSupportedException();
}
public short ToInt16(IFormatProvider provider)
{
throw new NotSupportedException();
}
public int ToInt32(IFormatProvider provider)
{
throw new NotSupportedException();
}
public long ToInt64(IFormatProvider provider)
{
throw new NotSupportedException();
}
public sbyte ToSByte(IFormatProvider provider)
{
throw new NotSupportedException();
}
public float ToSingle(IFormatProvider provider)
{
throw new NotSupportedException();
}
public ushort ToUInt16(IFormatProvider provider)
{
throw new NotSupportedException();
}
public uint ToUInt32(IFormatProvider provider)
{
throw new NotSupportedException();
}
public ulong ToUInt64(IFormatProvider provider)
{
throw new NotSupportedException();
}
#endregion
}
public class ConvertibleConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return false;
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (!(value is string))
throw new InvalidOperationException();
var parts = (value as string).Split(' ');
return new Convertible {
Left = parts[0],
Right = parts[1]
};
}
}
public class MissingDefaultCtor
{
public string Value;
public MissingDefaultCtor(string value)
{
Value = value;
}
}
public class MissingDefaultCtorConverter : IYamlTypeConverter
{
public bool Accepts(Type type)
{
return type == typeof(MissingDefaultCtor);
}
public object ReadYaml(IParser parser, Type type)
{
var value = ((Scalar) parser.Current).Value;
parser.MoveNext();
return new MissingDefaultCtor(value);
}
public void WriteYaml(IEmitter emitter, object value, Type type)
{
emitter.Emit(new Scalar(((MissingDefaultCtor) value).Value));
}
}
public class InheritanceExample
{
public object SomeScalar { get; set; }
public Base RegularBase { get; set; }
[YamlMember(serializeAs: typeof(Base))]
public Base BaseWithSerializeAs { get; set; }
}
public class InterfaceExample
{
public IDerived Derived { get; set; }
}
public interface IBase
{
string BaseProperty { get; set; }
}
public interface IDerived : IBase
{
string DerivedProperty { get; set; }
}
public class Base : IBase
{
public string BaseProperty { get; set; }
}
public class Derived : Base, IDerived
{
public string DerivedProperty { get; set; }
}
public class EmptyBase
{
}
public class EmptyDerived : EmptyBase
{
}
public class Simple
{
public string aaa { get; set; }
}
public class SimpleScratch
{
public string Scratch { get; set; }
public bool DeleteScratch { get; set; }
public IEnumerable<string> MappedScratch { get; set; }
}
public class Example
{
public bool MyFlag { get; set; }
public string Nothing { get; set; }
public int MyInt { get; set; }
public double MyDouble { get; set; }
public string MyString { get; set; }
public DateTime MyDate { get; set; }
public TimeSpan MyTimeSpan { get; set; }
public Point MyPoint { get; set; }
public int? MyNullableWithValue { get; set; }
public int? MyNullableWithoutValue { get; set; }
public Example()
{
MyInt = 1234;
MyDouble = 6789.1011;
MyString = "Hello world";
MyDate = DateTime.Now;
MyTimeSpan = TimeSpan.FromHours(1);
MyPoint = new Point(100, 200);
MyNullableWithValue = 8;
}
}
public class OrderExample
{
public OrderExample()
{
this.Order1 = "Order1 value";
this.Order2 = "Order2 value";
}
[YamlMember(Order = 2)]
public String Order2 { get; set; }
[YamlMember(Order = 1)]
public String Order1 { get; set; }
}
public class IgnoreExample
{
[YamlIgnore]
public String IgnoreMe
{
get { throw new NotImplementedException("Accessing a [YamlIgnore] property"); }
set { throw new NotImplementedException("Accessing a [YamlIgnore] property"); }
}
}
public class ScalarStyleExample
{
public ScalarStyleExample()
{
var content = "Test";
this.LiteralString = content;
this.DoubleQuotedString = content;
}
[YamlMember(ScalarStyle = ScalarStyle.Literal)]
public String LiteralString { get; set; }
[YamlMember(ScalarStyle = ScalarStyle.DoubleQuoted)]
public String DoubleQuotedString { get; set; }
}
public class DefaultsExample
{
public const string DefaultValue = "myDefault";
[DefaultValue(DefaultValue)]
public string Value { get; set; }
}
public class CustomGenericDictionary : IDictionary<string, string>
{
private readonly Dictionary<string, string> dictionary = new Dictionary<string, string>();
public void Add(string key, string value)
{
dictionary.Add(key, value);
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#region Unsupported Members
public bool ContainsKey(string key)
{
throw new NotSupportedException();
}
public ICollection<string> Keys
{
get { throw new NotSupportedException(); }
}
public bool Remove(string key)
{
throw new NotSupportedException();
}
public bool TryGetValue(string key, out string value)
{
throw new NotSupportedException();
}
public ICollection<string> Values
{
get { throw new NotSupportedException(); }
}
public string this[string key]
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public void Add(KeyValuePair<string, string> item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(KeyValuePair<string, string> item)
{
throw new NotSupportedException();
}
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
{
throw new NotSupportedException();
}
public int Count
{
get { throw new NotSupportedException(); }
}
public bool IsReadOnly
{
get { throw new NotSupportedException(); }
}
public bool Remove(KeyValuePair<string, string> item)
{
throw new NotSupportedException();
}
#endregion
}
public class NameConvention
{
public string FirstTest { get; set; }
public string SecondTest { get; set; }
public string ThirdTest { get; set; }
[YamlMember(Alias = "fourthTest")]
public string AliasTest { get; set; }
[YamlIgnore]
public string fourthTest { get; set; }
}
}
| |
using System;
using System.Diagnostics;
namespace ClosedXML.Excel
{
internal class XLAddress : IXLAddress
{
#region Static
/// <summary>
/// Create address without worksheet. For calculation only!
/// </summary>
/// <param name="cellAddressString"></param>
/// <returns></returns>
public static XLAddress Create(string cellAddressString)
{
return Create(null, cellAddressString);
}
public static XLAddress Create(XLAddress cellAddress)
{
return new XLAddress(cellAddress.Worksheet, cellAddress.RowNumber, cellAddress.ColumnNumber, cellAddress.FixedRow, cellAddress.FixedColumn);
}
public static XLAddress Create(XLWorksheet worksheet, string cellAddressString)
{
var fixedColumn = cellAddressString[0] == '$';
Int32 startPos;
if (fixedColumn)
{
startPos = 1;
}
else
{
startPos = 0;
}
int rowPos = startPos;
while (cellAddressString[rowPos] > '9')
{
rowPos++;
}
var fixedRow = cellAddressString[rowPos] == '$';
string columnLetter;
int rowNumber;
if (fixedRow)
{
if (fixedColumn)
{
columnLetter = cellAddressString.Substring(startPos, rowPos - 1);
}
else
{
columnLetter = cellAddressString.Substring(startPos, rowPos);
}
rowNumber = int.Parse(cellAddressString.Substring(rowPos + 1), XLHelper.NumberStyle, XLHelper.ParseCulture);
}
else
{
if (fixedColumn)
{
columnLetter = cellAddressString.Substring(startPos, rowPos - 1);
}
else
{
columnLetter = cellAddressString.Substring(startPos, rowPos);
}
rowNumber = Int32.Parse(cellAddressString.Substring(rowPos), XLHelper.NumberStyle, XLHelper.ParseCulture);
}
return new XLAddress(worksheet, rowNumber, columnLetter, fixedRow, fixedColumn);
}
#endregion
#region Private fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private bool _fixedRow;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private bool _fixedColumn;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _columnLetter;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int _rowNumber;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int _columnNumber;
private string _trimmedAddress;
#endregion
#region Constructors
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using a mixed notation. Attention: without worksheet for calculation only!
/// </summary>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnLetter">The column letter of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(int rowNumber, string columnLetter, bool fixedRow, bool fixedColumn)
: this(null, rowNumber, columnLetter, fixedRow, fixedColumn)
{
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using a mixed notation.
/// </summary>
/// <param name = "worksheet"></param>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnLetter">The column letter of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(XLWorksheet worksheet, int rowNumber, string columnLetter, bool fixedRow, bool fixedColumn)
: this(worksheet, rowNumber, XLHelper.GetColumnNumberFromLetter(columnLetter), fixedRow, fixedColumn)
{
_columnLetter = columnLetter;
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using R1C1 notation. Attention: without worksheet for calculation only!
/// </summary>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnNumber">The column number of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(int rowNumber, int columnNumber, bool fixedRow, bool fixedColumn)
: this(null, rowNumber, columnNumber, fixedRow, fixedColumn)
{
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using R1C1 notation.
/// </summary>
/// <param name = "worksheet"></param>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnNumber">The column number of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(XLWorksheet worksheet, int rowNumber, int columnNumber, bool fixedRow, bool fixedColumn)
{
Worksheet = worksheet;
_rowNumber = rowNumber;
_columnNumber = columnNumber;
_columnLetter = null;
_fixedColumn = fixedColumn;
_fixedRow = fixedRow;
}
#endregion
#region Properties
public XLWorksheet Worksheet { get; internal set; }
IXLWorksheet IXLAddress.Worksheet
{
[DebuggerStepThrough]
get { return Worksheet; }
}
public bool HasWorksheet
{
[DebuggerStepThrough]
get { return Worksheet != null; }
}
public bool FixedRow
{
get { return _fixedRow; }
set { _fixedRow = value; }
}
public bool FixedColumn
{
get { return _fixedColumn; }
set { _fixedColumn = value; }
}
/// <summary>
/// Gets the row number of this address.
/// </summary>
public Int32 RowNumber
{
get { return _rowNumber; }
}
/// <summary>
/// Gets the column number of this address.
/// </summary>
public Int32 ColumnNumber
{
get { return _columnNumber; }
}
/// <summary>
/// Gets the column letter(s) of this address.
/// </summary>
public String ColumnLetter
{
get { return _columnLetter ?? (_columnLetter = XLHelper.GetColumnLetterFromNumber(_columnNumber)); }
}
#endregion
#region Overrides
public override string ToString()
{
String retVal = ColumnLetter;
if (_fixedColumn)
{
retVal = "$" + retVal;
}
if (_fixedRow)
{
retVal += "$";
}
retVal += _rowNumber.ToInvariantString();
return retVal;
}
public string ToString(XLReferenceStyle referenceStyle)
{
if (referenceStyle == XLReferenceStyle.A1)
{
return ColumnLetter + _rowNumber.ToInvariantString();
}
if (referenceStyle == XLReferenceStyle.R1C1)
{
return String.Format("R{0}C{1}", _rowNumber.ToInvariantString(), ColumnNumber);
}
if (HasWorksheet && Worksheet.Workbook.ReferenceStyle == XLReferenceStyle.R1C1)
{
return String.Format("R{0}C{1}", _rowNumber.ToInvariantString(), ColumnNumber);
}
return ColumnLetter + _rowNumber.ToInvariantString();
}
#endregion
#region Methods
public string GetTrimmedAddress()
{
return _trimmedAddress ?? (_trimmedAddress = ColumnLetter + _rowNumber.ToInvariantString());
}
#endregion
#region Operator Overloads
public static XLAddress operator +(XLAddress left, XLAddress right)
{
return new XLAddress(left.Worksheet,
left.RowNumber + right.RowNumber,
left.ColumnNumber + right.ColumnNumber,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator -(XLAddress left, XLAddress right)
{
return new XLAddress(left.Worksheet,
left.RowNumber - right.RowNumber,
left.ColumnNumber - right.ColumnNumber,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator +(XLAddress left, Int32 right)
{
return new XLAddress(left.Worksheet,
left.RowNumber + right,
left.ColumnNumber + right,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator -(XLAddress left, Int32 right)
{
return new XLAddress(left.Worksheet,
left.RowNumber - right,
left.ColumnNumber - right,
left._fixedRow,
left._fixedColumn);
}
public static Boolean operator ==(XLAddress left, XLAddress right)
{
if (ReferenceEquals(left, right))
{
return true;
}
return !ReferenceEquals(left, null) && left.Equals(right);
}
public static Boolean operator !=(XLAddress left, XLAddress right)
{
return !(left == right);
}
#endregion
#region Interface Requirements
#region IEqualityComparer<XLCellAddress> Members
public Boolean Equals(IXLAddress x, IXLAddress y)
{
return x == y;
}
public Int32 GetHashCode(IXLAddress obj)
{
return obj.GetHashCode();
}
public new Boolean Equals(object x, object y)
{
return x == y;
}
public Int32 GetHashCode(object obj)
{
return (obj).GetHashCode();
}
public override int GetHashCode()
{
return _rowNumber ^ _columnNumber;
}
#endregion
#region IEquatable<XLCellAddress> Members
public bool Equals(IXLAddress other)
{
var right = other as XLAddress;
if (ReferenceEquals(right, null))
{
return false;
}
return _rowNumber == right._rowNumber && _columnNumber == right._columnNumber;
}
public override Boolean Equals(Object other)
{
return Equals((XLAddress) other);
}
#endregion
#endregion
public String ToStringRelative()
{
return ToStringRelative(false);
}
public String ToStringFixed()
{
return ToStringFixed(XLReferenceStyle.Default);
}
public String ToStringRelative(Boolean includeSheet)
{
if (includeSheet)
return String.Format("'{0}'!{1}",
Worksheet.Name,
GetTrimmedAddress());
return GetTrimmedAddress();
}
public String ToStringFixed(XLReferenceStyle referenceStyle)
{
return ToStringFixed(referenceStyle, false);
}
public String ToStringFixed(XLReferenceStyle referenceStyle, Boolean includeSheet)
{
String address;
if (referenceStyle == XLReferenceStyle.A1)
address = String.Format("${0}${1}", ColumnLetter, _rowNumber.ToInvariantString());
else if (referenceStyle == XLReferenceStyle.R1C1)
address = String.Format("R{0}C{1}", _rowNumber.ToInvariantString(), ColumnNumber);
else if (HasWorksheet && Worksheet.Workbook.ReferenceStyle == XLReferenceStyle.R1C1)
address = String.Format("R{0}C{1}", _rowNumber.ToInvariantString(), ColumnNumber);
else
address = String.Format("${0}${1}", ColumnLetter, _rowNumber.ToInvariantString());
if (includeSheet)
return String.Format("'{0}'!{1}",
Worksheet.Name,
address);
return address;
}
public String UniqueId { get { return RowNumber.ToString("0000000") + ColumnNumber.ToString("00000"); } }
}
}
| |
// <copyright file="Log.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Diagnostics;
using System.Threading;
using IX.StandardExtensions.Contracts;
using JetBrains.Annotations;
namespace IX.Abstractions.Logging;
/// <summary>
/// Logging engine.
/// </summary>
[PublicAPI]
public static class Log
{
#region Internal state
private static readonly AsyncLocal<ILog?> CurrentContext = new();
#endregion
#region Properties and indexers
/// <summary>
/// Gets the default logger.
/// </summary>
public static ILog? Default { get; }
/// <summary>
/// Gets the currently-used logger.
/// </summary>
public static ILog? Current => CurrentContext.Value ?? Default;
#endregion
#region Methods
#region Static methods
/// <summary>
/// Logs a critical error message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolCritical)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Critical(string message) => Current?.Critical(message);
/// <summary>
/// Logs a critical error message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
/// <param name="formatParameters">
/// The string format parameters.
/// </param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolCritical)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Critical(
string message,
params string[] formatParameters) =>
Current?.Critical(
message,
formatParameters);
/// <summary>
/// Logs a critical error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolCritical)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Critical(
Exception exception,
string message) =>
Current?.Critical(
exception,
message);
/// <summary>
/// Logs a critical error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
/// <param name="formatParameters">The string format parameters.</param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolCritical)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Critical(
Exception exception,
string message,
params string[] formatParameters) =>
Current?.Critical(
exception,
message,
formatParameters);
/// <summary>
/// Logs a debug message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Debug(string message) => Current?.Debug(message);
/// <summary>
/// Logs a debug message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
/// <param name="formatParameters">
/// The string format parameters.
/// </param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Debug(
string message,
params string[] formatParameters) =>
Current?.Debug(
message,
formatParameters);
/// <summary>
/// Logs a debug message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Debug(
Exception exception,
string message) =>
Current?.Debug(
exception,
message);
/// <summary>
/// Logs a debug message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
/// <param name="formatParameters">The string format parameters.</param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Debug(
Exception exception,
string message,
params string[] formatParameters) =>
Current?.Debug(
exception,
message,
formatParameters);
/// <summary>
/// Logs an error message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Error(string message) => Current?.Error(message);
/// <summary>
/// Logs an error message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
/// <param name="formatParameters">
/// The string format parameters.
/// </param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Error(
string message,
params string[] formatParameters) =>
Current?.Error(
message,
formatParameters);
/// <summary>
/// Logs an error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Error(
Exception exception,
string message) =>
Current?.Error(
exception,
message);
/// <summary>
/// Logs an error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
/// <param name="formatParameters">The string format parameters.</param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Error(
Exception exception,
string message,
params string[] formatParameters) =>
Current?.Error(
exception,
message,
formatParameters);
/// <summary>
/// Logs a fatal error message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolCritical)]
[Conditional(Constants.LoggingSymbolFatal)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Fatal(string message) => Current?.Fatal(message);
/// <summary>
/// Logs a fatal error message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
/// <param name="formatParameters">
/// The string format parameters.
/// </param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolCritical)]
[Conditional(Constants.LoggingSymbolFatal)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Fatal(
string message,
params string[] formatParameters) =>
Current?.Fatal(
message,
formatParameters);
/// <summary>
/// Logs a fatal error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolCritical)]
[Conditional(Constants.LoggingSymbolFatal)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Fatal(
Exception exception,
string message) =>
Current?.Fatal(
exception,
message);
/// <summary>
/// Logs a fatal error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
/// <param name="formatParameters">The string format parameters.</param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolError)]
[Conditional(Constants.LoggingSymbolCritical)]
[Conditional(Constants.LoggingSymbolFatal)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Fatal(
Exception exception,
string message,
params string[] formatParameters) =>
Current?.Fatal(
exception,
message,
formatParameters);
/// <summary>
/// Logs an informational message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Info(string message) => Current?.Info(message);
/// <summary>
/// Logs an informational message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
/// <param name="formatParameters">
/// The string format parameters.
/// </param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Info(
string message,
params string[] formatParameters) =>
Current?.Info(
message,
formatParameters);
/// <summary>
/// Logs an informational message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Info(
Exception exception,
string message) =>
Current?.Info(
exception,
message);
/// <summary>
/// Logs an informational message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
/// <param name="formatParameters">The string format parameters.</param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Info(
Exception exception,
string message,
params string[] formatParameters) =>
Current?.Info(
exception,
message,
formatParameters);
/// <summary>
/// Uses a special logger in a context.
/// </summary>
/// <param name="customLogger">The custom logger to use.</param>
/// <returns>A disposable context for this logger, that resets it upon disposal.</returns>
/// <exception cref="InvalidOperationException">There already is a special logging context.</exception>
public static IDisposable UseSpecialLogger(ILog customLogger)
{
if (CurrentContext.Value != null)
{
throw new InvalidOperationException();
}
CurrentContext.Value = Requires.NotNull(customLogger);
return new SpecialLoggerContext();
}
/// <summary>
/// Logs a warning message.
/// </summary>
/// <param name="message">
/// The message to log.
/// </param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Warning(string message) => Current?.Warning(message);
/// <summary>
/// Logs a warning message.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="formatParameters">The string format parameters.</param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Warning(
string message,
params string[] formatParameters) =>
Current?.Warning(
message,
formatParameters);
/// <summary>
/// Logs a warning message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Warning(
Exception exception,
string message) =>
Current?.Warning(
exception,
message);
/// <summary>
/// Logs a warning message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message to log.</param>
/// <param name="formatParameters">The string format parameters.</param>
[StringFormatMethod("message")]
[Conditional(Constants.LoggingSymbolDebug)]
[Conditional(Constants.LoggingSymbolInfo)]
[Conditional(Constants.LoggingSymbolWarning)]
[Conditional(Constants.LoggingSymbolAll)]
public static void Warning(
Exception exception,
string message,
params string[] formatParameters) =>
Current?.Warning(
exception,
message,
formatParameters);
#endregion
#endregion
#region Nested types and delegates
private sealed class SpecialLoggerContext : IDisposable
{
#region Methods
#region Interface implementations
public void Dispose() => CurrentContext.Value = null;
#endregion
#endregion
}
#endregion
}
| |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
namespace UnityEditor.Rendering.PostProcessing
{
[PostProcessEditor(typeof(ColorGrading))]
public sealed class ColorGradingEditor : PostProcessEffectEditor<ColorGrading>
{
SerializedParameterOverride m_GradingMode;
static GUIContent[] s_Curves =
{
new GUIContent("Master"),
new GUIContent("Red"),
new GUIContent("Green"),
new GUIContent("Blue"),
new GUIContent("Hue Vs Hue"),
new GUIContent("Hue Vs Sat"),
new GUIContent("Sat Vs Sat"),
new GUIContent("Lum Vs Sat")
};
SerializedParameterOverride m_ExternalLut;
SerializedParameterOverride m_Tonemapper;
SerializedParameterOverride m_ToneCurveToeStrength;
SerializedParameterOverride m_ToneCurveToeLength;
SerializedParameterOverride m_ToneCurveShoulderStrength;
SerializedParameterOverride m_ToneCurveShoulderLength;
SerializedParameterOverride m_ToneCurveShoulderAngle;
SerializedParameterOverride m_ToneCurveGamma;
SerializedParameterOverride m_LdrLut;
SerializedParameterOverride m_LdrLutContribution;
SerializedParameterOverride m_Temperature;
SerializedParameterOverride m_Tint;
SerializedParameterOverride m_ColorFilter;
SerializedParameterOverride m_HueShift;
SerializedParameterOverride m_Saturation;
SerializedParameterOverride m_Brightness;
SerializedParameterOverride m_PostExposure;
SerializedParameterOverride m_Contrast;
SerializedParameterOverride m_MixerRedOutRedIn;
SerializedParameterOverride m_MixerRedOutGreenIn;
SerializedParameterOverride m_MixerRedOutBlueIn;
SerializedParameterOverride m_MixerGreenOutRedIn;
SerializedParameterOverride m_MixerGreenOutGreenIn;
SerializedParameterOverride m_MixerGreenOutBlueIn;
SerializedParameterOverride m_MixerBlueOutRedIn;
SerializedParameterOverride m_MixerBlueOutGreenIn;
SerializedParameterOverride m_MixerBlueOutBlueIn;
SerializedParameterOverride m_Lift;
SerializedParameterOverride m_Gamma;
SerializedParameterOverride m_Gain;
SerializedParameterOverride m_MasterCurve;
SerializedParameterOverride m_RedCurve;
SerializedParameterOverride m_GreenCurve;
SerializedParameterOverride m_BlueCurve;
SerializedParameterOverride m_HueVsHueCurve;
SerializedParameterOverride m_HueVsSatCurve;
SerializedParameterOverride m_SatVsSatCurve;
SerializedParameterOverride m_LumVsSatCurve;
// Internal references to the actual animation curves
// Needed for the curve editor
SerializedProperty m_RawMasterCurve;
SerializedProperty m_RawRedCurve;
SerializedProperty m_RawGreenCurve;
SerializedProperty m_RawBlueCurve;
SerializedProperty m_RawHueVsHueCurve;
SerializedProperty m_RawHueVsSatCurve;
SerializedProperty m_RawSatVsSatCurve;
SerializedProperty m_RawLumVsSatCurve;
CurveEditor m_CurveEditor;
Dictionary<SerializedProperty, Color> m_CurveDict;
// Custom tone curve drawing
const int k_CustomToneCurveResolution = 48;
const float k_CustomToneCurveRangeY = 1.025f;
readonly Vector3[] m_RectVertices = new Vector3[4];
readonly Vector3[] m_LineVertices = new Vector3[2];
readonly Vector3[] m_CurveVertices = new Vector3[k_CustomToneCurveResolution];
Rect m_CustomToneCurveRect;
readonly HableCurve m_HableCurve = new HableCurve();
public override void OnEnable()
{
m_GradingMode = FindParameterOverride(x => x.gradingMode);
m_ExternalLut = FindParameterOverride(x => x.externalLut);
m_Tonemapper = FindParameterOverride(x => x.tonemapper);
m_ToneCurveToeStrength = FindParameterOverride(x => x.toneCurveToeStrength);
m_ToneCurveToeLength = FindParameterOverride(x => x.toneCurveToeLength);
m_ToneCurveShoulderStrength = FindParameterOverride(x => x.toneCurveShoulderStrength);
m_ToneCurveShoulderLength = FindParameterOverride(x => x.toneCurveShoulderLength);
m_ToneCurveShoulderAngle = FindParameterOverride(x => x.toneCurveShoulderAngle);
m_ToneCurveGamma = FindParameterOverride(x => x.toneCurveGamma);
m_LdrLut = FindParameterOverride(x => x.ldrLut);
m_LdrLutContribution = FindParameterOverride(x => x.ldrLutContribution);
m_Temperature = FindParameterOverride(x => x.temperature);
m_Tint = FindParameterOverride(x => x.tint);
m_ColorFilter = FindParameterOverride(x => x.colorFilter);
m_HueShift = FindParameterOverride(x => x.hueShift);
m_Saturation = FindParameterOverride(x => x.saturation);
m_Brightness = FindParameterOverride(x => x.brightness);
m_PostExposure = FindParameterOverride(x => x.postExposure);
m_Contrast = FindParameterOverride(x => x.contrast);
m_MixerRedOutRedIn = FindParameterOverride(x => x.mixerRedOutRedIn);
m_MixerRedOutGreenIn = FindParameterOverride(x => x.mixerRedOutGreenIn);
m_MixerRedOutBlueIn = FindParameterOverride(x => x.mixerRedOutBlueIn);
m_MixerGreenOutRedIn = FindParameterOverride(x => x.mixerGreenOutRedIn);
m_MixerGreenOutGreenIn = FindParameterOverride(x => x.mixerGreenOutGreenIn);
m_MixerGreenOutBlueIn = FindParameterOverride(x => x.mixerGreenOutBlueIn);
m_MixerBlueOutRedIn = FindParameterOverride(x => x.mixerBlueOutRedIn);
m_MixerBlueOutGreenIn = FindParameterOverride(x => x.mixerBlueOutGreenIn);
m_MixerBlueOutBlueIn = FindParameterOverride(x => x.mixerBlueOutBlueIn);
m_Lift = FindParameterOverride(x => x.lift);
m_Gamma = FindParameterOverride(x => x.gamma);
m_Gain = FindParameterOverride(x => x.gain);
m_MasterCurve = FindParameterOverride(x => x.masterCurve);
m_RedCurve = FindParameterOverride(x => x.redCurve);
m_GreenCurve = FindParameterOverride(x => x.greenCurve);
m_BlueCurve = FindParameterOverride(x => x.blueCurve);
m_HueVsHueCurve = FindParameterOverride(x => x.hueVsHueCurve);
m_HueVsSatCurve = FindParameterOverride(x => x.hueVsSatCurve);
m_SatVsSatCurve = FindParameterOverride(x => x.satVsSatCurve);
m_LumVsSatCurve = FindParameterOverride(x => x.lumVsSatCurve);
m_RawMasterCurve = FindProperty(x => x.masterCurve.value.curve);
m_RawRedCurve = FindProperty(x => x.redCurve.value.curve);
m_RawGreenCurve = FindProperty(x => x.greenCurve.value.curve);
m_RawBlueCurve = FindProperty(x => x.blueCurve.value.curve);
m_RawHueVsHueCurve = FindProperty(x => x.hueVsHueCurve.value.curve);
m_RawHueVsSatCurve = FindProperty(x => x.hueVsSatCurve.value.curve);
m_RawSatVsSatCurve = FindProperty(x => x.satVsSatCurve.value.curve);
m_RawLumVsSatCurve = FindProperty(x => x.lumVsSatCurve.value.curve);
m_CurveEditor = new CurveEditor();
m_CurveDict = new Dictionary<SerializedProperty, Color>();
// Prepare the curve editor
SetupCurve(m_RawMasterCurve, new Color(1f, 1f, 1f), 2, false);
SetupCurve(m_RawRedCurve, new Color(1f, 0f, 0f), 2, false);
SetupCurve(m_RawGreenCurve, new Color(0f, 1f, 0f), 2, false);
SetupCurve(m_RawBlueCurve, new Color(0f, 0.5f, 1f), 2, false);
SetupCurve(m_RawHueVsHueCurve, new Color(1f, 1f, 1f), 0, true);
SetupCurve(m_RawHueVsSatCurve, new Color(1f, 1f, 1f), 0, true);
SetupCurve(m_RawSatVsSatCurve, new Color(1f, 1f, 1f), 0, false);
SetupCurve(m_RawLumVsSatCurve, new Color(1f, 1f, 1f), 0, false);
}
public override void OnInspectorGUI()
{
PropertyField(m_GradingMode);
var gradingMode = (GradingMode)m_GradingMode.value.intValue;
// Check if we're in gamma or linear and display a warning if we're trying to do hdr
// color grading while being in gamma mode
if (gradingMode != GradingMode.LowDefinitionRange)
{
if (QualitySettings.activeColorSpace == ColorSpace.Gamma)
EditorGUILayout.HelpBox("ColorSpace in project settings is set to Gamma, HDR color grading won't look correct. Switch to Linear or use LDR color grading mode instead.", MessageType.Warning);
}
if (m_GradingMode.overrideState.boolValue && gradingMode == GradingMode.External)
{
if (!SystemInfo.supports3DRenderTextures || !SystemInfo.supportsComputeShaders)
EditorGUILayout.HelpBox("HDR color grading requires compute shader & 3D render texture support.", MessageType.Warning);
}
if (gradingMode == GradingMode.LowDefinitionRange)
DoStandardModeGUI(false);
else if (gradingMode == GradingMode.HighDefinitionRange)
DoStandardModeGUI(true);
else if (gradingMode == GradingMode.External)
DoExternalModeGUI();
EditorGUILayout.Space();
}
void SetupCurve(SerializedProperty prop, Color color, uint minPointCount, bool loop)
{
var state = CurveEditor.CurveState.defaultState;
state.color = color;
state.visible = false;
state.minPointCount = minPointCount;
state.onlyShowHandlesOnSelection = true;
state.zeroKeyConstantValue = 0.5f;
state.loopInBounds = loop;
m_CurveEditor.Add(prop, state);
m_CurveDict.Add(prop, color);
}
void DoExternalModeGUI()
{
PropertyField(m_ExternalLut);
var lut = m_ExternalLut.value.objectReferenceValue;
if (lut != null)
{
if (lut.GetType() == typeof(Texture3D))
{
var o = (Texture3D)lut;
if (o.width == o.height && o.height == o.depth)
return;
}
else if (lut.GetType() == typeof(RenderTexture))
{
var o = (RenderTexture)lut;
if (o.width == o.height && o.height == o.volumeDepth)
return;
}
EditorGUILayout.HelpBox("Custom LUTs have to be log-encoded 3D textures or 3D render textures with cube format.", MessageType.Warning);
}
}
void DoStandardModeGUI(bool hdr)
{
if (!hdr)
{
PropertyField(m_LdrLut);
PropertyField(m_LdrLutContribution);
var lut = (target as ColorGrading).ldrLut.value;
CheckLutImportSettings(lut);
}
if (hdr)
{
EditorGUILayout.Space();
EditorUtilities.DrawHeaderLabel("Tonemapping");
PropertyField(m_Tonemapper);
if (m_Tonemapper.value.intValue == (int)Tonemapper.Custom)
{
DrawCustomToneCurve();
PropertyField(m_ToneCurveToeStrength);
PropertyField(m_ToneCurveToeLength);
PropertyField(m_ToneCurveShoulderStrength);
PropertyField(m_ToneCurveShoulderLength);
PropertyField(m_ToneCurveShoulderAngle);
PropertyField(m_ToneCurveGamma);
}
}
EditorGUILayout.Space();
EditorUtilities.DrawHeaderLabel("White Balance");
PropertyField(m_Temperature);
PropertyField(m_Tint);
EditorGUILayout.Space();
EditorUtilities.DrawHeaderLabel("Tone");
if (hdr)
PropertyField(m_PostExposure);
PropertyField(m_ColorFilter);
PropertyField(m_HueShift);
PropertyField(m_Saturation);
if (!hdr)
PropertyField(m_Brightness);
PropertyField(m_Contrast);
EditorGUILayout.Space();
int currentChannel = GlobalSettings.currentChannelMixer;
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Channel Mixer", GUIStyle.none, Styling.headerLabel);
EditorGUI.BeginChangeCheck();
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayoutUtility.GetRect(9f, 18f, GUILayout.ExpandWidth(false)); // Dirty hack to do proper right column alignement
if (GUILayout.Toggle(currentChannel == 0, EditorUtilities.GetContent("Red|Red output channel."), EditorStyles.miniButtonLeft)) currentChannel = 0;
if (GUILayout.Toggle(currentChannel == 1, EditorUtilities.GetContent("Green|Green output channel."), EditorStyles.miniButtonMid)) currentChannel = 1;
if (GUILayout.Toggle(currentChannel == 2, EditorUtilities.GetContent("Blue|Blue output channel."), EditorStyles.miniButtonRight)) currentChannel = 2;
}
}
if (EditorGUI.EndChangeCheck())
GUI.FocusControl(null);
}
GlobalSettings.currentChannelMixer = currentChannel;
if (currentChannel == 0)
{
PropertyField(m_MixerRedOutRedIn);
PropertyField(m_MixerRedOutGreenIn);
PropertyField(m_MixerRedOutBlueIn);
}
else if (currentChannel == 1)
{
PropertyField(m_MixerGreenOutRedIn);
PropertyField(m_MixerGreenOutGreenIn);
PropertyField(m_MixerGreenOutBlueIn);
}
else
{
PropertyField(m_MixerBlueOutRedIn);
PropertyField(m_MixerBlueOutGreenIn);
PropertyField(m_MixerBlueOutBlueIn);
}
EditorGUILayout.Space();
EditorUtilities.DrawHeaderLabel("Trackballs");
using (new EditorGUILayout.HorizontalScope())
{
PropertyField(m_Lift);
GUILayout.Space(4f);
PropertyField(m_Gamma);
GUILayout.Space(4f);
PropertyField(m_Gain);
}
EditorGUILayout.Space();
EditorUtilities.DrawHeaderLabel("Grading Curves");
DoCurvesGUI(hdr);
}
void CheckLutImportSettings(Texture lut)
{
if (lut != null)
{
var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(lut)) as TextureImporter;
// Fails when using an internal texture as you can't change import settings on
// builtin resources, thus the check for null
if (importer != null)
{
bool valid = importer.anisoLevel == 0
&& importer.mipmapEnabled == false
&& importer.sRGBTexture == false
&& importer.textureCompression == TextureImporterCompression.Uncompressed
&& importer.wrapMode == TextureWrapMode.Clamp;
if (!valid)
EditorUtilities.DrawFixMeBox("Invalid LUT import settings.", () => SetLutImportSettings(importer));
}
}
}
void SetLutImportSettings(TextureImporter importer)
{
importer.textureType = TextureImporterType.Default;
importer.mipmapEnabled = false;
importer.anisoLevel = 0;
importer.sRGBTexture = false;
importer.npotScale = TextureImporterNPOTScale.None;
importer.textureCompression = TextureImporterCompression.Uncompressed;
importer.alphaSource = TextureImporterAlphaSource.None;
importer.wrapMode = TextureWrapMode.Clamp;
importer.SaveAndReimport();
AssetDatabase.Refresh();
}
void DrawCustomToneCurve()
{
EditorGUILayout.Space();
// Reserve GUI space
using (new GUILayout.HorizontalScope())
{
GUILayout.Space(EditorGUI.indentLevel * 15f);
m_CustomToneCurveRect = GUILayoutUtility.GetRect(128, 80);
}
if (Event.current.type != EventType.Repaint)
return;
// Prepare curve data
float toeStrength = m_ToneCurveToeStrength.value.floatValue;
float toeLength = m_ToneCurveToeLength.value.floatValue;
float shoulderStrength = m_ToneCurveShoulderStrength.value.floatValue;
float shoulderLength = m_ToneCurveShoulderLength.value.floatValue;
float shoulderAngle = m_ToneCurveShoulderAngle.value.floatValue;
float gamma = m_ToneCurveGamma.value.floatValue;
m_HableCurve.Init(
toeStrength,
toeLength,
shoulderStrength,
shoulderLength,
shoulderAngle,
gamma
);
float endPoint = m_HableCurve.whitePoint;
// Background
m_RectVertices[0] = PointInRect(0f, 0f, endPoint);
m_RectVertices[1] = PointInRect(endPoint, 0f, endPoint);
m_RectVertices[2] = PointInRect(endPoint, k_CustomToneCurveRangeY, endPoint);
m_RectVertices[3] = PointInRect(0f, k_CustomToneCurveRangeY, endPoint);
Handles.DrawSolidRectangleWithOutline(m_RectVertices, Color.white * 0.1f, Color.white * 0.4f);
// Vertical guides
if (endPoint < m_CustomToneCurveRect.width / 3)
{
int steps = Mathf.CeilToInt(endPoint);
for (var i = 1; i < steps; i++)
DrawLine(i, 0, i, k_CustomToneCurveRangeY, 0.4f, endPoint);
}
// Label
Handles.Label(m_CustomToneCurveRect.position + Vector2.right, "Custom Tone Curve", EditorStyles.miniLabel);
// Draw the acual curve
var vcount = 0;
while (vcount < k_CustomToneCurveResolution)
{
float x = endPoint * vcount / (k_CustomToneCurveResolution - 1);
float y = m_HableCurve.Eval(x);
if (y < k_CustomToneCurveRangeY)
{
m_CurveVertices[vcount++] = PointInRect(x, y, endPoint);
}
else
{
if (vcount > 1)
{
// Extend the last segment to the top edge of the rect.
var v1 = m_CurveVertices[vcount - 2];
var v2 = m_CurveVertices[vcount - 1];
var clip = (m_CustomToneCurveRect.y - v1.y) / (v2.y - v1.y);
m_CurveVertices[vcount - 1] = v1 + (v2 - v1) * clip;
}
break;
}
}
if (vcount > 1)
{
Handles.color = Color.white * 0.9f;
Handles.DrawAAPolyLine(2f, vcount, m_CurveVertices);
}
}
void DrawLine(float x1, float y1, float x2, float y2, float grayscale, float rangeX)
{
m_LineVertices[0] = PointInRect(x1, y1, rangeX);
m_LineVertices[1] = PointInRect(x2, y2, rangeX);
Handles.color = Color.white * grayscale;
Handles.DrawAAPolyLine(2f, m_LineVertices);
}
Vector3 PointInRect(float x, float y, float rangeX)
{
x = Mathf.Lerp(m_CustomToneCurveRect.x, m_CustomToneCurveRect.xMax, x / rangeX);
y = Mathf.Lerp(m_CustomToneCurveRect.yMax, m_CustomToneCurveRect.y, y / k_CustomToneCurveRangeY);
return new Vector3(x, y, 0);
}
void ResetVisibleCurves()
{
foreach (var curve in m_CurveDict)
{
var state = m_CurveEditor.GetCurveState(curve.Key);
state.visible = false;
m_CurveEditor.SetCurveState(curve.Key, state);
}
}
void SetCurveVisible(SerializedProperty rawProp, SerializedProperty overrideProp)
{
var state = m_CurveEditor.GetCurveState(rawProp);
state.visible = true;
state.editable = overrideProp.boolValue;
m_CurveEditor.SetCurveState(rawProp, state);
}
void CurveOverrideToggle(SerializedProperty overrideProp)
{
overrideProp.boolValue = GUILayout.Toggle(overrideProp.boolValue, EditorUtilities.GetContent("Override"), EditorStyles.toolbarButton);
}
static Material s_MaterialGrid;
void DoCurvesGUI(bool hdr)
{
EditorGUILayout.Space();
ResetVisibleCurves();
using (new EditorGUI.DisabledGroupScope(serializedObject.isEditingMultipleObjects))
{
int curveEditingId = 0;
SerializedProperty currentCurveRawProp = null;
// Top toolbar
using (new GUILayout.HorizontalScope(EditorStyles.toolbar))
{
curveEditingId = DoCurveSelectionPopup(GlobalSettings.currentCurve, hdr);
curveEditingId = Mathf.Clamp(curveEditingId, hdr ? 4 : 0, 7);
EditorGUILayout.Space();
switch (curveEditingId)
{
case 0:
CurveOverrideToggle(m_MasterCurve.overrideState);
SetCurveVisible(m_RawMasterCurve, m_MasterCurve.overrideState);
currentCurveRawProp = m_RawMasterCurve;
break;
case 1:
CurveOverrideToggle(m_RedCurve.overrideState);
SetCurveVisible(m_RawRedCurve, m_RedCurve.overrideState);
currentCurveRawProp = m_RawRedCurve;
break;
case 2:
CurveOverrideToggle(m_GreenCurve.overrideState);
SetCurveVisible(m_RawGreenCurve, m_GreenCurve.overrideState);
currentCurveRawProp = m_RawGreenCurve;
break;
case 3:
CurveOverrideToggle(m_BlueCurve.overrideState);
SetCurveVisible(m_RawBlueCurve, m_BlueCurve.overrideState);
currentCurveRawProp = m_RawBlueCurve;
break;
case 4:
CurveOverrideToggle(m_HueVsHueCurve.overrideState);
SetCurveVisible(m_RawHueVsHueCurve, m_HueVsHueCurve.overrideState);
currentCurveRawProp = m_RawHueVsHueCurve;
break;
case 5:
CurveOverrideToggle(m_HueVsSatCurve.overrideState);
SetCurveVisible(m_RawHueVsSatCurve, m_HueVsSatCurve.overrideState);
currentCurveRawProp = m_RawHueVsSatCurve;
break;
case 6:
CurveOverrideToggle(m_SatVsSatCurve.overrideState);
SetCurveVisible(m_RawSatVsSatCurve, m_SatVsSatCurve.overrideState);
currentCurveRawProp = m_RawSatVsSatCurve;
break;
case 7:
CurveOverrideToggle(m_LumVsSatCurve.overrideState);
SetCurveVisible(m_RawLumVsSatCurve, m_LumVsSatCurve.overrideState);
currentCurveRawProp = m_RawLumVsSatCurve;
break;
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Reset", EditorStyles.toolbarButton))
{
switch (curveEditingId)
{
case 0: m_RawMasterCurve.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
break;
case 1: m_RawRedCurve.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
break;
case 2: m_RawGreenCurve.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
break;
case 3: m_RawBlueCurve.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
break;
case 4: m_RawHueVsHueCurve.animationCurveValue = new AnimationCurve();
break;
case 5: m_RawHueVsSatCurve.animationCurveValue = new AnimationCurve();
break;
case 6: m_RawSatVsSatCurve.animationCurveValue = new AnimationCurve();
break;
case 7: m_RawLumVsSatCurve.animationCurveValue = new AnimationCurve();
break;
}
}
GlobalSettings.currentCurve = curveEditingId;
}
// Curve area
var settings = m_CurveEditor.settings;
var rect = GUILayoutUtility.GetAspectRect(2f);
var innerRect = settings.padding.Remove(rect);
if (Event.current.type == EventType.Repaint)
{
// Background
EditorGUI.DrawRect(rect, new Color(0.15f, 0.15f, 0.15f, 1f));
if (curveEditingId == 4 || curveEditingId == 5)
DrawBackgroundTexture(innerRect, 0);
else if (curveEditingId == 6 || curveEditingId == 7)
DrawBackgroundTexture(innerRect, 1);
// Bounds
Handles.color = Color.white * (GUI.enabled ? 1f : 0.5f);
Handles.DrawSolidRectangleWithOutline(innerRect, Color.clear, new Color(0.8f, 0.8f, 0.8f, 0.5f));
// Grid setup
Handles.color = new Color(1f, 1f, 1f, 0.05f);
int hLines = (int)Mathf.Sqrt(innerRect.width);
int vLines = (int)(hLines / (innerRect.width / innerRect.height));
// Vertical grid
int gridOffset = Mathf.FloorToInt(innerRect.width / hLines);
int gridPadding = ((int)(innerRect.width) % hLines) / 2;
for (int i = 1; i < hLines; i++)
{
var offset = i * Vector2.right * gridOffset;
offset.x += gridPadding;
Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.x, innerRect.yMax - 1) + offset);
}
// Horizontal grid
gridOffset = Mathf.FloorToInt(innerRect.height / vLines);
gridPadding = ((int)(innerRect.height) % vLines) / 2;
for (int i = 1; i < vLines; i++)
{
var offset = i * Vector2.up * gridOffset;
offset.y += gridPadding;
Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.xMax - 1, innerRect.y) + offset);
}
}
// Curve editor
if (m_CurveEditor.OnGUI(rect))
{
Repaint();
GUI.changed = true;
}
if (Event.current.type == EventType.Repaint)
{
// Borders
Handles.color = Color.black;
Handles.DrawLine(new Vector2(rect.x, rect.y - 18f), new Vector2(rect.xMax, rect.y - 18f));
Handles.DrawLine(new Vector2(rect.x, rect.y - 19f), new Vector2(rect.x, rect.yMax));
Handles.DrawLine(new Vector2(rect.x, rect.yMax), new Vector2(rect.xMax, rect.yMax));
Handles.DrawLine(new Vector2(rect.xMax, rect.yMax), new Vector2(rect.xMax, rect.y - 18f));
bool editable = m_CurveEditor.GetCurveState(currentCurveRawProp).editable;
string editableString = editable ? string.Empty : "(Not Overriding)\n";
// Selection info
var selection = m_CurveEditor.GetSelection();
var infoRect = innerRect;
infoRect.x += 5f;
infoRect.width = 100f;
infoRect.height = 30f;
if (selection.curve != null && selection.keyframeIndex > -1)
{
var key = selection.keyframe.Value;
GUI.Label(infoRect, string.Format("{0}\n{1}", key.time.ToString("F3"), key.value.ToString("F3")), Styling.preLabel);
}
else
{
GUI.Label(infoRect, editableString, Styling.preLabel);
}
}
}
}
void DrawBackgroundTexture(Rect rect, int pass)
{
if (s_MaterialGrid == null)
s_MaterialGrid = new Material(Shader.Find("Hidden/PostProcessing/Editor/CurveGrid")) { hideFlags = HideFlags.HideAndDontSave };
float scale = EditorGUIUtility.pixelsPerPoint;
#if UNITY_2018_1_OR_NEWER
const RenderTextureReadWrite kReadWrite = RenderTextureReadWrite.sRGB;
#else
const RenderTextureReadWrite kReadWrite = RenderTextureReadWrite.Linear;
#endif
var oldRt = RenderTexture.active;
var rt = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, kReadWrite);
s_MaterialGrid.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f);
s_MaterialGrid.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint);
Graphics.Blit(null, rt, s_MaterialGrid, pass);
RenderTexture.active = oldRt;
GUI.DrawTexture(rect, rt);
RenderTexture.ReleaseTemporary(rt);
}
int DoCurveSelectionPopup(int id, bool hdr)
{
GUILayout.Label(s_Curves[id], EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f));
var lastRect = GUILayoutUtility.GetLastRect();
var e = Event.current;
if (e.type == EventType.MouseDown && e.button == 0 && lastRect.Contains(e.mousePosition))
{
var menu = new GenericMenu();
for (int i = 0; i < s_Curves.Length; i++)
{
if (i == 4)
menu.AddSeparator("");
if (hdr && i < 4)
menu.AddDisabledItem(s_Curves[i]);
else
{
int current = i; // Capture local for closure
menu.AddItem(s_Curves[i], current == id, () => GlobalSettings.currentCurve = current);
}
}
menu.DropDown(new Rect(lastRect.xMin, lastRect.yMax, 1f, 1f));
}
return id;
}
}
}
| |
using Bridge.Html5;
using Bridge.Test.NUnit;
using System;
namespace Bridge.ClientTest
{
[Category(Constants.MODULE_SCRIPT)]
[TestFixture]
public class ScriptTests
{
public class TestType
{
public TestType()
{
i = 42;
P = 42;
}
public int i;
public int P
{
get;
set;
}
public int P2
{
get
{
return 0;
}
}
public int P3
{
set
{
}
}
public event EventHandler Evt;
public void Raise()
{
if (Evt != null)
Evt(this, null);
}
public void InstanceMethod()
{
}
public static void StaticMethod()
{
}
public int F1()
{
return 42;
}
public int F2(int i)
{
return i + 10;
}
public int F3(int i, int j)
{
return i + j;
}
}
// #SPI
[Test]
public void BooleanWorks_SPI_1619()
{
// #1619
Assert.AreStrictEqual(Script.Boolean(0), false);
Assert.AreStrictEqual(Script.Boolean(""), false);
Assert.AreStrictEqual(Script.Boolean("1"), true);
}
[Test]
public void EvalWorks()
{
Assert.AreEqual(5, Script.Eval<object>("2 + 3"));
}
private static object Undefined
{
[Template("undefined")]
get
{
return null;
}
}
// #SPI
[Test]
public void IsNullWorks_SPI_1618()
{
// #1618
Assert.True(Script.IsNull(null));
Assert.False(Script.IsNull(Undefined));
Assert.False(Script.IsNull(3));
}
// #SPI
[Test]
public void IsUndefinedWorks_SPI_1616()
{
// #1616
Assert.False(Script.IsUndefined(null));
Assert.True(Script.IsUndefined(Undefined));
Assert.False(Script.IsUndefined(3));
}
// #SPI
[Test]
public void HasValueWorks_SPI_1617()
{
// 1617
Assert.False(Script.HasValue(null));
Assert.False(Script.HasValue(Undefined));
Assert.True(Script.HasValue(3));
}
// #SPI
//[Test]
//public void UndefinedWorks()
//{
// Assert.True(Script.IsUndefined(Script.Undefined));
//}
[Test]
public void TypeOfWorks()
{
Assert.AreEqual("undefined", Script.TypeOf(Script.Undefined), "#1");
Assert.AreEqual("object", Script.TypeOf(null), "#2");
Assert.AreEqual("boolean", Script.TypeOf(true), "#3");
Assert.AreEqual("number", Script.TypeOf(0), "#4");
Assert.AreEqual("number", Script.TypeOf(double.MaxValue), "#5");
Assert.AreEqual("string", Script.TypeOf("X"), "#6");
// #1620
Assert.AreEqual("function", Script.TypeOf(new Function("", "")), "#7");
Assert.AreEqual("object", Script.TypeOf(new
{
}), "#8");
}
[Test(ExpectedCount = 9)]
public void DeleteWorksForJsClass_SPI_1571()
{
// #1571
dynamic c = new object();
c.i = 42;
Assert.AreEqual(42, c.i);
var r = Script.Delete(c, "i");
Assert.True(r);
Assert.Null(c.i);
Assert.AreEqual("undefined", Script.TypeOf(c.i));
dynamic c2 = new object();
c2.i = 43;
Assert.AreEqual(43, c2.i);
Func<string> f = () => { return "i"; };
var r2 = Script.Delete(c2, "i");
Assert.True(r2);
Assert.Null(c2.i);
Assert.AreEqual("undefined", Script.TypeOf(c2.i));
Assert.Throws(() =>
{
dynamic o = Script.Get("Object");
Script.Delete(o.prototype); // throws a TypeError in strict mode
});
// The test cannot be run in strict mode due to
// 'SyntaxError: Delete of an unqualified identifier in strict mode.'
//r = Script.Delete(c2);
//Assert.True(r);
//Assert.Null(c2);
//Assert.AreEqual("undefined", Script.TypeOf(c2));
}
[Test(ExpectedCount = 9)]
public void DeleteWorksForClassPrototype_SPI_1571()
{
// #1571
TestType c = new TestType();
Assert.AreEqual(42, c.i);
var r = Script.Delete(c, "i");
Assert.True(r);
Assert.AreEqual(0, c.i);
Assert.AreEqual("number", Script.TypeOf(c.i));
TestType c2 = new TestType() { i = 43 };
Assert.AreEqual(43, c2.i);
Func<string> f = () => { return "i"; };
var r2 = Script.Delete(c2, "i");
Assert.True(r2);
Assert.AreEqual(0, c2.i);
Assert.AreEqual("number", Script.TypeOf(c2.i));
Assert.Throws(() =>
{
dynamic o = Script.Get("Object");
Script.Delete(o.prototype); // throws a TypeError in strict mode
});
// The test cannot be run in strict mode due to
// 'SyntaxError: Delete of an unqualified identifier in strict mode.'
//r = Script.Delete(c2);
//Assert.True(r);
//Assert.Null(c2);
//Assert.AreEqual("undefined", Script.TypeOf(c2));
}
// #SPI
[Test]
public void InWorks_SPI_1573()
{
// #1573
var c = new TestType();
Assert.True(Script.In(c, "i"));
Assert.False(Script.In(c, "x"));
Assert.True(Script.In(c, "P"));
}
// #SPI
[Test]
public void InvokeMethodWorks_SPI_1572()
{
var c = new TestType();
Assert.AreEqual(Script.InvokeMethod(c, "F1"), 42);
Assert.AreEqual(Script.InvokeMethod(c, "F2", 17), 27);
Assert.AreEqual(Script.InvokeMethod(c, "F3", 19, 2), 21);
}
[Test]
public void ParseIntWithoutRadixWorks()
{
Assert.AreEqual(234, Script.ParseInt("234"));
}
[Test]
public void ParseIntWithRadixWorks()
{
Assert.AreEqual(0x234, Script.ParseInt("234", 16));
}
}
}
| |
namespace Multiformats.Hash
{
public enum HashType : uint
{
ID = 0x00,
MD4 = 0xd4,
MD5 = 0xd5,
SHA1 = 0x11,
SHA2_256 = 0x12,
SHA2_512 = 0x13,
SHA3_512 = 0x14,
SHA3_384 = 0x15,
SHA3_256 = 0x16,
SHA3_224 = 0x17,
SHAKE_128 = 0x18,
SHAKE_256 = 0x19,
KECCAK_224 = 0x1A,
KECCAK_256 = 0x1B,
KECCAK_384 = 0x1C,
KECCAK_512 = 0x1D,
MURMUR3_128 = 0x23,
MURMUR3_32 = 0x22,
BLAKE2B_8 = 0xb201,
BLAKE2B_16 = 0xb202,
BLAKE2B_24 = 0xb203,
BLAKE2B_32 = 0xb204,
BLAKE2B_40 = 0xb205,
BLAKE2B_48 = 0xb206,
BLAKE2B_56 = 0xb207,
BLAKE2B_64 = 0xb208,
BLAKE2B_72 = 0xb209,
BLAKE2B_80 = 0xb20a,
BLAKE2B_88 = 0xb20b,
BLAKE2B_96 = 0xb20c,
BLAKE2B_104 = 0xb20d,
BLAKE2B_112 = 0xb20e,
BLAKE2B_120 = 0xb20f,
BLAKE2B_128 = 0xb210,
BLAKE2B_136 = 0xb211,
BLAKE2B_144 = 0xb212,
BLAKE2B_152 = 0xb213,
BLAKE2B_160 = 0xb214,
BLAKE2B_168 = 0xb215,
BLAKE2B_176 = 0xb216,
BLAKE2B_184 = 0xb217,
BLAKE2B_192 = 0xb218,
BLAKE2B_200 = 0xb219,
BLAKE2B_208 = 0xb21a,
BLAKE2B_216 = 0xb21b,
BLAKE2B_224 = 0xb21c,
BLAKE2B_232 = 0xb21d,
BLAKE2B_240 = 0xb21e,
BLAKE2B_248 = 0xb21f,
BLAKE2B_256 = 0xb220,
BLAKE2B_264 = 0xb221,
BLAKE2B_272 = 0xb222,
BLAKE2B_280 = 0xb223,
BLAKE2B_288 = 0xb224,
BLAKE2B_296 = 0xb225,
BLAKE2B_304 = 0xb226,
BLAKE2B_312 = 0xb227,
BLAKE2B_320 = 0xb228,
BLAKE2B_328 = 0xb229,
BLAKE2B_336 = 0xb22a,
BLAKE2B_344 = 0xb22b,
BLAKE2B_352 = 0xb22c,
BLAKE2B_360 = 0xb22d,
BLAKE2B_368 = 0xb22e,
BLAKE2B_376 = 0xb22f,
BLAKE2B_384 = 0xb230,
BLAKE2B_392 = 0xb231,
BLAKE2B_400 = 0xb232,
BLAKE2B_408 = 0xb233,
BLAKE2B_416 = 0xb234,
BLAKE2B_424 = 0xb235,
BLAKE2B_432 = 0xb236,
BLAKE2B_440 = 0xb237,
BLAKE2B_448 = 0xb238,
BLAKE2B_456 = 0xb239,
BLAKE2B_464 = 0xb23a,
BLAKE2B_472 = 0xb23b,
BLAKE2B_480 = 0xb23c,
BLAKE2B_488 = 0xb23d,
BLAKE2B_496 = 0xb23e,
BLAKE2B_504 = 0xb23f,
BLAKE2B_512 = 0xb240,
BLAKE2S_8 = 0xb241,
BLAKE2S_16 = 0xb242,
BLAKE2S_24 = 0xb243,
BLAKE2S_32 = 0xb244,
BLAKE2S_40 = 0xb245,
BLAKE2S_48 = 0xb246,
BLAKE2S_56 = 0xb247,
BLAKE2S_64 = 0xb248,
BLAKE2S_72 = 0xb249,
BLAKE2S_80 = 0xb24a,
BLAKE2S_88 = 0xb24b,
BLAKE2S_96 = 0xb24c,
BLAKE2S_104 = 0xb24d,
BLAKE2S_112 = 0xb24e,
BLAKE2S_120 = 0xb24f,
BLAKE2S_128 = 0xb250,
BLAKE2S_136 = 0xb251,
BLAKE2S_144 = 0xb252,
BLAKE2S_152 = 0xb253,
BLAKE2S_160 = 0xb254,
BLAKE2S_168 = 0xb255,
BLAKE2S_176 = 0xb256,
BLAKE2S_184 = 0xb257,
BLAKE2S_192 = 0xb258,
BLAKE2S_200 = 0xb259,
BLAKE2S_208 = 0xb25a,
BLAKE2S_216 = 0xb25b,
BLAKE2S_224 = 0xb25c,
BLAKE2S_232 = 0xb25d,
BLAKE2S_240 = 0xb25e,
BLAKE2S_248 = 0xb25f,
BLAKE2S_256 = 0xb260,
SKEIN256_8 = 0xb301,
SKEIN256_16 = 0xb302,
SKEIN256_24 = 0xb303,
SKEIN256_32 = 0xb304,
SKEIN256_40 = 0xb305,
SKEIN256_48 = 0xb306,
SKEIN256_56 = 0xb307,
SKEIN256_64 = 0xb308,
SKEIN256_72 = 0xb309,
SKEIN256_80 = 0xb30a,
SKEIN256_88 = 0xb30b,
SKEIN256_96 = 0xb30c,
SKEIN256_104 = 0xb30d,
SKEIN256_112 = 0xb30e,
SKEIN256_120 = 0xb30f,
SKEIN256_128 = 0xb310,
SKEIN256_136 = 0xb311,
SKEIN256_144 = 0xb312,
SKEIN256_152 = 0xb313,
SKEIN256_160 = 0xb314,
SKEIN256_168 = 0xb315,
SKEIN256_176 = 0xb316,
SKEIN256_184 = 0xb317,
SKEIN256_192 = 0xb318,
SKEIN256_200 = 0xb319,
SKEIN256_208 = 0xb31a,
SKEIN256_216 = 0xb31b,
SKEIN256_224 = 0xb31c,
SKEIN256_232 = 0xb31d,
SKEIN256_240 = 0xb31e,
SKEIN256_248 = 0xb31f,
SKEIN256_256 = 0xb320,
SKEIN512_8 = 0xb321,
SKEIN512_16 = 0xb322,
SKEIN512_24 = 0xb323,
SKEIN512_32 = 0xb324,
SKEIN512_40 = 0xb325,
SKEIN512_48 = 0xb326,
SKEIN512_56 = 0xb327,
SKEIN512_64 = 0xb328,
SKEIN512_72 = 0xb329,
SKEIN512_80 = 0xb32a,
SKEIN512_88 = 0xb32b,
SKEIN512_96 = 0xb32c,
SKEIN512_104 = 0xb32d,
SKEIN512_112 = 0xb32e,
SKEIN512_120 = 0xb32f,
SKEIN512_128 = 0xb330,
SKEIN512_136 = 0xb331,
SKEIN512_144 = 0xb332,
SKEIN512_152 = 0xb333,
SKEIN512_160 = 0xb334,
SKEIN512_168 = 0xb335,
SKEIN512_176 = 0xb336,
SKEIN512_184 = 0xb337,
SKEIN512_192 = 0xb338,
SKEIN512_200 = 0xb339,
SKEIN512_208 = 0xb33a,
SKEIN512_216 = 0xb33b,
SKEIN512_224 = 0xb33c,
SKEIN512_232 = 0xb33d,
SKEIN512_240 = 0xb33e,
SKEIN512_248 = 0xb33f,
SKEIN512_256 = 0xb340,
SKEIN512_264 = 0xb341,
SKEIN512_272 = 0xb342,
SKEIN512_280 = 0xb343,
SKEIN512_288 = 0xb344,
SKEIN512_296 = 0xb345,
SKEIN512_304 = 0xb346,
SKEIN512_312 = 0xb347,
SKEIN512_320 = 0xb348,
SKEIN512_328 = 0xb349,
SKEIN512_336 = 0xb34a,
SKEIN512_344 = 0xb34b,
SKEIN512_352 = 0xb34c,
SKEIN512_360 = 0xb34d,
SKEIN512_368 = 0xb34e,
SKEIN512_376 = 0xb34f,
SKEIN512_384 = 0xb350,
SKEIN512_392 = 0xb351,
SKEIN512_400 = 0xb352,
SKEIN512_408 = 0xb353,
SKEIN512_416 = 0xb354,
SKEIN512_424 = 0xb355,
SKEIN512_432 = 0xb356,
SKEIN512_440 = 0xb357,
SKEIN512_448 = 0xb358,
SKEIN512_456 = 0xb359,
SKEIN512_464 = 0xb35a,
SKEIN512_472 = 0xb35b,
SKEIN512_480 = 0xb35c,
SKEIN512_488 = 0xb35d,
SKEIN512_496 = 0xb35e,
SKEIN512_504 = 0xb35f,
SKEIN512_512 = 0xb360,
SKEIN1024_8 = 0xb361,
SKEIN1024_16 = 0xb362,
SKEIN1024_24 = 0xb363,
SKEIN1024_32 = 0xb364,
SKEIN1024_40 = 0xb365,
SKEIN1024_48 = 0xb366,
SKEIN1024_56 = 0xb367,
SKEIN1024_64 = 0xb368,
SKEIN1024_72 = 0xb369,
SKEIN1024_80 = 0xb36a,
SKEIN1024_88 = 0xb36b,
SKEIN1024_96 = 0xb36c,
SKEIN1024_104 = 0xb36d,
SKEIN1024_112 = 0xb36e,
SKEIN1024_120 = 0xb36f,
SKEIN1024_128 = 0xb370,
SKEIN1024_136 = 0xb371,
SKEIN1024_144 = 0xb372,
SKEIN1024_152 = 0xb373,
SKEIN1024_160 = 0xb374,
SKEIN1024_168 = 0xb375,
SKEIN1024_176 = 0xb376,
SKEIN1024_184 = 0xb377,
SKEIN1024_192 = 0xb378,
SKEIN1024_200 = 0xb379,
SKEIN1024_208 = 0xb37a,
SKEIN1024_216 = 0xb37b,
SKEIN1024_224 = 0xb37c,
SKEIN1024_232 = 0xb37d,
SKEIN1024_240 = 0xb37e,
SKEIN1024_248 = 0xb37f,
SKEIN1024_256 = 0xb380,
SKEIN1024_264 = 0xb381,
SKEIN1024_272 = 0xb382,
SKEIN1024_280 = 0xb383,
SKEIN1024_288 = 0xb384,
SKEIN1024_296 = 0xb385,
SKEIN1024_304 = 0xb386,
SKEIN1024_312 = 0xb387,
SKEIN1024_320 = 0xb388,
SKEIN1024_328 = 0xb389,
SKEIN1024_336 = 0xb38a,
SKEIN1024_344 = 0xb38b,
SKEIN1024_352 = 0xb38c,
SKEIN1024_360 = 0xb38d,
SKEIN1024_368 = 0xb38e,
SKEIN1024_376 = 0xb38f,
SKEIN1024_384 = 0xb390,
SKEIN1024_392 = 0xb391,
SKEIN1024_400 = 0xb392,
SKEIN1024_408 = 0xb393,
SKEIN1024_416 = 0xb394,
SKEIN1024_424 = 0xb395,
SKEIN1024_432 = 0xb396,
SKEIN1024_440 = 0xb397,
SKEIN1024_448 = 0xb398,
SKEIN1024_456 = 0xb399,
SKEIN1024_464 = 0xb39a,
SKEIN1024_472 = 0xb39b,
SKEIN1024_480 = 0xb39c,
SKEIN1024_488 = 0xb39d,
SKEIN1024_496 = 0xb39e,
SKEIN1024_504 = 0xb39f,
SKEIN1024_512 = 0xb3a0,
SKEIN1024_520 = 0xb3a1,
SKEIN1024_528 = 0xb3a2,
SKEIN1024_536 = 0xb3a3,
SKEIN1024_544 = 0xb3a4,
SKEIN1024_552 = 0xb3a5,
SKEIN1024_560 = 0xb3a6,
SKEIN1024_568 = 0xb3a7,
SKEIN1024_576 = 0xb3a8,
SKEIN1024_584 = 0xb3a9,
SKEIN1024_592 = 0xb3aa,
SKEIN1024_600 = 0xb3ab,
SKEIN1024_608 = 0xb3ac,
SKEIN1024_616 = 0xb3ad,
SKEIN1024_624 = 0xb3ae,
SKEIN1024_632 = 0xb3af,
SKEIN1024_640 = 0xb3b0,
SKEIN1024_648 = 0xb3b1,
SKEIN1024_656 = 0xb3b2,
SKEIN1024_664 = 0xb3b3,
SKEIN1024_672 = 0xb3b4,
SKEIN1024_680 = 0xb3b5,
SKEIN1024_688 = 0xb3b6,
SKEIN1024_696 = 0xb3b7,
SKEIN1024_704 = 0xb3b8,
SKEIN1024_712 = 0xb3b9,
SKEIN1024_720 = 0xb3ba,
SKEIN1024_728 = 0xb3bb,
SKEIN1024_736 = 0xb3bc,
SKEIN1024_744 = 0xb3bd,
SKEIN1024_752 = 0xb3be,
SKEIN1024_760 = 0xb3bf,
SKEIN1024_768 = 0xb3c0,
SKEIN1024_776 = 0xb3c1,
SKEIN1024_784 = 0xb3c2,
SKEIN1024_792 = 0xb3c3,
SKEIN1024_800 = 0xb3c4,
SKEIN1024_808 = 0xb3c5,
SKEIN1024_816 = 0xb3c6,
SKEIN1024_824 = 0xb3c7,
SKEIN1024_832 = 0xb3c8,
SKEIN1024_840 = 0xb3c9,
SKEIN1024_848 = 0xb3ca,
SKEIN1024_856 = 0xb3cb,
SKEIN1024_864 = 0xb3cc,
SKEIN1024_872 = 0xb3cd,
SKEIN1024_880 = 0xb3ce,
SKEIN1024_888 = 0xb3cf,
SKEIN1024_896 = 0xb3d0,
SKEIN1024_904 = 0xb3d1,
SKEIN1024_912 = 0xb3d2,
SKEIN1024_920 = 0xb3d3,
SKEIN1024_928 = 0xb3d4,
SKEIN1024_936 = 0xb3d5,
SKEIN1024_944 = 0xb3d6,
SKEIN1024_952 = 0xb3d7,
SKEIN1024_960 = 0xb3d8,
SKEIN1024_968 = 0xb3d9,
SKEIN1024_976 = 0xb3da,
SKEIN1024_984 = 0xb3db,
SKEIN1024_992 = 0xb3dc,
SKEIN1024_1000 = 0xb3dd,
SKEIN1024_1008 = 0xb3de,
SKEIN1024_1016 = 0xb3df,
SKEIN1024_1024 = 0xb3e0,
DBL_SHA2_256 = 0x56
}
}
| |
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Reflection;
using Microsoft.XmlDiffPatch;
namespace Microsoft.XmlDiffPatch
{
class TestXmlDiff
{
static void Main( string[] args )
{
bool bFragment = false;
bool bNodes = false;
XmlDiffAlgorithm algorithm = XmlDiffAlgorithm.Auto;
try
{
if ( args.Length < 3 )
{
WriteUsage();
return;
}
XmlDiffOptions options = XmlDiffOptions.None;
// process options
int curArgsIndex = 0;
string optionsString = string.Empty;
while ( args[curArgsIndex][0] == '/' )
{
if ( args[curArgsIndex].Length != 2 )
{
System.Console.Write( "Invalid option: " + args[curArgsIndex] + "\n" );
return;
}
switch ( args[curArgsIndex][1] )
{
case 'o':
options |= XmlDiffOptions.IgnoreChildOrder;
break;
case 'c':
options |= XmlDiffOptions.IgnoreComments;
break;
case 'p':
options |= XmlDiffOptions.IgnorePI;
break;
case 'w':
options |= XmlDiffOptions.IgnoreWhitespace;
break;
case 'n':
options |= XmlDiffOptions.IgnoreNamespaces;
break;
case 'r':
options |= XmlDiffOptions.IgnorePrefixes;
break;
case 'x':
options |= XmlDiffOptions.IgnoreXmlDecl;
break;
case 'd':
options |= XmlDiffOptions.IgnoreDtd;
break;
case 'e':
bNodes = true;
break;
case 'f':
bFragment = true;
break;
case 't':
algorithm = XmlDiffAlgorithm.Fast;
break;
case 'z':
algorithm = XmlDiffAlgorithm.Precise;
break;
default:
System.Console.Write( "Invalid option: " + args[curArgsIndex] + "\n" );
return;
}
optionsString += args[curArgsIndex][1];
curArgsIndex++;
if ( args.Length - curArgsIndex < 3 )
{
WriteUsage();
return;
}
}
// extract names from command line
string sourceXml = args[ curArgsIndex ];
string targetXml = args[ curArgsIndex + 1 ];
string diffgram = args[ curArgsIndex + 2 ];
bool bVerify = ( args.Length - curArgsIndex == 4 ) && ( args[ curArgsIndex + 3 ] == "verify" );
// write legend
string legend = sourceXml.Substring( sourceXml.LastIndexOf("\\") + 1 ) + " & " +
targetXml.Substring( targetXml.LastIndexOf("\\") + 1 ) + " -> " +
diffgram.Substring( diffgram.LastIndexOf("\\") + 1 );
if ( optionsString != string.Empty )
legend += " (" + optionsString + ")";
if ( legend.Length < 60 )
legend += new String( ' ', 60 - legend.Length );
else
legend += "\n" + new String( ' ', 60 );
System.Console.Write( legend );
// create diffgram writer
XmlWriter DiffgramWriter = new XmlTextWriter( diffgram, new System.Text.UnicodeEncoding() );
// create XmlDiff object & set the options
XmlDiff xmlDiff = new XmlDiff( options );
xmlDiff.Algorithm = algorithm;
// compare xml files
bool bIdentical;
if ( bNodes ) {
if ( bFragment ) {
Console.Write( "Cannot have option 'd' and 'f' together." );
return;
}
XmlDocument sourceDoc = new XmlDocument();
sourceDoc.Load( sourceXml );
XmlDocument targetDoc = new XmlDocument();
targetDoc.Load( targetXml );
bIdentical = xmlDiff.Compare( sourceDoc, targetDoc, DiffgramWriter );
}
else {
bIdentical = xmlDiff.Compare( sourceXml, targetXml, bFragment, DiffgramWriter );
}
/*
* if ( bMeasurePerf ) {
Type type = xmlDiff.GetType();
MemberInfo[] mi = type.GetMember( "_xmlDiffPerf" );
if ( mi != null && mi.Length > 0 ) {
XmlDiffPerf xmldiffPerf = (XmlDiffPerf)type.InvokeMember( "_xmlDiffPerf", BindingFlags.GetField, null, xmlDiff, new object[0]);
}
}
*/
// write result
if ( bIdentical )
System.Console.Write( "identical" );
else
System.Console.Write( "different" );
DiffgramWriter.Close();
// verify
if ( !bIdentical && bVerify )
{
XmlNode sourceNode;
if ( bFragment )
{
NameTable nt = new NameTable();
XmlTextReader tr = new XmlTextReader( new FileStream( sourceXml, FileMode.Open, FileAccess.Read ),
XmlNodeType.Element,
new XmlParserContext( nt, new XmlNamespaceManager( nt ),
string.Empty, XmlSpace.Default ) );
XmlDocument doc = new XmlDocument();
XmlDocumentFragment frag = doc.CreateDocumentFragment();
XmlNode node;
while ( ( node = doc.ReadNode( tr ) ) != null ) {
if ( node.NodeType != XmlNodeType.Whitespace )
frag.AppendChild( node );
}
sourceNode = frag;
}
else
{
// load source document
XmlDocument sourceDoc = new XmlDocument();
sourceDoc.XmlResolver = null;
sourceDoc.Load( sourceXml );
sourceNode = sourceDoc;
}
// patch it & save
new XmlPatch().Patch( ref sourceNode, new XmlTextReader( diffgram ) );
if ( sourceNode.NodeType == XmlNodeType.Document )
((XmlDocument)sourceNode).Save( "_patched.xml" );
else {
XmlTextWriter tw = new XmlTextWriter( "_patched.xml", Encoding.Unicode );
sourceNode.WriteTo( tw );
tw.Close();
}
XmlWriter diffgramWriter2 = new XmlTextWriter( "_2ndDiff.xml", new System.Text.UnicodeEncoding() );
// compare patched source document and target document
if ( xmlDiff.Compare( "_patched.xml", targetXml, bFragment, diffgramWriter2 ) )
System.Console.Write( " - ok" );
else
System.Console.Write( " - FAILED" );
diffgramWriter2.Close();
}
System.Console.Write( "\n" );
}
catch ( Exception e )
{
Console.Write("\n*** Error: " + e.Message + " (source: " + e.Source + ")\n");
}
if ( System.Diagnostics.Debugger.IsAttached )
{
Console.Write( "\nPress enter...\n" );
Console.Read();
}
}
static private void WriteUsage()
{
System.Console.Write( "TestXmlDiff - test application for XmlDiff\n" );
System.Console.Write( "USAGE: testapp [options] <source xml> <target xml> <diffgram> [verify]\n\n" +
"Options:\n" +
"/o ignore child order\n" +
"/c ignore comments\n" +
"/p ignore processing instructions\n" +
"/w ignore whitespaces, normalize text value\n" +
"/n ignore namespaces\n" +
"/r ignore prefixes\n" +
"/x ignore XML declaration\n" );
}
}
}
| |
//
// DiffieHellmanManaged.cs: Implements the Diffie-Hellman key agreement algorithm
//
// Author:
// Pieter Philippaerts (Pieter@mentalis.org)
//
// (C) 2003 The Mentalis.org Team (http://www.mentalis.org/)
//
// References:
// - PKCS#3 [http://www.rsasecurity.com/rsalabs/pkcs/pkcs-3/]
//
//
// 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.Security.Cryptography;
using Mono.Math;
namespace Mono.Security.Cryptography {
/// <summary>
/// Implements the Diffie-Hellman algorithm.
/// </summary>
public sealed class DiffieHellmanManaged : DiffieHellman {
/// <summary>
/// Initializes a new <see cref="DiffieHellmanManaged"/> instance.
/// </summary>
/// <remarks>The default length of the shared secret is 1024 bits.</remarks>
public DiffieHellmanManaged() : this(1024, 160, DHKeyGeneration.Static) {}
/// <summary>
/// Initializes a new <see cref="DiffieHellmanManaged"/> instance.
/// </summary>
/// <param name="bitLength">The length, in bits, of the public P parameter.</param>
/// <param name="l">The length, in bits, of the secret value X. This parameter can be set to 0 to use the default size.</param>
/// <param name="method">One of the <see cref="DHKeyGeneration"/> values.</param>
/// <remarks>The larger the bit length, the more secure the algorithm is. The default is 1024 bits. The minimum bit length is 128 bits.<br/>The size of the private value will be one fourth of the bit length specified.</remarks>
/// <exception cref="ArgumentException">The specified bit length is invalid.</exception>
public DiffieHellmanManaged(int bitLength, int l, DHKeyGeneration method) {
if (bitLength < 256 || l < 0)
throw new ArgumentException();
BigInteger p, g;
GenerateKey (bitLength, method, out p, out g);
Initialize(p, g, null, l, false);
}
/// <summary>
/// Initializes a new <see cref="DiffieHellmanManaged"/> instance.
/// </summary>
/// <param name="p">The P parameter of the Diffie-Hellman algorithm. This is a public parameter.</param>
/// <param name="g">The G parameter of the Diffie-Hellman algorithm. This is a public parameter.</param>
/// <param name="x">The X parameter of the Diffie-Hellman algorithm. This is a private parameter. If this parameters is a null reference (<b>Nothing</b> in Visual Basic), a secret value of the default size will be generated.</param>
/// <exception cref="ArgumentNullException"><paramref name="p"/> or <paramref name="g"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
/// <exception cref="CryptographicException"><paramref name="p"/> or <paramref name="g"/> is invalid.</exception>
public DiffieHellmanManaged(byte[] p, byte[] g, byte[] x) {
if (p == null || g == null)
throw new ArgumentNullException();
if (x == null)
Initialize(new BigInteger(p), new BigInteger(g), null, 0, true);
else
Initialize(new BigInteger(p), new BigInteger(g), new BigInteger(x), 0, true);
}
/// <summary>
/// Initializes a new <see cref="DiffieHellmanManaged"/> instance.
/// </summary>
/// <param name="p">The P parameter of the Diffie-Hellman algorithm.</param>
/// <param name="g">The G parameter of the Diffie-Hellman algorithm.</param>
/// <param name="l">The length, in bits, of the private value. If 0 is specified, the default value will be used.</param>
/// <exception cref="ArgumentNullException"><paramref name="p"/> or <paramref name="g"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
/// <exception cref="ArgumentException"><paramref name="l"/> is invalid.</exception>
/// <exception cref="CryptographicException"><paramref name="p"/> or <paramref name="g"/> is invalid.</exception>
public DiffieHellmanManaged(byte[] p, byte[] g, int l) {
if (p == null || g == null)
throw new ArgumentNullException();
if (l < 0)
throw new ArgumentException();
Initialize(new BigInteger(p), new BigInteger(g), null, l, true);
}
// initializes the private variables (throws CryptographicException)
private void Initialize(BigInteger p, BigInteger g, BigInteger x, int secretLen, bool checkInput) {
if (checkInput) {
if (!p.IsProbablePrime() || g <= 0 || g >= p || (x != null && (x <= 0 || x > p - 2)))
throw new CryptographicException();
}
// default is to generate a number as large as the prime this
// is usually overkill, but it's the most secure thing we can
// do if the user doesn't specify a desired secret length ...
if (secretLen == 0)
secretLen = p.BitCount();
m_P = p;
m_G = g;
if (x == null) {
BigInteger pm1 = m_P - 1;
for(m_X = BigInteger.GenerateRandom(secretLen); m_X >= pm1 || m_X == 0; m_X = BigInteger.GenerateRandom(secretLen)) {}
} else {
m_X = x;
}
}
/// <summary>
/// Creates the key exchange data.
/// </summary>
/// <returns>The key exchange data to be sent to the intended recipient.</returns>
public override byte[] CreateKeyExchange() {
BigInteger y = m_G.ModPow(m_X, m_P);
byte[] ret = y.GetBytes();
y.Clear();
return ret;
}
/// <summary>
/// Extracts secret information from the key exchange data.
/// </summary>
/// <param name="keyEx">The key exchange data within which the shared key is hidden.</param>
/// <returns>The shared key derived from the key exchange data.</returns>
public override byte[] DecryptKeyExchange(byte[] keyEx) {
BigInteger pvr = new BigInteger(keyEx);
BigInteger z = pvr.ModPow(m_X, m_P);
byte[] ret = z.GetBytes();
z.Clear();
return ret;
}
/// <summary>
/// Gets the name of the key exchange algorithm.
/// </summary>
/// <value>The name of the key exchange algorithm.</value>
public override string KeyExchangeAlgorithm {
get {
return "1.2.840.113549.1.3"; // PKCS#3 OID
}
}
/// <summary>
/// Gets the name of the signature algorithm.
/// </summary>
/// <value>The name of the signature algorithm.</value>
public override string SignatureAlgorithm {
get {
return null;
}
}
// clear keys
protected override void Dispose(bool disposing) {
if (!m_Disposed) {
m_P.Clear();
m_G.Clear();
m_X.Clear();
}
m_Disposed = true;
}
/// <summary>
/// Exports the <see cref="DHParameters"/>.
/// </summary>
/// <param name="includePrivateParameters"><b>true</b> to include private parameters; otherwise, <b>false</b>.</param>
/// <returns>The parameters for <see cref="DiffieHellman"/>.</returns>
public override DHParameters ExportParameters(bool includePrivateParameters) {
DHParameters ret = new DHParameters();
ret.P = m_P.GetBytes();
ret.G = m_G.GetBytes();
if (includePrivateParameters) {
ret.X = m_X.GetBytes();
}
return ret;
}
/// <summary>
/// Imports the specified <see cref="DHParameters"/>.
/// </summary>
/// <param name="parameters">The parameters for <see cref="DiffieHellman"/>.</param>
/// <exception cref="CryptographicException"><paramref name="P"/> or <paramref name="G"/> is a null reference (<b>Nothing</b> in Visual Basic) -or- <paramref name="P"/> is not a prime number.</exception>
public override void ImportParameters(DHParameters parameters) {
if (parameters.P == null)
throw new CryptographicException("Missing P value.");
if (parameters.G == null)
throw new CryptographicException("Missing G value.");
BigInteger p = new BigInteger(parameters.P), g = new BigInteger(parameters.G), x = null;
if (parameters.X != null) {
x = new BigInteger(parameters.X);
}
Initialize(p, g, x, 0, true);
}
~DiffieHellmanManaged() {
Dispose(false);
}
//TODO: implement DH key generation methods
private void GenerateKey(int bitlen, DHKeyGeneration keygen, out BigInteger p, out BigInteger g) {
if (keygen == DHKeyGeneration.Static) {
if (bitlen == 768)
p = new BigInteger(m_OAKLEY768);
else if (bitlen == 1024)
p = new BigInteger(m_OAKLEY1024);
else if (bitlen == 1536)
p = new BigInteger(m_OAKLEY1536);
else
throw new ArgumentException("Invalid bit size.");
g = new BigInteger(22); // all OAKLEY keys use 22 as generator
//} else if (keygen == DHKeyGeneration.SophieGermain) {
// throw new NotSupportedException(); //TODO
//} else if (keygen == DHKeyGeneration.DSA) {
// 1. Let j = (p - 1)/q.
// 2. Set h = any integer, where 1 < h < p - 1
// 3. Set g = h^j mod p
// 4. If g = 1 go to step 2
// BigInteger j = (p - 1) / q;
} else { // random
p = BigInteger.GeneratePseudoPrime(bitlen);
g = new BigInteger(3); // always use 3 as a generator
}
}
private BigInteger m_P;
private BigInteger m_G;
private BigInteger m_X;
private bool m_Disposed;
private static byte[] m_OAKLEY768 = new byte[] {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2,
0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6,
0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D,
0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9,
0xA6, 0x3A, 0x36, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
private static byte[] m_OAKLEY1024 = new byte[] {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2,
0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6,
0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D,
0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9,
0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11,
0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
private static byte[] m_OAKLEY1536 = new byte[] {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2,
0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6,
0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D,
0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9,
0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11,
0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,
0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, 0x98, 0xDA, 0x48, 0x36,
0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56,
0x20, 0x85, 0x52, 0xBB, 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,
0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, 0xF1, 0x74, 0x6C, 0x08,
0xCA, 0x23, 0x73, 0x27, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
}
}
| |
using System.Net;
using System.Text.Json;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Diagnostics;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace JsonApiDotNetCore.Middleware;
/// <summary>
/// Intercepts HTTP requests to populate injected <see cref="IJsonApiRequest" /> instance for JSON:API requests.
/// </summary>
[PublicAPI]
public sealed class JsonApiMiddleware
{
private static readonly MediaTypeHeaderValue MediaType = MediaTypeHeaderValue.Parse(HeaderConstants.MediaType);
private static readonly MediaTypeHeaderValue AtomicOperationsMediaType = MediaTypeHeaderValue.Parse(HeaderConstants.AtomicOperationsMediaType);
private readonly RequestDelegate _next;
public JsonApiMiddleware(RequestDelegate next, IHttpContextAccessor httpContextAccessor)
{
_next = next;
var session = new AspNetCodeTimerSession(httpContextAccessor);
CodeTimingSessionManager.Capture(session);
}
public async Task InvokeAsync(HttpContext httpContext, IControllerResourceMapping controllerResourceMapping, IJsonApiOptions options,
IJsonApiRequest request, ILogger<JsonApiMiddleware> logger)
{
ArgumentGuard.NotNull(httpContext, nameof(httpContext));
ArgumentGuard.NotNull(controllerResourceMapping, nameof(controllerResourceMapping));
ArgumentGuard.NotNull(options, nameof(options));
ArgumentGuard.NotNull(request, nameof(request));
ArgumentGuard.NotNull(logger, nameof(logger));
using (CodeTimingSessionManager.Current.Measure("JSON:API middleware"))
{
if (!await ValidateIfMatchHeaderAsync(httpContext, options.SerializerWriteOptions))
{
return;
}
RouteValueDictionary routeValues = httpContext.GetRouteData().Values;
ResourceType? primaryResourceType = CreatePrimaryResourceType(httpContext, controllerResourceMapping);
if (primaryResourceType != null)
{
if (!await ValidateContentTypeHeaderAsync(HeaderConstants.MediaType, httpContext, options.SerializerWriteOptions) ||
!await ValidateAcceptHeaderAsync(MediaType, httpContext, options.SerializerWriteOptions))
{
return;
}
SetupResourceRequest((JsonApiRequest)request, primaryResourceType, routeValues, httpContext.Request);
httpContext.RegisterJsonApiRequest();
}
else if (IsRouteForOperations(routeValues))
{
if (!await ValidateContentTypeHeaderAsync(HeaderConstants.AtomicOperationsMediaType, httpContext, options.SerializerWriteOptions) ||
!await ValidateAcceptHeaderAsync(AtomicOperationsMediaType, httpContext, options.SerializerWriteOptions))
{
return;
}
SetupOperationsRequest((JsonApiRequest)request, options, httpContext.Request);
httpContext.RegisterJsonApiRequest();
}
using (CodeTimingSessionManager.Current.Measure("Subsequent middleware"))
{
await _next(httpContext);
}
}
if (CodeTimingSessionManager.IsEnabled)
{
string timingResults = CodeTimingSessionManager.Current.GetResults();
string url = httpContext.Request.GetDisplayUrl();
logger.LogInformation($"Measurement results for {httpContext.Request.Method} {url}:{Environment.NewLine}{timingResults}");
}
}
private async Task<bool> ValidateIfMatchHeaderAsync(HttpContext httpContext, JsonSerializerOptions serializerOptions)
{
if (httpContext.Request.Headers.ContainsKey(HeaderNames.IfMatch))
{
await FlushResponseAsync(httpContext.Response, serializerOptions, new ErrorObject(HttpStatusCode.PreconditionFailed)
{
Title = "Detection of mid-air edit collisions using ETags is not supported.",
Source = new ErrorSource
{
Header = "If-Match"
}
});
return false;
}
return true;
}
private static ResourceType? CreatePrimaryResourceType(HttpContext httpContext, IControllerResourceMapping controllerResourceMapping)
{
Endpoint? endpoint = httpContext.GetEndpoint();
var controllerActionDescriptor = endpoint?.Metadata.GetMetadata<ControllerActionDescriptor>();
return controllerActionDescriptor != null
? controllerResourceMapping.GetResourceTypeForController(controllerActionDescriptor.ControllerTypeInfo)
: null;
}
private static async Task<bool> ValidateContentTypeHeaderAsync(string allowedContentType, HttpContext httpContext, JsonSerializerOptions serializerOptions)
{
string? contentType = httpContext.Request.ContentType;
if (contentType != null && contentType != allowedContentType)
{
await FlushResponseAsync(httpContext.Response, serializerOptions, new ErrorObject(HttpStatusCode.UnsupportedMediaType)
{
Title = "The specified Content-Type header value is not supported.",
Detail = $"Please specify '{allowedContentType}' instead of '{contentType}' for the Content-Type header value.",
Source = new ErrorSource
{
Header = "Content-Type"
}
});
return false;
}
return true;
}
private static async Task<bool> ValidateAcceptHeaderAsync(MediaTypeHeaderValue allowedMediaTypeValue, HttpContext httpContext,
JsonSerializerOptions serializerOptions)
{
string[] acceptHeaders = httpContext.Request.Headers.GetCommaSeparatedValues("Accept");
if (!acceptHeaders.Any())
{
return true;
}
bool seenCompatibleMediaType = false;
foreach (string acceptHeader in acceptHeaders)
{
if (MediaTypeHeaderValue.TryParse(acceptHeader, out MediaTypeHeaderValue? headerValue))
{
headerValue.Quality = null;
if (headerValue.MediaType == "*/*" || headerValue.MediaType == "application/*")
{
seenCompatibleMediaType = true;
break;
}
if (allowedMediaTypeValue.Equals(headerValue))
{
seenCompatibleMediaType = true;
break;
}
}
}
if (!seenCompatibleMediaType)
{
await FlushResponseAsync(httpContext.Response, serializerOptions, new ErrorObject(HttpStatusCode.NotAcceptable)
{
Title = "The specified Accept header value does not contain any supported media types.",
Detail = $"Please include '{allowedMediaTypeValue}' in the Accept header values.",
Source = new ErrorSource
{
Header = "Accept"
}
});
return false;
}
return true;
}
private static async Task FlushResponseAsync(HttpResponse httpResponse, JsonSerializerOptions serializerOptions, ErrorObject error)
{
httpResponse.ContentType = HeaderConstants.MediaType;
httpResponse.StatusCode = (int)error.StatusCode;
var errorDocument = new Document
{
Errors = error.AsList()
};
await JsonSerializer.SerializeAsync(httpResponse.Body, errorDocument, serializerOptions);
await httpResponse.Body.FlushAsync();
}
private static void SetupResourceRequest(JsonApiRequest request, ResourceType primaryResourceType, RouteValueDictionary routeValues,
HttpRequest httpRequest)
{
request.IsReadOnly = httpRequest.Method == HttpMethod.Get.Method || httpRequest.Method == HttpMethod.Head.Method;
request.PrimaryResourceType = primaryResourceType;
request.PrimaryId = GetPrimaryRequestId(routeValues);
string? relationshipName = GetRelationshipNameForSecondaryRequest(routeValues);
if (relationshipName != null)
{
request.Kind = IsRouteForRelationship(routeValues) ? EndpointKind.Relationship : EndpointKind.Secondary;
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
request.WriteOperation =
httpRequest.Method == HttpMethod.Post.Method ? WriteOperationKind.AddToRelationship :
httpRequest.Method == HttpMethod.Patch.Method ? WriteOperationKind.SetRelationship :
httpRequest.Method == HttpMethod.Delete.Method ? WriteOperationKind.RemoveFromRelationship : null;
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
RelationshipAttribute? requestRelationship = primaryResourceType.FindRelationshipByPublicName(relationshipName);
if (requestRelationship != null)
{
request.Relationship = requestRelationship;
request.SecondaryResourceType = requestRelationship.RightType;
}
}
else
{
request.Kind = EndpointKind.Primary;
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
request.WriteOperation =
httpRequest.Method == HttpMethod.Post.Method ? WriteOperationKind.CreateResource :
httpRequest.Method == HttpMethod.Patch.Method ? WriteOperationKind.UpdateResource :
httpRequest.Method == HttpMethod.Delete.Method ? WriteOperationKind.DeleteResource : null;
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
}
bool isGetAll = request.PrimaryId == null && request.IsReadOnly;
request.IsCollection = isGetAll || request.Relationship is HasManyAttribute;
}
private static string? GetPrimaryRequestId(RouteValueDictionary routeValues)
{
return routeValues.TryGetValue("id", out object? id) ? (string?)id : null;
}
private static string? GetRelationshipNameForSecondaryRequest(RouteValueDictionary routeValues)
{
return routeValues.TryGetValue("relationshipName", out object? routeValue) ? (string?)routeValue : null;
}
private static bool IsRouteForRelationship(RouteValueDictionary routeValues)
{
string actionName = (string)routeValues["action"]!;
return actionName.EndsWith("Relationship", StringComparison.Ordinal);
}
private static bool IsRouteForOperations(RouteValueDictionary routeValues)
{
string actionName = (string)routeValues["action"]!;
return actionName == "PostOperations";
}
private static void SetupOperationsRequest(JsonApiRequest request, IJsonApiOptions options, HttpRequest httpRequest)
{
request.IsReadOnly = false;
request.Kind = EndpointKind.AtomicOperations;
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERLevel;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C08_Region (editable child object).<br/>
/// This is a generated base class of <see cref="C08_Region"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="C09_CityObjects"/> of type <see cref="C09_CityColl"/> (1:M relation to <see cref="C10_City"/>)<br/>
/// This class is an item of <see cref="C07_RegionColl"/> collection.
/// </remarks>
[Serializable]
public partial class C08_Region : BusinessBase<C08_Region>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Regions ID");
/// <summary>
/// Gets the Regions ID.
/// </summary>
/// <value>The Regions ID.</value>
public int Region_ID
{
get { return GetProperty(Region_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Region_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Regions Name");
/// <summary>
/// Gets or sets the Regions Name.
/// </summary>
/// <value>The Regions Name.</value>
public string Region_Name
{
get { return GetProperty(Region_NameProperty); }
set { SetProperty(Region_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C09_Region_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C09_Region_Child> C09_Region_SingleObjectProperty = RegisterProperty<C09_Region_Child>(p => p.C09_Region_SingleObject, "C09 Region Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C09 Region Single Object ("self load" child property).
/// </summary>
/// <value>The C09 Region Single Object.</value>
public C09_Region_Child C09_Region_SingleObject
{
get { return GetProperty(C09_Region_SingleObjectProperty); }
private set { LoadProperty(C09_Region_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C09_Region_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C09_Region_ReChild> C09_Region_ASingleObjectProperty = RegisterProperty<C09_Region_ReChild>(p => p.C09_Region_ASingleObject, "C09 Region ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C09 Region ASingle Object ("self load" child property).
/// </summary>
/// <value>The C09 Region ASingle Object.</value>
public C09_Region_ReChild C09_Region_ASingleObject
{
get { return GetProperty(C09_Region_ASingleObjectProperty); }
private set { LoadProperty(C09_Region_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C09_CityObjects"/> property.
/// </summary>
public static readonly PropertyInfo<C09_CityColl> C09_CityObjectsProperty = RegisterProperty<C09_CityColl>(p => p.C09_CityObjects, "C09 City Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the C09 City Objects ("self load" child property).
/// </summary>
/// <value>The C09 City Objects.</value>
public C09_CityColl C09_CityObjects
{
get { return GetProperty(C09_CityObjectsProperty); }
private set { LoadProperty(C09_CityObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C08_Region"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C08_Region"/> object.</returns>
internal static C08_Region NewC08_Region()
{
return DataPortal.CreateChild<C08_Region>();
}
/// <summary>
/// Factory method. Loads a <see cref="C08_Region"/> object from the given C08_RegionDto.
/// </summary>
/// <param name="data">The <see cref="C08_RegionDto"/>.</param>
/// <returns>A reference to the fetched <see cref="C08_Region"/> object.</returns>
internal static C08_Region GetC08_Region(C08_RegionDto data)
{
C08_Region obj = new C08_Region();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C08_Region"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C08_Region()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C08_Region"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Region_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(C09_Region_SingleObjectProperty, DataPortal.CreateChild<C09_Region_Child>());
LoadProperty(C09_Region_ASingleObjectProperty, DataPortal.CreateChild<C09_Region_ReChild>());
LoadProperty(C09_CityObjectsProperty, DataPortal.CreateChild<C09_CityColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C08_Region"/> object from the given <see cref="C08_RegionDto"/>.
/// </summary>
/// <param name="data">The C08_RegionDto to use.</param>
private void Fetch(C08_RegionDto data)
{
// Value properties
LoadProperty(Region_IDProperty, data.Region_ID);
LoadProperty(Region_NameProperty, data.Region_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(C09_Region_SingleObjectProperty, C09_Region_Child.GetC09_Region_Child(Region_ID));
LoadProperty(C09_Region_ASingleObjectProperty, C09_Region_ReChild.GetC09_Region_ReChild(Region_ID));
LoadProperty(C09_CityObjectsProperty, C09_CityColl.GetC09_CityColl(Region_ID));
}
/// <summary>
/// Inserts a new <see cref="C08_Region"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C06_Country parent)
{
var dto = new C08_RegionDto();
dto.Parent_Country_ID = parent.Country_ID;
dto.Region_Name = Region_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IC08_RegionDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(Region_IDProperty, resultDto.Region_ID);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C08_Region"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new C08_RegionDto();
dto.Region_ID = Region_ID;
dto.Region_Name = Region_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IC08_RegionDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="C08_Region"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IC08_RegionDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(Region_IDProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators;
using CppSharp.Generators.AST;
using CppSharp.Generators.CLI;
using CppSharp.Generators.CSharp;
namespace CppSharp.Types.Std
{
[TypeMap("va_list")]
public class VaList : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
return "va_list";
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
return "va_list";
}
public override bool IsIgnored
{
get { return true; }
}
}
[TypeMap("std::string", GeneratorKind.CLI)]
public class String : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
return "System::String^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF8>({0})",
ctx.Parameter.Name);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF8>({0})",
ctx.ReturnVarName);
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
return "Std.String";
}
public override void CSharpMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("new Std.String()");
}
public override void CSharpMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write(ctx.ReturnVarName);
}
}
[TypeMap("std::wstring")]
public class WString : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
return "System::String^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF16>({0})",
ctx.Parameter.Name);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF16>({0})",
ctx.ReturnVarName);
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
return "string";
}
public override void CSharpMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("new Std.WString()");
}
public override void CSharpMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write(ctx.ReturnVarName);
}
}
[TypeMap("std::vector")]
public class Vector : TypeMap
{
public override bool IsIgnored
{
get
{
var type = Type as TemplateSpecializationType;
var pointeeType = type.Arguments[0].Type;
var checker = new TypeIgnoreChecker(TypeMapDatabase);
pointeeType.Visit(checker);
return checker.IsIgnored;
}
}
public override string CLISignature(CLITypePrinterContext ctx)
{
return string.Format("System::Collections::Generic::List<{0}>^",
ctx.GetTemplateParameterList());
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
var isPointerToPrimitive = type.Type.IsPointerToPrimitiveType();
var managedType = isPointerToPrimitive
? new CILType(typeof(System.IntPtr))
: type.Type;
var entryString = (ctx.Parameter != null) ? ctx.Parameter.Name
: ctx.ArgName;
var tmpVarName = "_tmp" + entryString;
var cppTypePrinter = new CppTypePrinter(ctx.Driver.TypeDatabase);
var nativeType = type.Type.Visit(cppTypePrinter);
ctx.SupportBefore.WriteLine("auto {0} = std::vector<{1}>();",
tmpVarName, nativeType);
ctx.SupportBefore.WriteLine("for each({0} _element in {1})",
managedType, entryString);
ctx.SupportBefore.WriteStartBraceIndent();
{
var param = new Parameter
{
Name = "_element",
QualifiedType = type
};
var elementCtx = new MarshalContext(ctx.Driver)
{
Parameter = param,
ArgName = param.Name,
};
var marshal = new CLIMarshalManagedToNativePrinter(elementCtx);
type.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore))
ctx.SupportBefore.Write(marshal.Context.SupportBefore);
if (isPointerToPrimitive)
ctx.SupportBefore.WriteLine("auto _marshalElement = {0}.ToPointer();",
marshal.Context.Return);
else
ctx.SupportBefore.WriteLine("auto _marshalElement = {0};",
marshal.Context.Return);
ctx.SupportBefore.WriteLine("{0}.push_back(_marshalElement);",
tmpVarName);
}
ctx.SupportBefore.WriteCloseBraceIndent();
ctx.Return.Write(tmpVarName);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
var isPointerToPrimitive = type.Type.IsPointerToPrimitiveType();
var managedType = isPointerToPrimitive
? new CILType(typeof(System.IntPtr))
: type.Type;
var tmpVarName = "_tmp" + ctx.ArgName;
ctx.SupportBefore.WriteLine(
"auto {0} = gcnew System::Collections::Generic::List<{1}>();",
tmpVarName, managedType);
ctx.SupportBefore.WriteLine("for(auto _element : {0})",
ctx.ReturnVarName);
ctx.SupportBefore.WriteStartBraceIndent();
{
var elementCtx = new MarshalContext(ctx.Driver)
{
ReturnVarName = "_element",
ReturnType = type
};
var marshal = new CLIMarshalNativeToManagedPrinter(elementCtx);
type.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore))
ctx.SupportBefore.Write(marshal.Context.SupportBefore);
ctx.SupportBefore.WriteLine("auto _marshalElement = {0};",
marshal.Context.Return);
if (isPointerToPrimitive)
ctx.SupportBefore.WriteLine("{0}->Add({1}(_marshalElement));",
tmpVarName, managedType);
else
ctx.SupportBefore.WriteLine("{0}->Add(_marshalElement);",
tmpVarName);
}
ctx.SupportBefore.WriteCloseBraceIndent();
ctx.Return.Write(tmpVarName);
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
if (ctx.CSharpKind == CSharpTypePrinterContextKind.Native)
return "Std.Vector";
return string.Format("Std.Vector<{0}>", ctx.GetTemplateParameterList());
}
public override void CSharpMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("{0}.Internal", ctx.Parameter.Name);
}
public override void CSharpMarshalToManaged(MarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
ctx.Return.Write("new Std.Vector<{0}>({1})", type,
ctx.ReturnVarName);
}
}
[TypeMap("std::map")]
public class Map : TypeMap
{
public override bool IsIgnored { get { return true; } }
public override string CLISignature(CLITypePrinterContext ctx)
{
var type = Type as TemplateSpecializationType;
return string.Format(
"System::Collections::Generic::Dictionary<{0}, {1}>^",
type.Arguments[0].Type, type.Arguments[1].Type);
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
if (ctx.CSharpKind == CSharpTypePrinterContextKind.Native)
return "Std.Map";
var type = Type as TemplateSpecializationType;
return string.Format(
"System.Collections.Generic.Dictionary<{0}, {1}>",
type.Arguments[0].Type, type.Arguments[1].Type);
}
}
[TypeMap("std::list")]
public class List : TypeMap
{
public override bool IsIgnored { get { return true; } }
}
[TypeMap("std::shared_ptr")]
public class SharedPtr : TypeMap
{
public override bool IsIgnored { get { return true; } }
public override string CLISignature(CLITypePrinterContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
}
[TypeMap("std::ostream", GeneratorKind.CLI)]
public class OStream : TypeMap
{
public override string CLISignature(CLITypePrinterContext ctx)
{
return "System::IO::TextWriter^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
var marshal = (CLIMarshalManagedToNativePrinter) ctx.MarshalToNative;
if (!ctx.Parameter.Type.Desugar().IsPointer())
marshal.ArgumentPrefix.Write("*");
var marshalCtxName = string.Format("ctx_{0}", ctx.Parameter.Name);
ctx.SupportBefore.WriteLine("msclr::interop::marshal_context {0};", marshalCtxName);
ctx.Return.Write("{0}.marshal_as<std::ostream*>({1})",
marshalCtxName, ctx.Parameter.Name);
}
}
[TypeMap("std::nullptr_t")]
public class NullPtr : TypeMap
{
public override bool DoesMarshalling { get { return false; } }
public override void CLITypeReference(CLITypeReferenceCollector collector,
ASTRecord<Declaration> loc)
{
var typeRef = collector.GetTypeReference(loc.Value);
var include = new Include
{
File = "cstddef",
Kind = Include.IncludeKind.Angled,
};
typeRef.Include = include;
}
}
[TypeMap("FILE")]
public class FILE : TypeMap
{
public override string CSharpSignature(CSharpTypePrinterContext ctx)
{
return "global::System.IntPtr";
}
public override void CSharpMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write(ctx.Parameter.Name);
}
public override void CSharpMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write(ctx.ReturnVarName);
}
}
}
| |
using System.Linq;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Ceen.Extras.InMemorySession
{
/// <summary>
/// Handler for registering a session on a request
/// </summary>
public class InMemorySessionHandler : IHttpModule
{
/// <summary>
/// Gets or sets the name of the cookie with the token.
/// </summary>
public string CookieName { get; set; } = "ceen-session-token";
/// <summary>
/// Gets or sets the number of seconds a session is valid.
/// </summary>
public TimeSpan ExpirationSeconds { get; set; } = TimeSpan.FromMinutes(30);
/// <summary>
/// Gets or sets a value indicating if the session cookie gets the "secure" option set,
/// meaning that it will only be sent over HTTPS
/// </summary>
public bool SessionCookieSecure { get; set; } = false;
/// <summary>
/// Gets or sets the value for the cookie "samesite" attribute.
/// The default is "Strict" meaning that the cookie will not be shared with other sites.
/// </summary>
public string SessionCookieSameSite { get; set; } = "Strict";
/// <summary>
/// Handles the request
/// </summary>
/// <returns>The awaitable task.</returns>
/// <param name="context">The requests context.</param>
public async Task<bool> HandleAsync(IHttpContext context)
{
var sessiontoken = context.Request.Cookies[CookieName];
if (string.IsNullOrWhiteSpace(sessiontoken) || !InMemorySession.SessionExists(sessiontoken))
{
sessiontoken = Guid.NewGuid().ToString();
context.Response.AddCookie(CookieName, sessiontoken, secure: SessionCookieSecure, httponly: true, samesite: SessionCookieSameSite);
}
context.Request.SessionID = sessiontoken;
await InMemorySession.GetOrCreateSessionAsync(context, ExpirationSeconds, OnCreateAsync, OnExpireAsync);
return false;
}
/// <summary>
/// Virtual method for custom handling of newly created sessions
/// </summary>
/// <param name="request">The request that caused the session to be created</param>
/// <param name="sessionID">The session ID used</param>
/// <param name="values">The values in the session</param>
/// <returns>An awaitable task</returns>
protected virtual Task OnCreateAsync(IHttpRequest request, string sessionID, Dictionary<string, object> values)
=> Task.FromResult(true);
/// <summary>
/// Virtual method for custom handling of expired sessions
/// </summary>
/// <param name="id">The ID of the session that expires</param>
/// <param name="values">The values in the session</param>
/// <returns>An awaitable task</returns>
protected virtual Task OnExpireAsync(string id, Dictionary<string, object> values)
=> Task.FromResult(true);
}
/// <summary>
/// Helper class for providing support for sessions that are only backed by memory,
/// such that contents are lost on server restart
/// </summary>
public static class InMemorySession
{
/// <summary>
/// Default delegate for callback after a session has expired
/// </summary>
/// <param name="sessionID">The session ID of the item</param>
/// <param name="values">The values in the session</param>
/// <returns>An awaitable task</returns>
public delegate Task SessionExpireCallback(string sessionID, Dictionary<string, object> values);
/// <summary>
/// Default delegate for callback when a new session is created
/// </summary>
/// <param name="request">The request that caused the session to start</param>
/// <param name="sessionID">The session ID</param>
/// <param name="values">The values in the session</param>
/// <returns>An awaitable task</returns>
public delegate Task SessionCreateCallback(IHttpRequest request, string sessionID, Dictionary<string, object> values);
/// <summary>
/// The session item, keeping track of the session state
/// </summary>
private class SessionItem
{
/// <summary>
/// The session ID
/// </summary>
public readonly string ID;
/// <summary>
/// The expiration time for this item
/// </summary>
public DateTime Expires;
/// <summary>
/// The duration for this item
/// </summary>
public TimeSpan Duration;
/// <summary>
/// The session values
/// </summary>
public Dictionary<string, object> Values = new Dictionary<string, object>();
/// <summary>
/// The callback method to invoke on expiration
/// </summary>
public SessionExpireCallback ExpireCallback;
/// <summary>
/// Creates a new session item
/// </summary>
/// <param name="id">The session ID</param>
/// <param name="duration">The session duration</param>
public SessionItem(string id, TimeSpan duration)
{
ID = id;
Duration = duration;
}
}
/// <summary>
/// The lock that guards the lookup tables
/// </summary>
private static readonly object _lock = new object();
/// <summary>
/// The list of active sessions
/// </summary>
private static Dictionary<string, SessionItem> _sessions = new Dictionary<string, SessionItem>();
/// <summary>
/// List of items, sorted by expiration time (in ticks)
/// </summary>
private static SortedList<long, List<string>> _expirations = new SortedList<long, List<string>>();
/// <summary>
/// The current expiration task
/// </summary>
private static Task ExpireTask;
/// <summary>
/// The time a session is kept alive without activity
/// </summary>
public static TimeSpan SessionDuration = TimeSpan.FromMinutes(15);
/// <summary>
/// A callback that is invoked when an item has expired
/// </summary>
public static SessionExpireCallback SessionExpired;
/// <summary>
/// A callback that is invoked when an item is created
/// </summary>
public static SessionCreateCallback SessionStarted;
/// <summary>
/// Checks if a session exists
/// </summary>
/// <param name="id">The session ID</param>
/// <returns><c>true</c> if the session exists, <c>false</c> otherwise</returns>
public static bool SessionExists(string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
lock(_lock)
return _sessions.ContainsKey(id);
}
/// <summary>
/// Updates the timeout-duration for a session.
/// If the session does not exist, this method does nothing.
/// </summary>
/// <param name="self">The session to update</param>
/// <param name="duration">The new duration</param>
public static void SetSessionDuration(this IHttpContext self, TimeSpan duration)
=> SetSessionDuration(self.Request.SessionID, duration);
/// <summary>
/// Updates the timeout-duration for a session.
/// If the session does not exist, this method does nothing.
/// </summary>
/// <param name="self">The session to update</param>
/// <param name="duration">The new duration</param>
public static void SetSessionDuration(this IHttpRequest self, TimeSpan duration)
=> SetSessionDuration(self.SessionID, duration);
/// <summary>
/// Updates the timeout-duration for a session.
/// If the session does not exist, this method does nothing.
/// </summary>
/// <param name="id">The session to update</param>
/// <param name="duration">The new duration</param>
public static void SetSessionDuration(string id, TimeSpan duration)
{
lock(_lock)
{
_sessions.TryGetValue(id, out var res);
if (res == null)
return;
_expirations[res.Expires.Ticks].Remove(res.ID);
res.Duration = duration;
res.Expires = DateTime.Now + res.Duration;
_expirations.TryGetValue(res.Expires.Ticks, out var lst);
if (lst == null)
_expirations[res.Expires.Ticks] = lst = new List<string>();
_expirations[res.Expires.Ticks].Add(res.ID);
}
}
/// <summary>
/// Gets the session values for the request, or null if no session exists.
/// This method assumes that the SessionID value of the requests has been set
/// </summary>
/// <param name="self">The context to get the session values for</param>
/// <returns>The values for the session, or null</returns>
public static Dictionary<string, object> CurrentSession(this IHttpContext self)
=> CurrentSession(self.Request.SessionID);
/// <summary>
/// Gets the session values for the request, or null if no session exists.
/// This method assumes that the SessionID value of the requests has been set
/// </summary>
/// <param name="self">The request to get the session values for</param>
/// <returns>The values for the session, or null</returns>
public static Dictionary<string, object> CurrentSession(this IHttpRequest self)
=> CurrentSession(self.SessionID);
/// <summary>
/// Gets the session with the give ID, or null if no such session exists
/// </summary>
/// <param name="id">The ID of the session to find</param>
/// <returns>The values for the session, or null</returns>
public static Dictionary<string, object> CurrentSession(string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
lock(_lock)
{
_sessions.TryGetValue(id, out var session);
return session?.Values;
}
}
/// <summary>
/// Gets or creates a session for the current context
/// </summary>
/// <param name="self">The context to use</param>
/// <returns>The values for the session</returns>
public static Task<Dictionary<string, object>> GetOrCreateSessionAsync(this IHttpContext self, TimeSpan duration = default(TimeSpan), SessionCreateCallback createCallback = null, SessionExpireCallback expireCallback = null)
=> GetOrCreateSessionAsync(self.Request.SessionID, duration, self.Request, createCallback, expireCallback);
/// <summary>
/// Gets or creates a session for the current request
/// </summary>
/// <param name="self">The request to use</param>
/// <returns>The values for the session</returns>
public static Task<Dictionary<string, object>> GetOrCreateSessionAsync(this IHttpRequest self, TimeSpan duration = default(TimeSpan), SessionCreateCallback createCallback = null, SessionExpireCallback expireCallback = null)
=> GetOrCreateSessionAsync(self.SessionID, duration, self, createCallback, expireCallback);
/// <summary>
/// Gets or creates a session for the session ID
/// </summary>
/// <param name="self">The session ID to use</param>
/// <param name="request">The request to report to the creation callback</param>
/// <returns>The values for the session</returns>
public static async Task<Dictionary<string, object>> GetOrCreateSessionAsync(string id, TimeSpan duration = default(TimeSpan), IHttpRequest request = null, SessionCreateCallback createCallback = null, SessionExpireCallback expireCallback = null)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
if (duration.Ticks < 0)
throw new ArgumentOutOfRangeException(nameof(duration));
SessionItem res;
bool created = false;
lock(_lock)
{
_sessions.TryGetValue(id, out res);
if (res == null)
{
_sessions[id] = res = new SessionItem(id, duration.Ticks == 0 ? SessionDuration: duration) {
ExpireCallback = expireCallback
};
created = true;
}
else
{
_expirations[res.Expires.Ticks].Remove(res.ID);
}
res.Expires = DateTime.Now.Add(res.Duration);
_expirations.TryGetValue(res.Expires.Ticks, out var lst);
if (lst == null)
_expirations[res.Expires.Ticks] = lst = new List<string>();
_expirations[res.Expires.Ticks].Add(res.ID);
}
if (created)
{
if (createCallback != null)
await createCallback(request, res.ID, res.Values);
else if (SessionStarted != null)
await SessionStarted(request, res.ID, res.Values);
}
StartExpireTimer();
return res.Values;
}
/// <summary>
/// Force an expiration of the session
/// </summary>
/// <param name="self">The context to find the session in</param>
/// <returns>An awaitable task</returns>
public static Task ExpireSession(this IHttpContext self)
=> ExpireSession(self.Request.SessionID);
/// <summary>
/// Force an expiration of the session
/// </summary>
/// <param name="self">The request to find the session in</param>
/// <returns>An awaitable task</returns>
public static Task ExpireSession(this IHttpRequest self)
=> ExpireSession(self.SessionID);
/// <summary>
/// Force an expiration of the session
/// </summary>
/// <param name="id">The session ID to expire</param>
/// <returns>An awaitable task</returns>
public static async Task ExpireSession(string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
SessionItem res;
lock(_lock)
{
if (_sessions.TryGetValue(id, out res) && res != null)
{
_sessions.Remove(res.ID);
_expirations[res.Expires.Ticks].Remove(res.ID);
}
}
StartExpireTimer();
if (res != null)
{
if (res.ExpireCallback != null)
await res.ExpireCallback(res.ID, res.Values);
else if (SessionExpired != null)
await SessionExpired(res.ID, res.Values);
}
}
/// <summary>
/// Starts the expire timer task, if not already running
/// </summary>
private static void StartExpireTimer()
{
lock(_lock)
{
// If there are no more tasks to run, do nothing
if (_sessions.Count == 0)
return;
// If we are already running an expiration task,
// do not start a new one
if (ExpireTask != null && !ExpireTask.IsCompleted)
return;
ExpireTask = Task.Run(TimerRunnerAsync);
}
}
/// <summary>
/// The method performing periodic invocation of expiration
/// </summary>
/// <returns>An awaitable task</returns>
private static async Task TimerRunnerAsync()
{
while(true)
{
var next = await ExpireItemsAsync();
var waittime = next - DateTime.Now;
// Avoid repeated callbacks at the expense of expiration accuracy
if (waittime < TimeSpan.FromSeconds(5))
waittime = TimeSpan.FromSeconds(5);
// Do not wait more than a single period
if (waittime > SessionDuration)
waittime = SessionDuration.Add(TimeSpan.FromSeconds(1));
// Stop running if there are no more sessions
if (_sessions.Count == 0)
{
lock(_lock)
{
if (_sessions.Count == 0)
{
ExpireTask = null;
return;
}
}
}
await Task.Delay(waittime);
}
}
/// <summary>
/// Finds all sessions that needs to expire, and expires them
/// </summary>
/// <returns>The time the next item will expire</returns>
private static async Task<DateTime> ExpireItemsAsync()
{
var expired = new Queue<SessionItem>();
var now = DateTime.Now.Ticks;
var nextExpire = now + TimeSpan.TicksPerDay;
lock(_lock)
{
// The list is sorted, so we can grab the oldest items from the top
while(_expirations.Count > 0)
{
if (_expirations.Keys[0] < now)
{
foreach(var k in _expirations.Values[0])
{
expired.Enqueue(_sessions[k]);
_sessions.Remove(k);
}
_expirations.RemoveAt(0);
}
else
{
nextExpire = _expirations.Keys[0];
break;
}
}
}
// Invoke callback methods on each expired item
while(expired.Count > 0)
{
var s = expired.Dequeue();
try
{
if (s.ExpireCallback != null)
await s.ExpireCallback(s.ID, s.Values);
else if (SessionExpired != null)
await SessionExpired(s.ID, s.Values);
}
catch (Exception ex)
{
Console.WriteLine("Error while expiring item: {0}", ex);
}
}
return new DateTime(nextExpire);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//-------------------------------------------------------------------------
/// <summary>
/// Frontend class to deal with UnityEditor specific tasks which the
/// Runtime-dll is not allowed to access, but the script can.
/// The backend part is directly exposed via the .Backend member. So
/// methods and members other than BinaryAlphaThresholdImageFromTexture()
/// can be accessed by calling PolygonOutlineFromImageFrontend.Backend.method().
/// </summary>
public class PolygonOutlineFromImageFrontend {
private Texture2D mLastSubImageTexture = null;
private bool mLastUseRegion = false;
private int mLastSubImageX = 0;
private int mLastSubImageY = 0;
private int mLastSubImageWidth = 0;
private int mLastSubImageHeight = 0;
private Color32[] mLastSubImage = null;
private PolygonOutlineFromImage mBackend = new PolygonOutlineFromImage();
private PolygonOutlineFromImage Backend {
get {
return mBackend;
}
}
public string LastError
{
get
{
return mBackend.GetLastError();
}
}
//-------------------------------------------------------------------------
// ALGORITHM PARAMETERS
//-------------------------------------------------------------------------
public float VertexReductionDistanceTolerance {
set {
mBackend.mVertexReductionDistanceTolerance = value;
}
get {
return mBackend.mVertexReductionDistanceTolerance;
}
}
public int MaxPointCount {
set {
mBackend.mMaxPointCount = value;
}
get {
return mBackend.mMaxPointCount;
}
}
public bool Convex {
set {
mBackend.mConvex = value;
}
get {
return mBackend.mConvex;
}
}
public float XOffsetNormalized {
set {
mBackend.mXOffsetNormalized = value;
}
get {
return mBackend.mXOffsetNormalized;
}
}
public float YOffsetNormalized {
set {
mBackend.mYOffsetNormalized = value;
}
get {
return mBackend.mYOffsetNormalized;
}
}
public float XScale {
set {
mBackend.mXScale = value;
}
get {
return mBackend.mXScale;
}
}
public float YScale {
set {
mBackend.mYScale = value;
}
get {
return mBackend.mYScale;
}
}
public float Thickness {
set {
mBackend.mThickness = value;
}
get {
return mBackend.mYScale;
}
}
// Used to extract a region of an input binary image that is not exactly following pixel borders but cuts out a region of e.g. [0.3px to width-0.5px]. Outside vertices are clamped component-wise to the border.
public float RegionPixelCutawayLeft {
set {
mBackend.mRegionPixelCutawayLeft = value;
}
get {
return mBackend.mRegionPixelCutawayLeft;
}
}
// See above.
public float RegionPixelCutawayRight {
set {
mBackend.mRegionPixelCutawayRight = value;
}
get {
return mBackend.mRegionPixelCutawayRight;
}
}
// See above. Top is at the positive side of the image's y axis, thus mapping to the vertex position <width>.
public float RegionPixelCutawayTop {
set {
mBackend.mRegionPixelCutawayTop = value;
}
get {
return mBackend.mRegionPixelCutawayTop;
}
}
// See above. Bottom is at the origin of the image's y axis, thus mapping to the vertex position <0>.
public float RegionPixelCutawayBottom {
set {
mBackend.mRegionPixelCutawayBottom = value;
}
get {
return mBackend.mRegionPixelCutawayBottom;
}
}
public bool NormalizeResultToCutRegion {
set {
mBackend.mNormalizeResultToCutRegion = value;
}
get {
return mBackend.mNormalizeResultToCutRegion;
}
}
//-------------------------------------------------------------------------
/// <param name='binaryImage'>
/// A bool array representing the resuling threshold image. In row-major order, thus accessed binaryImage[y,x].
/// </param>
public bool BinaryAlphaThresholdImageFromTexture(out bool[,] binaryImage, Texture2D texture, float normalizedAlphaThreshold,
bool useRegion, int regionX, int regionYFromTop, int regionWidth, int regionHeight) {
bool isCachedSubImageUpToDate = IsCachedImageUpToDate(texture, useRegion, regionX, regionYFromTop, regionWidth, regionHeight);
if (!isCachedSubImageUpToDate) {
if (!ReadAndCacheSubImage(texture, useRegion, regionX, regionYFromTop, regionWidth, regionHeight)) { // this method calls SetLastError with a precise message.
binaryImage = null;
return false;
}
}
byte alphaThreshold8Bit = (byte)(normalizedAlphaThreshold * 255.0f);
int width = mLastSubImageWidth;
int height = mLastSubImageHeight;
binaryImage = new bool[height, width];
// NOTE: mainTexPixels is read from bottom left origin upwards.
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
byte alpha = mLastSubImage[y * width + x].a;
if (alpha >= alphaThreshold8Bit)
binaryImage[y,x] = true;
else
binaryImage[y,x] = false;
}
}
return true;
}
//-------------------------------------------------------------------------
private bool IsCachedImageUpToDate(Texture2D texture, bool useRegion,
int regionX, int regionYFromTop, int regionWidth, int regionHeight) {
return (mLastSubImageTexture == texture &&
mLastUseRegion == useRegion &&
mLastSubImageX == regionX &&
mLastSubImageY == regionYFromTop &&
mLastSubImageWidth == regionWidth &&
mLastSubImageHeight == regionHeight &&
mLastSubImage != null);
}
//-------------------------------------------------------------------------
private bool ReadAndCacheSubImage(Texture2D texture, bool useRegion,
int regionX, int regionYFromTop, int regionWidth, int regionHeight) {
Color32[] texturePixels = null;
try {
texturePixels = texture.GetPixels32();
}
catch (System.Exception ) {
// expected behaviour, if the texture is read-only.
}
bool wasTextureReadOnly = (texturePixels == null);
if (wasTextureReadOnly) {
if (!SetTextureReadable(texture, true)) {
SetLastError("Unable to set the texture '" + texture.name + "' to readable state. Aborting collider mesh generation. Please set the texture's readable flag manually via the editor.");
return false;
}
texturePixels = texture.GetPixels32();
}
int destWidth = texture.width;
int destHeight = texture.height;
int srcRegionOffsetX = 0;
int srcRegionOffsetY = 0; // = bottom left origin
if (!useRegion) {
mLastSubImage = texturePixels;
}
else {
destWidth = regionWidth;
destHeight = regionHeight;
srcRegionOffsetX = regionX;
srcRegionOffsetY = texture.height - destHeight - regionYFromTop; // regionYFromTop is measured from top(-left) origin to the top of the region.
mLastSubImage = new Color32[destHeight * destWidth];
// NOTE: mainTexPixels is read from bottom left origin upwards.
for (int destY = 0; destY < destHeight; ++destY) {
for (int destX = 0; destX < destWidth; ++destX) {
int srcX = destX + srcRegionOffsetX;
int srcY = destY + srcRegionOffsetY;
int destIndex = destY * destWidth + destX;
int srcIndex = srcY * texture.width + srcX;
mLastSubImage[destIndex] = texturePixels[srcIndex];
}
}
}
mLastSubImageTexture = texture;
mLastUseRegion = useRegion;
mLastSubImageX = regionX;
mLastSubImageY = regionYFromTop;
mLastSubImageWidth = destWidth;
mLastSubImageHeight = destHeight;
if (wasTextureReadOnly) {
if (!SetTextureReadable(texture, false)) {
SetLastError("Unable to set the texture '" + texture.name + "' back to read-only state. Continuing anyway, please set the texture's readable flag manually via the editor.");
return false;
}
}
return true;
}
//-------------------------------------------------------------------------
public bool SetTextureReadable(Texture2D texture, bool readable) {
#if UNITY_EDITOR
string texturePath = UnityEditor.AssetDatabase.GetAssetPath(texture);
if (!System.IO.File.Exists(texturePath)) {
SetLastError("Aborting Generation: Texture at path " + texturePath + " not found while changing import settings - did you delete it?");
return false;
}
UnityEditor.TextureImporter textureImporter = (UnityEditor.TextureImporter) UnityEditor.AssetImporter.GetAtPath(texturePath);
textureImporter.isReadable = readable;
UnityEditor.AssetDatabase.ImportAsset(texturePath);
#endif
return true;
}
//-------------------------------------------------------------------------
private void SetLastError(string description) {
mBackend.SetLastError(description);
}
//-------------------------------------------------------------------------
// METHODS SIMPLY FORWARDED TO THE BACKEND CLASS
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
/// <summary>
/// Performs all steps of the collider computation and fills the output
/// parameters vertices and triangleIndices with data of an (uncapped)
/// triangle-fence.
/// </summary>
/// <param name='vertices'>
/// The resulting vertex array, can e.g. be assigned at MeshCollider.sharedMesh.vertices.
/// </param>
/// <param name='triangleIndices'>
/// The resulting triangle indices for the vertex array, can e.g. be assigned at MeshCollider.sharedMesh.triangles.
/// </param>
/// <param name='binaryImage'>
/// The input binary image as a bool array. True represents island-pixels, false sea-pixels.
/// </param>
/// <param name='regionStartingPoint'>
/// The starting point within the desired island- or sea-region for the collider computation.
/// </param>
/// <param name='isIsland'>
/// If true, then the outline of island-pixels connected to regionStartingPoint is computed. If false, the outline of sea-pixels is computed.
/// </param>
/// <param name='outputVerticesInNormalizedSpace'>
/// If true, the resulting vertices will be in the range [0..1], if false it will be [0..imageWidth].
/// </param>
/// <param name='traverseInCCWOrder'>
/// If true, the resulting outline will be in counter-clockwise (ccw) order, thus normals pointing outwards (usually needed at islands).
/// If false, the outline will be in clockwise (cw) order, thus normals pointing inwards (usually needed at sea-regions).
/// </param>
public void TriangleFenceOutlineFromBinaryImage(out Vector3[] vertices, out int[] triangleIndices, bool[,] binaryImage, IntVector2 regionStartingPoint, bool isIsland, bool outputVerticesInNormalizedSpace, bool traverseInCCWOrder)
{
mBackend.TriangleFenceOutlineFromBinaryImage(out vertices, out triangleIndices, binaryImage, regionStartingPoint, isIsland, outputVerticesInNormalizedSpace, traverseInCCWOrder);
}
//-------------------------------------------------------------------------
/// <summary>
/// Performs all steps of the collider computation and fills the output
/// parameters vertices and quadIndices with data of an (uncapped)
/// quad-fence.
/// </summary>
/// <param name='vertices'>
/// The resulting vertex array.
/// </param>
/// <param name='quadIndices'>
/// The resulting quad indices for the vertex array.
/// </param>
/// <param name='binaryImage'>
/// The input binary image as a bool array. True represents island-pixels, false sea-pixels.
/// </param>
/// <param name='regionStartingPoint'>
/// The starting point within the desired island- or sea-region for the collider computation.
/// </param>
/// <param name='isIsland'>
/// If true, then the outline of island-pixels connected to regionStartingPoint is computed. If false, the outline of sea-pixels is computed.
/// </param>
/// <param name='outputVerticesInNormalizedSpace'>
/// If true, the resulting vertices will be in the range [0..1], if false it will be [0..imageWidth].
/// </param>
/// <param name='traverseInCCWOrder'>
/// If true, the resulting outline will be in counter-clockwise (ccw) order, thus normals pointing outwards (usually needed at islands).
/// If false, the outline will be in clockwise (cw) order, thus normals pointing inwards (usually needed at sea-regions).
/// </param>
public void QuadFenceOutlineFromBinaryImage(out Vector3[] vertices, out int[] quadIndices, bool[,] binaryImage, IntVector2 regionStartingPoint, bool isIsland, bool outputVerticesInNormalizedSpace, bool traverseInCCWOrder)
{
mBackend.QuadFenceOutlineFromBinaryImage(out vertices, out quadIndices, binaryImage, regionStartingPoint, isIsland, outputVerticesInNormalizedSpace, traverseInCCWOrder);
}
//-------------------------------------------------------------------------
/// <summary>
/// Performs multiple steps of the collider computation at once and fills the output
/// parameter outlinePolygonVertexList with data of the computed outline polygon.
/// </summary>
/// <param name='outlinePolygonVertexList'>
/// The resulting outline polygon vertices.
/// </param>
/// <param name='binaryImage'>
/// The input binary image as a bool array. True represents island-pixels, false sea-pixels.
/// </param>
/// <param name='regionStartingPoint'>
/// The starting point within the desired island- or sea-region for the collider computation.
/// </param>
/// <param name='isIsland'>
/// If true, then the outline of island-pixels connected to regionStartingPoint is computed. If false, the outline of sea-pixels is computed.
/// </param>
/// <param name='outputVerticesInNormalizedSpace'>
/// If true, the resulting vertices will be in the range [0..1], if false it will be [0..imageWidth].
/// </param>
/// <param name='traverseInCCWOrder'>
/// If true, the resulting outline will be in counter-clockwise (ccw) order, thus normals pointing outwards (usually needed at islands).
/// If false, the outline will be in clockwise (cw) order, thus normals pointing inwards (usually needed at sea-regions).
/// </param>
public void PolygonOutlineFromBinaryImage(out List<Vector2> outlinePolygonVertexList, bool[,] binaryImage, IntVector2 regionStartingPoint, bool isIsland, bool outputVerticesInNormalizedSpace, bool traverseInCCWOrder)
{
mBackend.PolygonOutlineFromBinaryImage(out outlinePolygonVertexList, binaryImage, regionStartingPoint, isIsland, outputVerticesInNormalizedSpace, traverseInCCWOrder);
}
//-------------------------------------------------------------------------
/// <summary>
/// First step in the TriangleFenceOutlineFromBinaryImage and
/// QuadFenceOutlineFromBinaryImage algorithms above.
/// First call this method, then pass the <c>outlineVertices</c> to the
/// TriangleFenceFromOutlineVertices method.
/// </summary>
/// <param name='outlineVertices'>
/// The resulting vertices describing the outline, not optimized yet.
/// Pass this output parameter to the TriangleFenceFromOutlineVertices
/// method to get an optimized outline triangle fence.
/// </param>
/// /// <param name='regionStartingPoint'>
/// The starting point within the desired island- or sea-region for the collider computation.
/// </param>
/// <param name='isIsland'>
/// If true, then the outline of island-pixels connected to regionStartingPoint is computed. If false, the outline of sea-pixels is computed.
/// </param>
/// <param name='outputVerticesInNormalizedSpace'>
/// If true, the resulting vertices will be in the range [0..1], if false it will be [0..imageWidth].
/// </param>
/// <param name='traverseInCCWOrder'>
/// If true, the resulting outline will be in counter-clockwise (ccw) order, thus normals pointing outwards (usually needed at islands).
/// If false, the outline will be in clockwise (cw) order, thus normals pointing inwards (usually needed at sea-regions).
/// </param>
public void UnreducedOutlineFromBinaryImage(out List<Vector2> outlineVertices, bool[,] binaryImage, IntVector2 regionStartingPoint, bool isIsland, bool outputVerticesInNormalizedSpace, bool traverseInCCWOrder)
{
mBackend.UnreducedOutlineFromBinaryImage(out outlineVertices, binaryImage, regionStartingPoint, isIsland, outputVerticesInNormalizedSpace, traverseInCCWOrder);
}
//-------------------------------------------------------------------------
/// <summary>
/// Reduces the vertex count of a given Vector2 vertex list.
/// The reduction algorithm produces no more vertices than both criteria
/// <c>mVertexReductionDistanceTolerance</c> and <c>mMaxPointCount</c>
/// combined allow for.
/// </summary>
/// <returns>
/// The outline with reduced vertex count.
/// </returns>
/// <param name='unreducedOutlineVertices'>
/// The input un-optimized outline polygon vertices.
/// </param>
/// <param name='outlineWasCreatedInCCWOrder'>
/// Whether the outline was created in counter-clockwise (CCW) order. This parameter is
/// important only if convex is set to true at the parameters.
/// </param>
public List<Vector2> ReduceOutline(List<Vector2> unreducedOutlineVertices, bool outlineWasCreatedInCCWOrder) {
return mBackend.ReduceOutline(unreducedOutlineVertices, outlineWasCreatedInCCWOrder);
}
//-------------------------------------------------------------------------
/// <summary>
/// Last step in the TriangleFenceOutlineFromBinaryImage algorithm above.
/// First call UnreducedOutlineFromBinaryImage, then optionally ReduceOutline
/// and finally pass the returned <c>outlineVertices</c> to this method.
/// </summary>
/// <param name='resultFenceVertices'>
/// The resulting vertex array, can e.g. be assigned at MeshCollider.sharedMesh.vertices.
/// </param>
/// <param name='triangleIndices'>
/// The resulting triangle indices for the vertex array, can e.g. be assigned at MeshCollider.sharedMesh.triangles.
/// </param>
/// <param name='outlineVertices'>
/// The input outline polygon vertices.
/// </param>
/// <param name='reverseVertexOrder'>
/// If true, the resulting triangle-fence will be in opposite (clockwise vs. counter-clockwise) order
/// than the input outlineVertices.
/// </param>
public void TriangleFenceFromOutline(out Vector3[] resultFenceVertices, out int[] triangleIndices, List<Vector2> outlineVertices, bool reverseVertexOrder) {
mBackend.TriangleFenceFromOutline(out resultFenceVertices, out triangleIndices, outlineVertices, reverseVertexOrder);
}
//-------------------------------------------------------------------------
/// <summary>
/// Last step in the QuadFenceOutlineFromBinaryImage algorithm above.
/// First call UnreducedOutlineFromBinaryImage, then optionally ReduceOutline
/// and finally pass the returned <c>outlineVertices</c> to this method.
/// </summary>
/// <param name='resultFenceVertices'>
/// The resulting vertex array.
/// </param>
/// <param name='quadIndices'>
/// The resulting quad indices for the vertex array.
/// </param>
/// <param name='outlineVertices'>
/// The input outline polygon vertices.
/// </param>
/// <param name='reverseVertexOrder'>
/// If true, the resulting triangle-fence will be in opposite (clockwise vs. counter-clockwise) order
/// than the input outlineVertices.
/// </param>
public void QuadFenceFromOutline(out Vector3[] resultFenceVertices, out int[] quadIndices, List<Vector2> outlineVertices, bool reverseVertexOrder) {
mBackend.QuadFenceFromOutline(out resultFenceVertices, out quadIndices, outlineVertices, reverseVertexOrder);
}
}
| |
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Linq.Expressions;
#if DLAB_UNROOT_NAMESPACE || DLAB_XRM
namespace DLaB.Xrm
#else
namespace Source.DLaB.Xrm
#endif
{
public static partial class Extensions
{
// ActiveOnly is a method and _activeOnly Can't be called ActiveOnly
// ReSharper disable once InconsistentNaming
private static readonly bool _activeOnly = new LateBoundQuerySettings(string.Empty).ActiveOnly;
#region LinkEntity
#region AddChildLink: All methods created due to possible bug - http://stackoverflow.com/questions/10722307/why-does-linkentity-addlink-initialize-the-linkfromentityname-with-its-own-lin
/// <summary>
/// Adds the new LinkEntity as a child to this LinkEntity, rather than this LinkEntity's LinkFrom Entity
/// Assumes that the linkFromAttributeName and the linkToAttributeName are the same
/// </summary>
/// <param name="link"></param>
/// <param name="linkToEntityName"></param>
/// <param name="linkAttributesName"></param>
/// <returns></returns>
public static LinkEntity AddChildLink(this LinkEntity link, string linkToEntityName, string linkAttributesName)
{
return link.AddChildLink(linkToEntityName, linkAttributesName, linkAttributesName);
}
/// <summary>
/// Adds the new LinkEntity as a child to this LinkEntity, rather than this LinkEntity's LinkFrom Entity
/// Assumes that the linkFromAttributeName and the linkToAttributeName are the same
/// </summary>
/// <param name="link"></param>
/// <param name="linkToEntityName"></param>
/// <param name="linkAttributesName"></param>
/// <param name="joinType"></param>
/// <returns></returns>
public static LinkEntity AddChildLink(this LinkEntity link, string linkToEntityName, string linkAttributesName, JoinOperator joinType)
{
return link.AddChildLink(linkToEntityName, linkAttributesName, linkAttributesName, joinType);
}
/// <summary>
/// Adds the new LinkEntity as a child to this LinkEntity, rather than this LinkEntity's LinkFrom Entity
/// </summary>
/// <param name="link"></param>
/// <param name="linkToEntityName"></param>
/// <param name="linkFromAttributeName"></param>
/// <param name="linkToAttributeName"></param>
/// <returns></returns>
public static LinkEntity AddChildLink(this LinkEntity link, string linkToEntityName,
string linkFromAttributeName, string linkToAttributeName)
{
return link.AddChildLink(linkToEntityName, linkFromAttributeName, linkToAttributeName, JoinOperator.Inner);
}
/// <summary>
/// Adds the new LinkEntity as a child to this LinkEntity, rather than this LinkEntity's LinkFrom Entity
/// </summary>
/// <param name="link"></param>
/// <param name="linkToEntityName"></param>
/// <param name="linkFromAttributeName"></param>
/// <param name="linkToAttributeName"></param>
/// <param name="joinType"></param>
/// <returns></returns>
public static LinkEntity AddChildLink(this LinkEntity link, string linkToEntityName,
string linkFromAttributeName, string linkToAttributeName, JoinOperator joinType)
{
var child = new LinkEntity(
link.LinkToEntityName, linkToEntityName,
linkFromAttributeName, linkToAttributeName, joinType);
link.LinkEntities.Add(child);
return child;
}
#endregion AddChildLink
#region AddLink
/// <summary>
/// Assumes that the linkFromAttributeName and the linkToAttributeName are the same
/// </summary>
/// <param name="link">The link.</param>
/// <param name="linkToEntityName">Name of the link to entity.</param>
/// <param name="linkAttributesName">Name of the link from and link to attribute.</param>
/// <returns></returns>
public static LinkEntity AddLink(this LinkEntity link, string linkToEntityName, string linkAttributesName)
{
return link.AddLink(linkToEntityName, linkAttributesName, linkAttributesName);
}
/// <summary>
/// Assumes that the linkFromAttributeName and the linkToAttributeName are the same
/// </summary>
/// <param name="link">The link.</param>
/// <param name="linkToEntityName">Name of the link to entity.</param>
/// <param name="linkAttributesName">Name of the link from and link to attribute.</param>
/// <param name="joinType">Type of the join to perform.</param>
/// <returns></returns>
public static LinkEntity AddLink(this LinkEntity link, string linkToEntityName, string linkAttributesName, JoinOperator joinType)
{
return link.AddLink(linkToEntityName, linkAttributesName, linkAttributesName, joinType);
}
#endregion AddLink
#region AddLink<T>
#region Same Link Attribute Name
/// <summary>
/// Adds the type T as a child linked entity to the LinkEntity, additionally ensuring it is active.
/// Assumes both entities have the same attribute name to link on.
/// </summary>
/// <typeparam name="T">The type of the entity that is to be linked</typeparam>
/// <param name="link">The link.</param>
/// <param name="linkAttributesName">Name of the link from and link to attribute.</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this LinkEntity link, string linkAttributesName) where T : Entity
{
return link.AddLink<T>(linkAttributesName, linkAttributesName);
}
/// <summary>
/// Adds the type T as a child linked entity to the LinkEntity, additionally ensuring it is active.
/// Assumes both entities have the same attribute name to link on.
/// </summary>
/// <typeparam name="T">The type of the entity that is to be linked</typeparam>
/// <param name="link">The link.</param>
/// <param name="linkAttributesName">Name of the link from and link to attribute.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this LinkEntity link, string linkAttributesName, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
return link.AddLink(linkAttributesName, linkAttributesName, anonymousTypeInitializer);
}
/// <summary>
/// Adds the type T as a child linked entity, additionally ensuring it is active.
/// Assumes both entities have the same attribute name to link on.
/// </summary>
/// <typeparam name="T">The type of the entity that is to me linked</typeparam>
/// <param name="link">The link.</param>
/// <param name="linkAttributesName">Name of the link from and link to attribute.</param>
/// <param name="joinType">Type of the join to perform.</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this LinkEntity link, string linkAttributesName, JoinOperator joinType) where T : Entity
{
return link.AddLink<T>(linkAttributesName, linkAttributesName, joinType);
}
/// <summary>
/// Adds the type T as a child linked entity, additionally ensuring it is active.
/// Assumes both entities have the same attribute name to link on.
/// </summary>
/// <typeparam name="T">The type of the entity that is to me linked</typeparam>
/// <param name="link">The link.</param>
/// <param name="linkAttributesName">Name of the link from and link to attribute.</param>
/// <param name="joinType">Type of the join to perform.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this LinkEntity link, string linkAttributesName, JoinOperator joinType, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
return link.AddLink(linkAttributesName, linkAttributesName, joinType, anonymousTypeInitializer);
}
#endregion Same Link Attribute Name
#region Different Link Attribute Names
/// <summary>
/// Adds the type T as a child linked entity, additionally ensuring it is active.
/// </summary>
/// <typeparam name="T">The type of the entity that is to me linked</typeparam>
/// <param name="link">The link.</param>
/// <param name="linkFromAttributeName">Name of the link from attribute.</param>
/// <param name="linkToAttributeName">Name of the link to attribute.</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this LinkEntity link, string linkFromAttributeName, string linkToAttributeName) where T : Entity
{
var childLink = link.AddChildLink(EntityHelper.GetEntityLogicalName<T>(), linkFromAttributeName, linkToAttributeName);
if (_activeOnly)
{
childLink.LinkCriteria.ActiveOnly<T>();
}
return childLink;
}
/// <summary>
/// Adds the type T as a child linked entity, additionally ensuring it is active.
/// </summary>
/// <typeparam name="T">The type of the entity that is to me linked</typeparam>
/// <param name="link">The link.</param>
/// <param name="linkFromAttributeName">Name of the link from attribute.</param>
/// <param name="linkToAttributeName">Name of the link to attribute.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this LinkEntity link, string linkFromAttributeName, string linkToAttributeName, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
var childLink = link.AddLink<T>(linkFromAttributeName, linkToAttributeName);
childLink.Columns.AddColumns(anonymousTypeInitializer);
return childLink;
}
/// <summary>
/// Adds the type T as a child linked entity, additionally ensuring it is active.
/// </summary>
/// <typeparam name="T">The type of Entity</typeparam>
/// <param name="link">The link.</param>
/// <param name="linkFromAttributeName">Name of the link from attribute.</param>
/// <param name="linkToAttributeName">Name of the link to attribute.</param>
/// <param name="joinType">Type of the join.</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this LinkEntity link, string linkFromAttributeName, string linkToAttributeName, JoinOperator joinType) where T : Entity
{
var childLink = link.AddChildLink(EntityHelper.GetEntityLogicalName<T>(), linkFromAttributeName, linkToAttributeName, joinType);
if (_activeOnly)
{
childLink.LinkCriteria.ActiveOnly<T>();
}
return childLink;
}
/// <summary>
/// Adds the type T as a child linked entity, additionally ensuring it is active.
/// </summary>
/// <typeparam name="T">The type of Entity</typeparam>
/// <param name="link">The link.</param>
/// <param name="linkFromAttributeName">Name of the link from attribute.</param>
/// <param name="linkToAttributeName">Name of the link to attribute.</param>
/// <param name="joinType">Type of the join.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this LinkEntity link, string linkFromAttributeName, string linkToAttributeName, JoinOperator joinType, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
var childLink = link.AddLink<T>(linkFromAttributeName, linkToAttributeName, joinType);
childLink.Columns.AddColumns(anonymousTypeInitializer);
return childLink;
}
#endregion Different Link Attribute Names
#endregion AddLink<T>
#endregion LinkEntity
#region QueryExpression
#region AddLink
/// <summary>
/// Adds a LinkEntity to the Query Expression, returning it.
/// </summary>
/// <param name="qe">The qe.</param>
/// <param name="linkToEntityName">Name of the link to entity.</param>
/// <param name="linkAttributesName">Name of the link attributes.</param>
/// <returns></returns>
public static LinkEntity AddLink(this QueryExpression qe, string linkToEntityName, string linkAttributesName)
{
return qe.AddLink(linkToEntityName, linkAttributesName, linkAttributesName);
}
/// <summary>
/// Adds a LinkEntity to the Query Expression, returning it.
/// </summary>
/// <param name="qe">The qe.</param>
/// <param name="linkToEntityName">Name of the link to entity.</param>
/// <param name="linkAttributesName">Name of the link attributes.</param>
/// <param name="joinType">Type of the join.</param>
/// <returns></returns>
public static LinkEntity AddLink(this QueryExpression qe, string linkToEntityName, string linkAttributesName, JoinOperator joinType)
{
return qe.AddLink(linkToEntityName, linkAttributesName, linkAttributesName, joinType);
}
#endregion AddLink
#region AddLink<T>
#region Same Link Attribute Name
/// <summary>
/// Adds the type T as a linked entity to the query expression, additionally ensuring it is active.
/// Assumes both entities have the same attribute name to link on.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="qe"></param>
/// <param name="linkAttributesName"></param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this QueryExpression qe, string linkAttributesName) where T : Entity
{
return qe.AddLink<T>(linkAttributesName, linkAttributesName);
}
/// <summary>
/// Adds the type T as a linked entity to the query expression, additionally ensuring it is active.
/// Assumes both entities have the same attribute name to link on.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="qe"></param>
/// <param name="linkAttributesName"></param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this QueryExpression qe, string linkAttributesName, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
return qe.AddLink(linkAttributesName, linkAttributesName, anonymousTypeInitializer);
}
/// <summary>
/// Adds the type T as a linked entity, additionally ensuring it is active.
/// Assumes both entities have the same attribute name to link on.
/// </summary>
/// <typeparam name="T">The type of the entity that is to be linked and asserted active.</typeparam>
/// <param name="qe">The query expression.</param>
/// <param name="linkAttributesName">Name of the link attributes.</param>
/// <param name="joinType">Type of the join to perform.</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this QueryExpression qe, string linkAttributesName, JoinOperator joinType) where T : Entity
{
return qe.AddLink<T>(linkAttributesName, linkAttributesName, joinType);
}
/// <summary>
/// Adds the type T as a linked entity, additionally ensuring it is active.
/// Assumes both entities have the same attribute name to link on.
/// </summary>
/// <typeparam name="T">The type of the entity that is to be linked and asserted active.</typeparam>
/// <param name="qe">The query expression.</param>
/// <param name="linkAttributesName">Name of the link attributes.</param>
/// <param name="joinType">Type of the join to perform.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this QueryExpression qe, string linkAttributesName, JoinOperator joinType, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
return qe.AddLink(linkAttributesName, linkAttributesName, joinType, anonymousTypeInitializer);
}
#endregion Same Link Attribute Name
#region Different Link Attribute Names
/// <summary>
/// Adds the type T as a linked entity to the query expression, additionally ensuring it is active.
/// </summary>
/// <typeparam name="T">The type of the entity that is to be linked and asserted active.</typeparam>
/// <param name="qe">The query expression.</param>
/// <param name="linkFromAttributeName">Name of the link from attribute.</param>
/// <param name="linkToAttributeName">Name of the link to attribute.</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this QueryExpression qe, string linkFromAttributeName, string linkToAttributeName) where T : Entity
{
var link = qe.AddLink(EntityHelper.GetEntityLogicalName<T>(), linkFromAttributeName, linkToAttributeName);
if (_activeOnly)
{
link.LinkCriteria.ActiveOnly<T>();
}
return link;
}
/// <summary>
/// Adds the type T as a linked entity to the query expression, additionally ensuring it is active.
/// </summary>
/// <typeparam name="T">The type of the entity that is to be linked and asserted active.</typeparam>
/// <param name="qe">The query expression.</param>
/// <param name="linkFromAttributeName">Name of the link from attribute.</param>
/// <param name="linkToAttributeName">Name of the link to attribute.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this QueryExpression qe, string linkFromAttributeName, string linkToAttributeName, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
var link = qe.AddLink(EntityHelper.GetEntityLogicalName<T>(), linkFromAttributeName, linkToAttributeName);
if (_activeOnly)
{
link.LinkCriteria.ActiveOnly<T>();
}
link.Columns.AddColumns(anonymousTypeInitializer);
return link;
}
/// <summary>
/// Adds the type T as a linked entity, additionally ensuring it is active.
/// </summary>
/// <typeparam name="T">The type of the entity that is to be linked and asserted active.</typeparam>
/// <param name="qe">The query expression.</param>
/// <param name="linkFromAttributeName">Name of the link from attribute.</param>
/// <param name="linkToAttributeName">Name of the link to attribute.</param>
/// <param name="joinType">Type of the join to perform.</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this QueryExpression qe, string linkFromAttributeName, string linkToAttributeName, JoinOperator joinType) where T : Entity
{
var link = qe.AddLink(EntityHelper.GetEntityLogicalName<T>(), linkFromAttributeName, linkToAttributeName, joinType);
if (_activeOnly)
{
link.LinkCriteria.ActiveOnly<T>();
}
return link;
}
/// <summary>
/// Adds the type T as a linked entity, additionally ensuring it is active.
/// </summary>
/// <typeparam name="T">The type of the entity that is to be linked and asserted active.</typeparam>
/// <param name="qe">The query expression.</param>
/// <param name="linkFromAttributeName">Name of the link from attribute.</param>
/// <param name="linkToAttributeName">Name of the link to attribute.</param>
/// <param name="joinType">Type of the join to perform.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add</param>
/// <returns></returns>
public static LinkEntity AddLink<T>(this QueryExpression qe, string linkFromAttributeName, string linkToAttributeName, JoinOperator joinType, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
var link = qe.AddLink(EntityHelper.GetEntityLogicalName<T>(), linkFromAttributeName, linkToAttributeName, joinType);
if (_activeOnly)
{
link.LinkCriteria.ActiveOnly<T>();
}
link.Columns.AddColumns(anonymousTypeInitializer);
return link;
}
#endregion Different Link Attribute Names
#endregion AddLink<T>
#endregion QueryExpression
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
//using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.Native;
namespace Microsoft.Samples.Debugging.CorDebug
{
// This class is a thin managed wrapper over the V3 stackwalking API (ICorDebugStackWalk).
// It does not expose ICorDebugInternalFrame. Use the derived class CorStackWalkEx if you want
// ICorDebugInternalFrame.
public class CorStackWalk : WrapperBase
{
internal CorStackWalk (ICorDebugStackWalk stackwalk, CorThread thread)
:base(stackwalk)
{
m_th = thread;
m_sw = stackwalk;
}
internal ICorDebugStackWalk GetInterface ()
{
return m_sw;
}
[CLSCompliant(false)]
public ICorDebugStackWalk Raw
{
get
{
return m_sw;
}
}
//
// IEnumerator interface
//
public virtual bool MoveNext()
{
int hr;
if (m_init)
{
hr = m_sw.Next();
}
else
{
m_init = true;
hr = (int)HResult.S_OK;
}
if (HRUtils.IsFailingHR(hr))
{
Marshal.ThrowExceptionForHR(hr);
}
if (hr == (int)HResult.S_OK)
{
ICorDebugFrame frame;
m_sw.GetFrame(out frame);
if (frame == null)
{
m_frame = null;
return true;
}
m_frame = new CorFrame(frame);
return true;
}
else
{
Debug.Assert(hr == (int)HResult.CORDBG_S_AT_END_OF_STACK);
return false;
}
}
public virtual void Reset()
{
// There is no way to reset. Just create a new one.
CorStackWalk s = m_th.CreateStackWalk(CorStackWalkType.PureV3StackWalk);
m_sw = s.GetInterface();
m_frame = null;
}
public CorFrame Current
{
get
{
return m_frame;
}
}
#region Get/Set Context
[CLSCompliant(false)]
public void GetThreadContext(ContextFlags flags, int contextBufferSize, out int contextSize, IntPtr contextBuffer)
{
uint uContextSize = 0;
m_sw.GetContext((uint)flags, (uint)contextBufferSize, out uContextSize, contextBuffer);
contextSize = (int)uContextSize;
}
[CLSCompliant(false)]
public INativeContext GetContext()
{
INativeContext context = ContextAllocator.GenerateContext();
this.GetContext(context);
return context;
}
// ClsComplaint version of GetThreadContext.
// Caller must ensure that the context is valid, and for the right architecture.
[CLSCompliant(false)]
public void GetContext(INativeContext context)
{
using (IContextDirectAccessor w = context.OpenForDirectAccess())
{ // context buffer is now locked
// We initialize to a HUGE number so that we make sure GetThreadContext is updating the size variable. If it doesn't,
// then we will hit the assert statement below.
int size = Int32.MaxValue;
this.GetThreadContext((ContextFlags)context.Flags,w.Size, out size, w.RawBuffer);
// We should only assert when the buffer is insufficient. Since the runtime only keeps track of CONTEXT_CONTROL and CONTEXT_INTEGER
// we will expect to create a larger buffer than absolutely necessary. The context buffer will be the size of a FULL machine
// context.
Debug.Assert(size <= w.Size, String.Format("Insufficient Buffer: Expected {0} bytes, but received {1}",w.Size, size));
}
}
[CLSCompliant(false)]
public void SetThreadContext ( CorDebugSetContextFlag flag, int contextSize, IntPtr contextBuffer)
{
m_sw.SetContext(flag, (uint)contextSize, contextBuffer);
// update the current frame
ICorDebugFrame frame;
m_sw.GetFrame(out frame);
if (frame == null)
{
m_frame = null;
}
else
{
m_frame = new CorFrame(frame);
}
}
// ClsComplaint version of SetThreadContext.
// Caller must ensure that the context is valid, and for the right architecture.
[CLSCompliant(false)]
public void SetContext(CorDebugSetContextFlag flag, INativeContext context)
{
using (IContextDirectAccessor w = context.OpenForDirectAccess())
{ // context buffer is now locked
SetThreadContext(flag, w.Size, w.RawBuffer);
}
}
#endregion // Get/Set Context
[CLSCompliant(false)]
protected ICorDebugStackWalk m_sw;
protected CorThread m_th;
protected CorFrame m_frame;
// This is an artificat of managed enumerator semantics. We must call MoveNext() once before the enumerator becomes "valid".
// Once this occurs, m_init becomes true, but it is false at creation time
protected bool m_init; // = false (at creation time)
} /* class CorStackWalk */
// Unlike CorStackWalk, this class exposes ICorDebugInternalFrame. It interleaves ICorDebugInternalFrames
// with real stack frames strictly according to the frame address and the SP of the stack frames.
public sealed class CorStackWalkEx : CorStackWalk
{
internal CorStackWalkEx (ICorDebugStackWalk stackwalk, CorThread thread)
:base(stackwalk, thread)
{
m_internalFrameIndex = 0;
m_internalFrames = thread.GetActiveInternalFrames();
m_bEndOfStackFrame = false;
}
//
// IEnumerator interface
//
public override bool MoveNext()
{
// This variable is used to store the child frame we are currently skipping for. It's also
// used as a flag to indicate whether this method should return or continue to the next frame.
CorFrame childFrame = null;
bool bMoreToWalk = false;
while (true)
{
// Check to see if the frame we have just given back is a child frame.
if (m_init)
{
CorFrame prevFrame = this.Current;
if ((prevFrame != null) && prevFrame.IsChild)
{
childFrame = prevFrame;
}
}
bMoreToWalk = MoveNextWorker();
if (!bMoreToWalk)
{
// Unless there is a catastrophic failure, we should always find the parent frame for any
// child frame.
Debug.Assert(childFrame == null);
break;
}
if (childFrame != null)
{
// We are currently skipping frames due to a child frame.
// Check whether the current frame is the parent frame.
CorFrame currentFrame = this.Current;
if ((currentFrame != null) && childFrame.IsMatchingParentFrame(currentFrame))
{
// We have reached the parent frame. We should skip the parent frame as well, so clear
// childFrame and unwind to the caller of the parent frame. We will break out of the
// loop on the next iteration.
childFrame = null;
}
continue;
}
break;
}
return bMoreToWalk;
}
// This method handles internal frames but no child frames.
private bool MoveNextWorker()
{
if (m_bEndOfStackFrame)
{
return false;
}
bool fIsLeafFrame = false;
bool fIsFuncEvalFrame = false;
int hr;
if (m_init)
{
// this the 2nd or more call to MoveNext() and MoveNextWorker()
if ((m_frame != null) && (m_frame.FrameType == CorFrameType.InternalFrame))
{
// We have just handed out an internal frame, so we need to start looking at the next
// internal frame AND we don't call m_sw.Next() to preserve the previous managed frame
if (m_internalFrameIndex < m_internalFrames.Length)
{
m_internalFrameIndex++;
}
fIsFuncEvalFrame = (m_frame.InternalFrameType == CorDebugInternalFrameType.STUBFRAME_FUNC_EVAL);
hr = (int)HResult.S_OK;
}
else
{
// We just handed out a managed or native frame.
// In any case, use the managed unwinder to unwind.
hr = m_sw.Next();
// Check for end-of-stack condition.
if (hr == (int)HResult.CORDBG_S_AT_END_OF_STACK)
{
m_bEndOfStackFrame = true;
}
}
}
else
{
// this is the initial call to MoveNext() and MoveNextWorker() that validates the enumeration
// after we return from MoveNext(), .Current will point to the leaf-most frame
m_init = true;
fIsLeafFrame = true;
hr = (int)HResult.S_OK;
}
// Check for errors.
if (HRUtils.IsFailingHR(hr))
{
Marshal.ThrowExceptionForHR(hr);
}
if (!m_bEndOfStackFrame)
{
// Now we need to do a comparison between the current stack frame and the internal frame (if any)
// to figure out which one to give back first.
ICorDebugFrame frame;
m_sw.GetFrame(out frame);
if (frame == null)
{
// this represents native frame(s) to managed code, we return true because there may be more
// managed frames beneath
m_frame = null;
return true;
}
// we compare the current managed frame with the internal frame
CorFrame currentFrame = new CorFrame(frame);
for (; m_internalFrameIndex < m_internalFrames.Length; m_internalFrameIndex++)
{
CorFrame internalFrame = m_internalFrames[m_internalFrameIndex];
// Check for internal frame types which are not exposed in V2.
if (IsV3InternalFrameType(internalFrame))
{
continue;
}
if (internalFrame.IsCloserToLeaf(currentFrame))
{
currentFrame = internalFrame;
}
else if (internalFrame.InternalFrameType == CorDebugInternalFrameType.STUBFRAME_M2U)
{
// we need to look at the caller stack frame's SP
INativeContext ctx = this.GetContext();
CorStackWalk tStack = m_th.CreateStackWalk(CorStackWalkType.PureV3StackWalk);
CorDebugSetContextFlag flag = ((fIsFuncEvalFrame || fIsLeafFrame) ?
CorDebugSetContextFlag.SET_CONTEXT_FLAG_ACTIVE_FRAME :
CorDebugSetContextFlag.SET_CONTEXT_FLAG_UNWIND_FRAME);
tStack.SetContext(flag, ctx);
//tStack now points to the "previous" managed frame, not the managed frame we're looking at
//the first MoveNext call moves the temporary stackwalker to the "current" frame and the next
//MoveNext call moves the temporary stackwalker to the "caller" frame
Int64 current = 0, caller = 0;
if (tStack.MoveNext())
{
if (tStack.Current != null)
{
current = tStack.GetContext().StackPointer.ToInt64();
}
}
if (tStack.MoveNext())
{
if (tStack.Current != null)
{
caller = tStack.GetContext().StackPointer.ToInt64();
}
}
if (current == 0 || caller == 0)
{
//we've hit a native frame somewhere, we shouldn't be doing anything with this
break;
}
if (current < caller && internalFrame.IsCloserToLeaf(tStack.Current))
{
// if there is no caller frame or the current managed frame is closer to the leaf frame
// than the next managed frame on the stack (the caller frame), then we must be in the case
// where:
// [IL frame without metadata]
// [Internal frame, 'M --> U']
// Caller frame (managed)
// We need to flip the internal and IL frames, so we hand back the internal frame first
currentFrame = internalFrame;
}
}
break;
}
m_frame = currentFrame;
return true;
}
else
{
// We have reached the end of the managed stack.
// Check to see if we have any internal frames left.
for (; m_internalFrameIndex < m_internalFrames.Length; m_internalFrameIndex++)
{
CorFrame internalFrame = m_internalFrames[m_internalFrameIndex];
if (IsV3InternalFrameType(internalFrame))
{
continue;
}
m_frame = internalFrame;
return true;
}
return false;
}
}
public override void Reset()
{
// There is no way to reset. Just create a new one.
CorStackWalk s = m_th.CreateStackWalk(CorStackWalkType.ExtendedV3StackWalk);
m_sw = s.GetInterface();
m_frame = null;
}
private static bool IsV3InternalFrameType(CorFrame internalFrame)
{
// CorStackWalkEx wants to expose V2 behaviour. The following frame types are new in V3.
// This function checks whether the specified internal frame is a V3 frame type and returns
// true if it is. CorStackWalkEx uses this function to decide whether it should expose
// an internal frame.
CorDebugInternalFrameType type = internalFrame.InternalFrameType;
if ((type == CorDebugInternalFrameType.STUBFRAME_INTERNALCALL) ||
(type == CorDebugInternalFrameType.STUBFRAME_CLASS_INIT) ||
(type == CorDebugInternalFrameType.STUBFRAME_EXCEPTION) ||
(type == CorDebugInternalFrameType.STUBFRAME_SECURITY) ||
(type == CorDebugInternalFrameType.STUBFRAME_JIT_COMPILATION))
{
return true;
}
else
{
return false;
}
}
private CorFrame[] m_internalFrames;
private uint m_internalFrameIndex;
private bool m_bEndOfStackFrame;
} /* class StackWalk Thread */
} /* namespace */
| |
/*
* Inspired from 2009 The Android Open Source Project
* Bluetooth chat
*/
using System;
using System.Collections.Generic;
using Android.App;
using Android.Bluetooth;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace Tetrim
{
[Activity(ScreenOrientation = ScreenOrientation.Portrait)]
public class BluetoothConnectionActivity : Activity, ViewTreeObserver.IOnGlobalLayoutListener
{
//--------------------------------------------------------------
// CONSTANTS
//--------------------------------------------------------------
// Debugging
private const string Tag = "BluetoothConnectionActivity";
// Return Intent extra
public const string ExtraDeviceAddress = "device_address";
private const int NbDevicesDisplayed = 6;
private const TetrisColor FriendsDeviceColor = TetrisColor.Magenta;
private const TetrisColor PairedDeviceColor = TetrisColor.Green;
private const TetrisColor NewDeviceColor = TetrisColor.Cyan;
private enum Menu
{
FRIENDS,
PAIRED,
NEW
};
//--------------------------------------------------------------
// ATTRIBUTES
//--------------------------------------------------------------
private BluetoothAdapter _bluetoothAdapter = null;
private List<BluetoothDevice> _friendsDevices = new List<BluetoothDevice>();
private List<BluetoothDevice> _pairedDevices = new List<BluetoothDevice>();
private List<BluetoothDevice> _newDevices = new List<BluetoothDevice>();
private Receiver _receiver;
private Network.StartState _state = Network.StartState.NONE;
private bool _isConnectionInitiator = false;
private string _opponentName = String.Empty;
private Menu _menuSelected = Menu.PAIRED;
private ScrollView _devicesLayout;
private LinearLayout _friendsDevicesLayout, _pairedDevicesLayout, _newDevicesLayout;
private ButtonStroked _friendsDevicesButton, _pairedDevicesButton, _newDevicesButton;
private ProgressBar _progressBar;
//--------------------------------------------------------------
// EVENT CATCHING OVERRIDE
//--------------------------------------------------------------
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Setup the window
RequestWindowFeature(WindowFeatures.IndeterminateProgress);
SetContentView(Resource.Layout.BluetoothConnection);
// Set result CANCELED incase the user backs out
SetResult(Result.Canceled);
// Initialize the buttons
UtilsUI.SetDeviceMenuButton(this, ref _friendsDevicesButton, Resource.Id.friendsDevices, FriendsDeviceColor);
_friendsDevicesButton.Click += (sender, e) => SwitchMenu (Menu.FRIENDS);
UtilsUI.SetDeviceMenuButton(this, ref _pairedDevicesButton, Resource.Id.pairedDevices, PairedDeviceColor);
_pairedDevicesButton.Click += (sender, e) => SwitchMenu (Menu.PAIRED);
UtilsUI.SetDeviceMenuButton(this, ref _newDevicesButton, Resource.Id.newDevices, NewDeviceColor);
_newDevicesButton.Click += (sender, e) => {
SwitchMenu(Menu.NEW);
startDiscovery();
};
// Create the layouts
_devicesLayout = FindViewById<ScrollView>(Resource.Id.devicesLayout);
UtilsUI.SetDeviceMenuLayout(this, ref _friendsDevicesLayout, NbDevicesDisplayed);
UtilsUI.SetDeviceMenuLayout(this, ref _pairedDevicesLayout, NbDevicesDisplayed);
UtilsUI.SetDeviceMenuLayout(this, ref _newDevicesLayout, NbDevicesDisplayed);
SwitchMenu(Menu.FRIENDS);
// Test if the view is created so we can resize the buttons
if(_devicesLayout.ViewTreeObserver.IsAlive)
{
_devicesLayout.ViewTreeObserver.AddOnGlobalLayoutListener(this);
}
}
public void OnGlobalLayout()
{
// The view is completely loaded now, so Height won't return 0
// Register for broadcasts when a device is discovered
_receiver = new Receiver(this);
var filter = new IntentFilter(BluetoothDevice.ActionFound);
RegisterReceiver(_receiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ActionDiscoveryFinished);
RegisterReceiver(_receiver, filter);
if(Network.Instance.TryEnablingBluetooth(this) == Network.ResultEnabling.Enabled)
{
actualizeView();
}
// Hook on the Network event
Network.Instance.EraseAllEvent();
Network.Instance.DeviceNameEvent += NameReceived;
Network.Instance.ReadEvent += ReadMessageEventReceived;
Network.Instance.StateConnectedEvent += StateConnectedEventReceived;
Network.Instance.StateConnectingEvent += StateConnectingEventReceived;
Network.Instance.StateNoneEvent += StateNoneEventReceived;
Network.Instance.WriteEvent += WriteMessageEventReceived;
Network.Instance.StartMessage += StartGameMessageReceived;
// Destroy the onGlobalLayout afterwards, otherwise it keeps changing
// the sizes non-stop, even though it's already done
_devicesLayout.ViewTreeObserver.RemoveGlobalOnLayoutListener(this);
}
protected override void OnDestroy()
{
Utils.RemoveBitmapsOfButtonStroked(FindViewById<ViewGroup>(Resource.Id.rootBluetoothConnection));
base.OnDestroy();
// Make sure we're not doing discovery anymore
if(_bluetoothAdapter != null)
{
_bluetoothAdapter.CancelDiscovery();
}
// Unregister broadcast listeners
UnregisterReceiver(_receiver);
// Stop the Bluetooth Manager
if (Network.Instance.Enabled)
Network.Instance.Stop ();
#if DEBUG
Log.Error (Tag, "--- ON DESTROY ---");
#endif
}
protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
#if DEBUG
Log.Debug(Tag, "onActivityResult " + resultCode);
#endif
if(requestCode == (int) Utils.RequestCode.RequestGameTwoPlayer)
{
if(resultCode == Result.FirstUser)
{
// We want to restart a game
MenuActivity.startTwoPlayerGame(this, _opponentName); // We launch the game (change view and everything)
}
else
{
// We end this activity after the game so we come back on the menu screen
Finish();
}
}
// The request code is tested in ResultBluetoothActivation
if(Network.Instance.ResultBluetoothActivation(requestCode, resultCode, this))
{
actualizeView();
}
}
//--------------------------------------------------------------
// DEVICES
//--------------------------------------------------------------
public void AddNewDevice(BluetoothDevice device)
{
if(device != null)
{
_newDevices.Add(device);
}
ButtonStroked newDeviceButton = UtilsUI.CreateDeviceButton(this, device, NewDeviceColor, (int)(_devicesLayout.Height*1f/NbDevicesDisplayed), Resource.String.none_found);
LinearLayout.LayoutParams lp = UtilsUI.CreateDeviceLayoutParams(this, 5);
_newDevicesLayout.AddView(newDeviceButton, _newDevicesLayout.ChildCount - 1, lp);
}
public void AddFriendDevice(BluetoothDevice device, string name)
{
if(device != null)
{
_friendsDevices.Add(device);
}
ButtonStroked friendsDeviceButton = UtilsUI.CreateDeviceButton(this, device, FriendsDeviceColor, (int)(_devicesLayout.Height*1f/NbDevicesDisplayed), name);
LinearLayout.LayoutParams lp = UtilsUI.CreateDeviceLayoutParams(this, 5);
_friendsDevicesLayout.AddView(friendsDeviceButton, lp);
}
public void AddPairedDevice(BluetoothDevice device)
{
if(device != null)
{
_pairedDevices.Add(device);
}
ButtonStroked pairedDeviceButton = UtilsUI.CreateDeviceButton(this, device, PairedDeviceColor, (int)(_devicesLayout.Height*1f/NbDevicesDisplayed), Resource.String.none_paired);
LinearLayout.LayoutParams lp = UtilsUI.CreateDeviceLayoutParams(this, 5);
_pairedDevicesLayout.AddView(pairedDeviceButton, lp);
}
//--------------------------------------------------------------
// MENU BEHAVIOUR
//--------------------------------------------------------------
private void SwitchMenu(Menu chosenMenu)
{
this._menuSelected = chosenMenu;
switch(this._menuSelected)
{
case Menu.FRIENDS:
DisableMenuCategory(_pairedDevicesLayout, _pairedDevicesButton);
DisableMenuCategory(_newDevicesLayout, _newDevicesButton);
_newDevicesLayout.RemoveAllViews();
EnableMenuCategory(_friendsDevicesLayout, _friendsDevicesButton);
break;
case Menu.PAIRED:
DisableMenuCategory(_friendsDevicesLayout, _friendsDevicesButton);
DisableMenuCategory(_newDevicesLayout, _newDevicesButton);
_newDevicesLayout.RemoveAllViews();
EnableMenuCategory(_pairedDevicesLayout, _pairedDevicesButton);
break;
case Menu.NEW:
DisableMenuCategory(_friendsDevicesLayout, _friendsDevicesButton);
DisableMenuCategory(_pairedDevicesLayout, _pairedDevicesButton);
EnableMenuCategory(_newDevicesLayout, _newDevicesButton);
break;
}
}
private void EnableMenuCategory(LinearLayout layout, ButtonStroked button)
{
_devicesLayout.AddView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent));
button.Selected = true;
button.Clickable = false;
}
private void DisableMenuCategory(LinearLayout layout, ButtonStroked button)
{
_devicesLayout.RemoveView(layout);
button.Selected = false;
button.Clickable = true;
}
//--------------------------------------------------------------
// NETWORK METHODS
//--------------------------------------------------------------
public int WriteMessageEventReceived(byte[] writeBuf)
{
#if DEBUG
Log.Debug(Tag, "MessageType = write");
#endif
if(writeBuf[0] == Constants.IdMessageStart && _state == Network.StartState.OPPONENT_READY)
{
User.Instance.AddFriend(Network.Instance.CommunicationWay._deviceAddress, _opponentName);
MenuActivity.startTwoPlayerGame(this, _opponentName);
}
return 0;
}
public int ReadMessageEventReceived(byte[] readBuf)
{
var message = new Java.Lang.String (readBuf);
#if DEBUG
Log.Debug(Tag, "MessageType = read, " + message);
#endif
return 0;
}
public int StateConnectingEventReceived()
{
#if DEBUG
Log.Debug(Tag, "State = connecting");
#endif
_isConnectionInitiator = true;
return 0;
}
public int StateConnectedEventReceived()
{
#if DEBUG
Log.Debug(Tag, "State = connected");
#endif
// No need to continue the discovery now that we are connected
if(_bluetoothAdapter.IsDiscovering)
{
_bluetoothAdapter.CancelDiscovery();
}
// Send the name of the user anyway
SendNameMessage();
if(_isConnectionInitiator)
{
// Send a request to start a game
SendStartGameMessage();
}
else
{
// Dislay a pop-up telling that there is a connection which was made with someone
// The pop-up is closed as soon as we received a StartGameMessage
displayWaitingDialog(Resource.String.connection_in_progress);
}
return 0;
}
public int StateNoneEventReceived()
{
#if DEBUG
Log.Debug(Tag, "State = none");
#endif
// To avoid infinite loop because this function can throw a StateNoneEvent
Network.Instance.StateNoneEvent -= StateNoneEventReceived;
_isConnectionInitiator = false;
_state = Network.StartState.NONE;
// if the connection fail we remove the pop-up and restart the bluetooth
DialogActivity.CloseAll();
Network.Instance.CommunicationWay.Start();
if(Network.Instance.CommunicationWay.State == BluetoothManager.StateEnum.None)
{
// if the bluetooth is still disabled, we need to stop
Finish();
}
Network.Instance.StateNoneEvent += StateNoneEventReceived;
return 0;
}
public int StartGameMessageReceived(byte[] message)
{
// close the pop-up in all the case
DialogActivity.CloseAll();
// We have recieve a demand to start the game
// We verify that the two player have the same version of the application
if(message[1] == Constants.NumVersion)
{
// The 2 players have the same version, we can launch the game if we are ready
if(_state == Network.StartState.WAITING_FOR_OPPONENT)
{
User.Instance.AddFriend(Network.Instance.CommunicationWay._deviceAddress, _opponentName);
MenuActivity.startTwoPlayerGame(this, _opponentName);
}
else
{
// if we are not ready, display a pop-up asking if we want to play with this person
_state = Network.StartState.OPPONENT_READY;
// Display a pop-up asking if we want to play now that we are connected and the opponent is ready
Intent dialog = DialogActivity.CreateYesNoDialog(this, Resources.GetString(Resource.String.game_request_title),
String.Format(Resources.GetString(Resource.String.game_request), _opponentName),
delegate{SendStartGameMessage();}, delegate{CancelConnection();});
StartActivity(dialog);
}
}
else
{
Intent dialog = UtilsDialog.CreateBluetoothDialogNoCancel(this, Resource.String.wrong_version);
StartActivity(dialog);
Network.Instance.CommunicationWay.Start(); // We restart the connection
}
return 0;
}
public void SendStartGameMessage()
{
byte[] message = {Constants.IdMessageStart, Constants.NumVersion};
// We notify the opponent that we are ready
Network.Instance.CommunicationWay.Write(message);
if(_state != Network.StartState.OPPONENT_READY)
{
_state = Network.StartState.WAITING_FOR_OPPONENT;
displayWaitingDialog(Resource.String.waiting_for_opponent);
}
}
public void SendNameMessage()
{
byte[] message = new byte[Constants.SizeMessage[Constants.IdMessageName]];
message[0] = Constants.IdMessageName;
char[] smallName = User.Instance.UserName.ToCharArray();
char[] name = new char[Constants.MaxLengthName]; // the array is already initialized with the default value which is '\0'
Buffer.BlockCopy(smallName, 0, name, 0, sizeof(char)*smallName.Length);
for(int i = 0; i < name.Length; i++)
{
Utils.AddByteArrayToOverArray(ref message, BitConverter.GetBytes(name[i]), 1 + i*sizeof(char));
}
Network.Instance.CommunicationWay.Write(message);
}
public int NameReceived(string name)
{
_opponentName = name;
return 0;
}
public void FinishDiscovery()
{
// Remove the progress bar
_newDevicesLayout.RemoveView(_progressBar);
// Display if no device found
if(_newDevices.Count == 0)
{
AddNewDevice(null);
}
}
public void CancelConnection()
{
#if DEBUG
Log.Debug(Tag, "CancelConnection()");
#endif
_state = Network.StartState.NONE;
_isConnectionInitiator = false;
DialogActivity.CloseAll();
Network.Instance.CommunicationWay.Start();
}
// The on-click listener for all devices in the ListViews
public void DeviceListClick(ButtonStroked sender)
{
if(_bluetoothAdapter.IsDiscovering)
{
// Cancel discovery because it's costly and we're about to connect
_bluetoothAdapter.CancelDiscovery();
}
// Get the device MAC address, which is the last 17 chars in the View
//string info = (sender).Text;
string address = (sender).Tag.ToString();
if(Network.Instance.Enabled)
{
displayWaitingDialog(Resource.String.waiting_for_opponent);
// Get the BLuetoothDevice object
BluetoothDevice device = BluetoothAdapter.DefaultAdapter.GetRemoteDevice(address);
// Attempt to connect to the device
Network.Instance.CommunicationWay.Connect(device);
}
}
//--------------------------------------------------------------
// PRIVATE METHODS
//--------------------------------------------------------------
private void actualizeView()
{
// Get the local Bluetooth adapter
_bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
// Get a set of currently paired devices
ICollection<BluetoothDevice> pairedDevices = _bluetoothAdapter.BondedDevices;
// If there are paired devices, add each one to the ArrayAdapter
if(pairedDevices.Count > 0)
{
_pairedDevices.Clear();
string name;
foreach(BluetoothDevice device in pairedDevices)
{
if(User.Instance.Friends.TryGetValue(device.Address, out name))
{
AddFriendDevice(device, name);
}
AddPairedDevice(device);
}
}
else
{
AddPairedDevice(null);
}
if(_friendsDevices.Count == 0)
{
AddFriendDevice(null, Resources.GetString(Resource.String.none_friend));
}
}
private void displayWaitingDialog(int idMessage)
{
DialogActivity.CloseAll();
Intent dialog = DialogActivity.CreateYesNoDialog(this, idMessage, -1,
Resource.String.cancel, -1, delegate{CancelConnection();}, null);
StartActivity(dialog);
}
// Start device discover with the BluetoothAdapter
private void startDiscovery()
{
#if DEBUG
Log.Debug(Tag, "doDiscovery()");
#endif
_progressBar = new ProgressBar(this);
_progressBar.Indeterminate = true;
int padding = Utils.GetPixelsFromDP(this, 15);
_progressBar.SetPadding(padding, padding, padding, padding);
_newDevicesLayout.SetGravity(GravityFlags.CenterHorizontal);
_newDevicesLayout.AddView(_progressBar, (int)(_devicesLayout.Height*1f/NbDevicesDisplayed), (int)(_devicesLayout.Height*1f/NbDevicesDisplayed));
// If we're already discovering, stop it
if(_bluetoothAdapter.IsDiscovering)
{
_bluetoothAdapter.CancelDiscovery();
}
// Request discover from BluetoothAdapter
_bluetoothAdapter.StartDiscovery();
}
}
}
| |
#region License
/**
* Copyright (c) 2010-2012 Lightning Development Studios <lightningdevelopmentstudios@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System;
using OpenTK.Graphics.OpenGL;
namespace CircuitCrawlerEditor.Models
{
/// <summary>
/// Automatically generated vertex data for model "SpikeWall.obj".
/// </summary>
public static class SpikeWallData
{
/// <summary>
/// The number of vertices in the vertex array.
/// </summary>
private const int vertexCount = 40;
/// <summary>
/// The number of floats in the vertex array.
/// </summary>
private const int vertexFloatCount = 320;
/// <summary>
/// The number of bytes in the vertex array.
/// </summary>
private const int vertexByteCount = 1280;
/// <summary>
/// The number of indices in the index array.
/// </summary>
private const int indexCount = 96;
/// <summary>
/// The number of bytes in the index array.
/// </summary>
private const int indexByteCount = 192;
/// <summary>
/// Vertex data.
/// </summary>
private static readonly float[] vertices =
{
-36f, 6.686293f, 6.686293f, 0.169922f, 0.998047f, 0.21693f, -0.690269f, -0.690268f,
-36f, 2.000002f, 18f, 0.251953f, 0.998047f, 0.21693f, -0.976187f, 0f,
36f, 18f, 18f, 0.498047f, 0.001953006f, 1f, 0f, 0f,
-36f, 6.686293f, 29.31371f, 0.333984f, 0.998047f, 0.21693f, -0.690269f, 0.690269f,
-36f, 18f, 34f, 0.416016f, 0.998047f, 0.21693f, 0f, 0.976187f,
-36f, 29.31371f, 29.31371f, 0.498047f, 0.998047f, 0.21693f, 0.690268f, 0.690269f,
-36f, 34f, 18f, 0.583984f, 0.998047f, 0.21693f, 0.976187f, 0f,
-36f, 29.31371f, 6.686292f, 0.666016f, 0.998047f, 0.21693f, 0.690269f, -0.690269f,
-36f, 18f, 2f, 0.748047f, 0.998047f, 0.21693f, 0f, -0.976187f,
-36f, 6.686293f, 6.686293f, 0.830078f, 0.998047f, 0.21693f, -0.690269f, -0.690268f,
-36f, -31.31371f, 6.686293f, 0.169922f, 0.998047f, 0.21693f, -0.690269f, -0.690268f,
-36f, -36f, 18f, 0.251953f, 0.998047f, 0.21693f, -0.976187f, 0f,
36f, -20f, 18f, 0.498047f, 0.001953006f, 1f, 0f, 0f,
-36f, -31.31371f, 29.31371f, 0.333984f, 0.998047f, 0.21693f, -0.690269f, 0.690269f,
-36f, -20f, 34f, 0.416016f, 0.998047f, 0.21693f, 0f, 0.976187f,
-36f, -8.686293f, 29.31371f, 0.498047f, 0.998047f, 0.21693f, 0.690268f, 0.690269f,
-36f, -4.000001f, 18f, 0.583984f, 0.998047f, 0.21693f, 0.976187f, 0f,
-36f, -8.686292f, 6.686292f, 0.666016f, 0.998047f, 0.21693f, 0.690269f, -0.690269f,
-36f, -20f, 2f, 0.748047f, 0.998047f, 0.21693f, 0f, -0.976187f,
-36f, -31.31371f, 6.686293f, 0.830078f, 0.998047f, 0.21693f, -0.690269f, -0.690268f,
-36f, 6.686293f, 44.68629f, 0.169922f, 0.998047f, 0.21693f, -0.690269f, -0.690268f,
-36f, 2.000002f, 56f, 0.251953f, 0.998047f, 0.21693f, -0.976187f, 0f,
36f, 18f, 56f, 0.498047f, 0.001953006f, 1f, 0f, 0f,
-36f, 6.686293f, 67.31371f, 0.333984f, 0.998047f, 0.21693f, -0.690269f, 0.690269f,
-36f, 18f, 72f, 0.416016f, 0.998047f, 0.21693f, 0f, 0.976187f,
-36f, 29.31371f, 67.31371f, 0.498047f, 0.998047f, 0.21693f, 0.690268f, 0.690269f,
-36f, 34f, 56f, 0.583984f, 0.998047f, 0.21693f, 0.976187f, 0f,
-36f, 29.31371f, 44.68629f, 0.666016f, 0.998047f, 0.21693f, 0.690269f, -0.690269f,
-36f, 18f, 40f, 0.748047f, 0.998047f, 0.21693f, 0f, -0.976187f,
-36f, 6.686293f, 44.68629f, 0.830078f, 0.998047f, 0.21693f, -0.690269f, -0.690268f,
-36f, -31.31371f, 44.68629f, 0.169922f, 0.998047f, 0.21693f, -0.690269f, -0.690268f,
-36f, -36f, 56f, 0.251953f, 0.998047f, 0.21693f, -0.976187f, 0f,
36f, -20f, 56f, 0.498047f, 0.001953006f, 1f, 0f, 0f,
-36f, -31.31371f, 67.31371f, 0.333984f, 0.998047f, 0.21693f, -0.690269f, 0.690269f,
-36f, -20f, 72f, 0.416016f, 0.998047f, 0.21693f, 0f, 0.976187f,
-36f, -8.686293f, 67.31371f, 0.498047f, 0.998047f, 0.21693f, 0.690268f, 0.690269f,
-36f, -4.000001f, 56f, 0.583984f, 0.998047f, 0.21693f, 0.976187f, 0f,
-36f, -8.686292f, 44.68629f, 0.666016f, 0.998047f, 0.21693f, 0.690269f, -0.690269f,
-36f, -20f, 40f, 0.748047f, 0.998047f, 0.21693f, 0f, -0.976187f,
-36f, -31.31371f, 44.68629f, 0.830078f, 0.998047f, 0.21693f, -0.690269f, -0.690268f,
};
/// <summary>
/// Index data.
/// </summary>
private static readonly ushort[] indices =
{
0, 1, 2,
1, 3, 2,
3, 4, 2,
4, 5, 2,
5, 6, 2,
6, 7, 2,
7, 8, 2,
8, 9, 2,
10, 11, 12,
11, 13, 12,
13, 14, 12,
14, 15, 12,
15, 16, 12,
16, 17, 12,
17, 18, 12,
18, 19, 12,
20, 21, 22,
21, 23, 22,
23, 24, 22,
24, 25, 22,
25, 26, 22,
26, 27, 22,
27, 28, 22,
28, 29, 22,
30, 31, 32,
31, 33, 32,
33, 34, 32,
34, 35, 32,
35, 36, 32,
36, 37, 32,
37, 38, 32,
38, 39, 32,
};
/// <summary>
/// A VBO handle for vertices.
/// </summary>
private static int vertVbo;
/// <summary>
/// A VBO handle for indices.
/// </summary>
private static int indVbo;
/// <summary>
/// Gets a VBO that contains the vertex data for the model SpikeWall.obj.
/// </summary>
/// <returns>A VBO handle.</returns>
public static int GetVertexBufferID()
{
if (vertVbo == 0)
{
GL.GenBuffers(1, out vertVbo);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertVbo);
GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)vertexByteCount, vertices, BufferUsageHint.StaticDraw);
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
}
return vertVbo;
}
/// <summary>
/// Gets a VBO that contains the index data for the model SpikeWall.obj.
/// </summary>
/// <returns>A VBO handle.</returns>
public static int GetIndexBufferID()
{
if (indVbo == 0)
{
GL.GenBuffers(1, out indVbo);
GL.BindBuffer(BufferTarget.ArrayBuffer, indVbo);
GL.BufferData<ushort>(BufferTarget.ArrayBuffer, (IntPtr)indexByteCount, indices, BufferUsageHint.StaticDraw);
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
}
return indVbo;
}
/// <summary>
/// Gets the number of indices.
/// </summary>
/// <returns>The number of indices.</returns>
public static int GetIndexCount()
{
return indexCount;
}
/// <summary>
/// Unloads the model data from the VBO.
/// </summary>
public static void Unload()
{
int[] buffers = new int[] { vertVbo, indVbo };
GL.DeleteBuffers(2, buffers);
vertVbo = 0;
indVbo = 0;
}
}
}
| |
using System.Collections.Generic;
using BIRA_Issue_Tracker.Models;
using BIRA_Issue_Tracker.Models.Identity;
using BIRA_Issue_Tracker.Models.IssueTracker;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace BIRA_Issue_Tracker.Migrations
{
using System;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<IssueTrackerDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
ContextKey = "BIRA_Issue_Tracker.Models.IssueTrackerDbContext";
}
protected override void Seed(IssueTrackerDbContext db)
{
if (!db.Users.Any())
{
CreateUser(db, "admin@gmail.com", "123", "Vladi Admina");
CreateUser(db, "gosho@gmail.com", "123", "George Petrov");
CreateUser(db, "pesho@gmail.com", "123", "Peter Ivanov");
CreateUser(db, "merry@gmail.com", "123", "Maria Petrova");
CreateRole(db, "Administrators");
AddUserToRole(db, "admin@gmail.com", "Administrators");
}
db.SaveChanges();
if (!db.Issues.Any())
{
CreateIssue(db,
"HTTP 400 error",
"Adding an author with incorrect date format will return an HTTP 400 response code.",
State.Open,
"admin@gmail.com",
"gosho@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "user input"),
FindTagByName(db, "network"),
FindTagByName(db, "date"),
FindTagByName(db, "HTTP 400"),
FindTagByName(db, "author"),
}
);
CreateIssue(db,
"\'00\' birthday causes exception",
"Adding an author with a birth date which has day 00 will add the author with a birth date of the last day of the previous month",
State.Open,
"pesho@gmail.com",
"merry@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "birth date"),
FindTagByName(db, "form"),
FindTagByName(db, "error"),
FindTagByName(db, "input validation"),
}
);
CreateIssue(db,
"negative birthday causes exception",
"Adding an author with a birth date the day of which is negative will add the author with a birth date which is the same but the day is non negative",
State.Open,
"merry@gmail.com",
"gosho@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "birthday"),
FindTagByName(db, "error"),
FindTagByName(db, "input validation"),
}
);
CreateIssue(db,
"no last name causes exception",
"Adding an author with a valid first name and date, but no last name throws an unhandled exception \"Last name out of range\" insteaof validating the input before sending it.",
State.Open,
"gosho@gmail.com",
"admin@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "form"),
FindTagByName(db, "last name"),
FindTagByName(db, "date"),
}
);
CreateIssue(db,
"missing first name causes exception",
"Adding an author with a valid last name and date, but no first name throws an unhandled exception \"First name out of range\" instead of validating the input before sending it.",
State.Open,
"pesho@gmail.com",
"gosho@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "form"),
FindTagByName(db, "last name"),
FindTagByName(db, "date"),
}
);
CreateIssue(db,
"short first name causes exception",
"If first name is too short, the system throws an unhandled exception \"First name out of range\" instead of validating the input before sending it.",
State.Open,
"admin@gmail.com",
"admin@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "first name"),
FindTagByName(db, "error"),
FindTagByName(db, "form"),
}
);
CreateIssue(db,
"short last name causes exception",
"If last name is too short, the system throws an unhandled exception \"Last name out of range\" instead of validating the input before sending it.",
State.Open,
"merry@gmail.com",
"gosho@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "last name"),
FindTagByName(db, "error"),
FindTagByName(db, "form"),
}
);
CreateIssue(db,
"Wrong first name upper limit",
"First name upper limit is 239 characters instead of 240",
State.Open,
"merry@gmail.com",
"admin@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "back end"),
FindTagByName(db, "form"),
FindTagByName(db, "error"),
}
);
CreateIssue(db,
"Wrong last name upper limit",
"Last name upper limit is 237 characters instead of 240",
State.Open,
"gosho@gmail.com",
"gosho@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "back end"),
FindTagByName(db, "form"),
FindTagByName(db, "error"),
}
);
CreateIssue(db,
"Tags don't work",
"Last name upper limit is 237 characters instead of 240",
State.Open,
"gosho@gmail.com",
"gosho@gmail.com",
new SortedSet<Tag>
{
FindTagByName(db, "back end"),
FindTagByName(db, "form"),
FindTagByName(db, "error"),
}
);
}
db.SaveChanges();
}
private static Tag FindTagByName(IssueTrackerDbContext db, string name)
{
var foundTag = db.Tags.FirstOrDefault(t => t.Name == name);
if (foundTag == null)
{
var newTag = new Tag(name);
db.Tags.Add(newTag);
db.SaveChanges();
return db.Tags.FirstOrDefault(t => t.Name == newTag.Name);
}
return foundTag;
}
private static void CreateUser(IssueTrackerDbContext db,
string email, string password, string fullName)
{
var userManager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(db))
{
PasswordValidator = new PasswordValidator
{
RequiredLength = 1,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
}
};
var user = new ApplicationUser
{
UserName = email,
Email = email,
FullName = fullName
};
var userCreateResult = userManager.Create(user, password);
if (!userCreateResult.Succeeded)
{
throw new Exception(string.Join("; ", userCreateResult.Errors));
}
}
private static void CreateIssue(IssueTrackerDbContext db, string title, string description, State state,
string author, string assignee, ISet<Tag> tags)
{
var authorAsUser = db.Users.FirstOrDefault(u => u.UserName == author);
var assigneeAsUser = db.Users.FirstOrDefault(u => u.UserName == assignee);
var issue = new Issue
{
Title = title,
Description = description,
State = state,
Author = authorAsUser,
Assignee = assigneeAsUser,
Date = DateTime.Now,
Tags = tags
};
db.Issues.Add(issue);
//var issueInDatabase = db.Issues.Find(issue.Id);
//foreach (var tag in tags)
//{
// issueInDatabase.Tags.Add(tag);
//}
}
private void CreateRole(IssueTrackerDbContext db, string roleName)
{
var roleManager = new RoleManager<IdentityRole>(
new RoleStore<IdentityRole>(db));
var roleCreateResult = roleManager.Create(new IdentityRole(roleName));
if (!roleCreateResult.Succeeded)
{
throw new Exception(string.Join("; ", roleCreateResult.Errors));
}
}
private static void AddUserToRole(IssueTrackerDbContext db, string userName, string roleName)
{
var user = db.Users.First(u => u.UserName == userName);
var userManager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(db));
var addAdminRoleResult = userManager.AddToRole(user.Id, roleName);
if (!addAdminRoleResult.Succeeded)
{
throw new Exception(string.Join("; ", addAdminRoleResult.Errors));
}
}
}
}
| |
using System.Diagnostics;
namespace Lucene.Net.Codecs
{
/*
* 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 IndexOutput = Lucene.Net.Store.IndexOutput;
using MathUtil = Lucene.Net.Util.MathUtil;
using RAMOutputStream = Lucene.Net.Store.RAMOutputStream;
/// <summary>
/// This abstract class writes skip lists with multiple levels.
///
/// <code>
///
/// Example for skipInterval = 3:
/// c (skip level 2)
/// c c c (skip level 1)
/// x x x x x x x x x x (skip level 0)
/// d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d (posting list)
/// 3 6 9 12 15 18 21 24 27 30 (df)
///
/// d - document
/// x - skip data
/// c - skip data with child pointer
///
/// Skip level i contains every skipInterval-th entry from skip level i-1.
/// Therefore the number of entries on level i is: floor(df / ((skipInterval ^ (i + 1))).
///
/// Each skip entry on a level i>0 contains a pointer to the corresponding skip entry in list i-1.
/// this guarantees a logarithmic amount of skips to find the target document.
///
/// While this class takes care of writing the different skip levels,
/// subclasses must define the actual format of the skip data.
/// </code>
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class MultiLevelSkipListWriter
{
/// <summary>
/// Number of levels in this skip list. </summary>
protected internal int m_numberOfSkipLevels;
/// <summary>
/// The skip interval in the list with level = 0. </summary>
private int skipInterval;
/// <summary>
/// SkipInterval used for level > 0. </summary>
private int skipMultiplier;
/// <summary>
/// For every skip level a different buffer is used. </summary>
private RAMOutputStream[] skipBuffer;
/// <summary>
/// Creates a <see cref="MultiLevelSkipListWriter"/>. </summary>
protected MultiLevelSkipListWriter(int skipInterval, int skipMultiplier, int maxSkipLevels, int df)
{
this.skipInterval = skipInterval;
this.skipMultiplier = skipMultiplier;
// calculate the maximum number of skip levels for this document frequency
if (df <= skipInterval)
{
m_numberOfSkipLevels = 1;
}
else
{
m_numberOfSkipLevels = 1 + MathUtil.Log(df / skipInterval, skipMultiplier);
}
// make sure it does not exceed maxSkipLevels
if (m_numberOfSkipLevels > maxSkipLevels)
{
m_numberOfSkipLevels = maxSkipLevels;
}
}
/// <summary>
/// Creates a <see cref="MultiLevelSkipListWriter"/>, where
/// <see cref="skipInterval"/> and <see cref="skipMultiplier"/> are
/// the same.
/// </summary>
protected MultiLevelSkipListWriter(int skipInterval, int maxSkipLevels, int df)
: this(skipInterval, skipInterval, maxSkipLevels, df)
{
}
/// <summary>
/// Allocates internal skip buffers. </summary>
protected virtual void Init()
{
skipBuffer = new RAMOutputStream[m_numberOfSkipLevels];
for (int i = 0; i < m_numberOfSkipLevels; i++)
{
skipBuffer[i] = new RAMOutputStream();
}
}
/// <summary>
/// Creates new buffers or empties the existing ones. </summary>
public virtual void ResetSkip()
{
if (skipBuffer == null)
{
Init();
}
else
{
for (int i = 0; i < skipBuffer.Length; i++)
{
skipBuffer[i].Reset();
}
}
}
/// <summary>
/// Subclasses must implement the actual skip data encoding in this method.
/// </summary>
/// <param name="level"> The level skip data shall be writing for. </param>
/// <param name="skipBuffer"> The skip buffer to write to. </param>
protected abstract void WriteSkipData(int level, IndexOutput skipBuffer);
/// <summary>
/// Writes the current skip data to the buffers. The current document frequency determines
/// the max level is skip data is to be written to.
/// </summary>
/// <param name="df"> The current document frequency. </param>
/// <exception cref="System.IO.IOException"> If an I/O error occurs. </exception>
public virtual void BufferSkip(int df)
{
Debug.Assert(df % skipInterval == 0);
int numLevels = 1;
df /= skipInterval;
// determine max level
while ((df % skipMultiplier) == 0 && numLevels < m_numberOfSkipLevels)
{
numLevels++;
df /= skipMultiplier;
}
long childPointer = 0;
for (int level = 0; level < numLevels; level++)
{
WriteSkipData(level, skipBuffer[level]);
long newChildPointer = skipBuffer[level].GetFilePointer();
if (level != 0)
{
// store child pointers for all levels except the lowest
skipBuffer[level].WriteVInt64(childPointer);
}
//remember the childPointer for the next level
childPointer = newChildPointer;
}
}
/// <summary>
/// Writes the buffered skip lists to the given output.
/// </summary>
/// <param name="output"> The <see cref="IndexOutput"/> the skip lists shall be written to. </param>
/// <returns> The pointer the skip list starts. </returns>
public virtual long WriteSkip(IndexOutput output)
{
long skipPointer = output.GetFilePointer();
//System.out.println("skipper.writeSkip fp=" + skipPointer);
if (skipBuffer == null || skipBuffer.Length == 0)
{
return skipPointer;
}
for (int level = m_numberOfSkipLevels - 1; level > 0; level--)
{
long length = skipBuffer[level].GetFilePointer();
if (length > 0)
{
output.WriteVInt64(length);
skipBuffer[level].WriteTo(output);
}
}
skipBuffer[0].WriteTo(output);
return skipPointer;
}
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Rotorz.Tile.Editor
{
/// <exclude/>
[InitializeOnLoad]
public static class AssetPreviewCache
{
private const string LibraryRelativePreviewCacheFolderPath = "Library/Rotorz/PreviewCache";
private const double PreviewLifetimeInSeconds = 20.0;
private static double s_LastCheckExpiredPreviewTime;
private static Dictionary<string, PreviewInfo> s_LoadedAssetPreviews = new Dictionary<string, PreviewInfo>();
private static object s_Lock = new object();
static AssetPreviewCache()
{
EditorApplication.update += EditorApplication_Update;
}
private static void EditorApplication_Update()
{
if (EditorApplication.timeSinceStartup - s_LastCheckExpiredPreviewTime < PreviewLifetimeInSeconds) {
return;
}
//Debug.Log("Checking for expired previews");
if (s_LoadedAssetPreviews.Values.Any(x => x.HasExpired)) {
//Debug.Log("Found one or more expired previews!");
UnloadExpiredAssetPreviews();
}
s_LastCheckExpiredPreviewTime = EditorApplication.timeSinceStartup;
}
private struct PreviewInfo
{
public Texture2D PreviewTexture;
public double ExpireTime;
public bool HasBeenDestroyed {
get { return !ReferenceEquals(this.PreviewTexture, null) && this.PreviewTexture == null; }
}
public bool HasExpired {
get { return (this.ExpireTime < EditorApplication.timeSinceStartup && !ReferenceEquals(this.PreviewTexture, null)) || this.HasBeenDestroyed; }
}
}
public static Texture2D GetAssetPreview(Object targetObject)
{
// No target object means no preview :)
if (targetObject == null) {
return null;
}
string assetPath = AssetDatabase.GetAssetPath(targetObject);
string guid = AssetDatabase.AssetPathToGUID(assetPath);
string cacheFilePath = GetAssetPreviewCacheFilePath(targetObject);
if (File.Exists(cacheFilePath)) {
DateTime cacheFileTime = File.GetLastWriteTime(cacheFilePath);
DateTime assetFileTime = File.GetLastWriteTime(assetPath);
if (cacheFileTime < assetFileTime) {
ClearCachedAssetPreviewFile(guid);
}
}
var previewInfo = new PreviewInfo();
try {
if (TryGetInMemoryPreview(guid, out previewInfo) && !previewInfo.HasBeenDestroyed) {
// Already loaded asset preview into memory; let's use that!
return previewInfo.PreviewTexture;
}
// Attempt to load asset preview from cache file inside "Library" folder.
//Debug.Log(string.Format("Loading preview for asset '{0}' ({1}).", targetObject.name, guid));
if (File.Exists(cacheFilePath)) {
previewInfo.PreviewTexture = InternalEditorUtility.LoadSerializedFileAndForget(cacheFilePath).OfType<Texture2D>().FirstOrDefault();
return previewInfo.PreviewTexture;
}
// Attempt to generate asset preview.
//Debug.Log(string.Format("Generating preview for asset '{0}' ({1}).", targetObject.name, guid));
var generatedPreviewTexture = GenerateAssetPreview(targetObject);
if (generatedPreviewTexture != null) {
//Debug.Log(string.Format("Saving preview for asset '{0}' ({1}).", targetObject.name, guid));
EnsurePathExists(cacheFilePath);
InternalEditorUtility.SaveToSerializedFileAndForget(new Object[] { generatedPreviewTexture }, cacheFilePath, false);
}
previewInfo.PreviewTexture = generatedPreviewTexture;
return previewInfo.PreviewTexture;
}
finally {
if (previewInfo.PreviewTexture != null) {
previewInfo.PreviewTexture.hideFlags = HideFlags.HideAndDontSave;
}
previewInfo.ExpireTime = EditorApplication.timeSinceStartup + PreviewLifetimeInSeconds;
SetInMemoryPreview(guid, previewInfo);
}
}
private static void UnloadExpiredAssetPreviews()
{
foreach (var entry in s_LoadedAssetPreviews.ToArray()) {
if (entry.Value.HasExpired) {
UnloadAssetPreview(entry.Key);
//Debug.Log(string.Format("Preview expired ({0}).", entry.Key));
}
}
}
public static void UnloadAllAssetPreviews()
{
foreach (string guid in s_LoadedAssetPreviews.Keys.ToArray()) {
UnloadAssetPreview(guid);
}
}
public static void UnloadAssetPreview(string guid)
{
PreviewInfo previewInfo;
if (TryGetInMemoryPreview(guid, out previewInfo)) {
if (previewInfo.PreviewTexture != null) {
Object.DestroyImmediate(previewInfo.PreviewTexture);
}
lock (s_Lock) {
s_LoadedAssetPreviews.Remove(guid);
}
}
}
public static void ClearAllCachedAssetPreviewFiles()
{
// Clear preview cache files.
if (Directory.Exists(LibraryRelativePreviewCacheFolderPath)) {
try {
foreach (string fileName in Directory.GetFiles(LibraryRelativePreviewCacheFolderPath)) {
File.Delete(fileName);
}
}
catch (Exception ex) {
Debug.LogException(ex);
}
}
// Unload all asset previews from memory.
UnloadAllAssetPreviews();
}
public static void ClearCachedAssetPreviewFile(string guid)
{
// Clear preview cache file.
string cacheFilePath = GetAssetPreviewCacheFilePath(guid);
try {
if (File.Exists(cacheFilePath)) {
File.Delete(cacheFilePath);
}
}
catch (Exception ex) {
Debug.LogException(ex);
}
// Unload asset preview from memory.
UnloadAssetPreview(guid);
}
public static void ClearCachedAssetPreviewFile(Object obj)
{
string assetPath = AssetDatabase.GetAssetPath(obj);
string guid = AssetDatabase.AssetPathToGUID(assetPath);
ClearCachedAssetPreviewFile(guid);
}
private static bool TryGetInMemoryPreview(string guid, out PreviewInfo info)
{
lock (s_Lock) {
return s_LoadedAssetPreviews.TryGetValue(guid, out info);
}
}
private static void SetInMemoryPreview(string guid, PreviewInfo info)
{
lock (s_Lock) {
s_LoadedAssetPreviews[guid] = info;
}
}
private static void EnsurePathExists(string filePath)
{
string directoryName = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryName)) {
Directory.CreateDirectory(directoryName);
}
}
private static string GetAssetPreviewCacheFilePath(string guid)
{
return Path.Combine(LibraryRelativePreviewCacheFolderPath, guid + ".asset");
}
private static string GetAssetPreviewCacheFilePath(Object targetObject)
{
string assetPath = AssetDatabase.GetAssetPath(targetObject);
string guid = AssetDatabase.AssetPathToGUID(assetPath);
return GetAssetPreviewCacheFilePath(guid);
}
private static Texture2D GenerateAssetPreview(Object targetObject)
{
var editor = UnityEditor.Editor.CreateEditor(targetObject);
if (editor != null) {
var restoreAmbientLight = RenderSettings.ambientLight;
var restoreAmbientMode = RenderSettings.ambientMode;
var restoreAmbientIntensity = RenderSettings.ambientIntensity;
var restoreSkybox = RenderSettings.skybox;
try {
RenderSettings.ambientLight = new Color(0.212f, 0.227f, 0.259f, 1f);
RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Skybox;
RenderSettings.ambientIntensity = 2f;
// I would rather use the default skybox here; but for some reason it doesn't work :(
RenderSettings.skybox = null;//AssetDatabase.GetBuiltinExtraResource<Material>("Default-Skybox.mat");
string assetPath = AssetDatabase.GetAssetPath(targetObject);
Object[] subAssets = AssetDatabase.LoadAllAssetsAtPath(assetPath);
return editor.RenderStaticPreview(assetPath, subAssets, 256, 256);
}
finally {
RenderSettings.ambientLight = restoreAmbientLight;
RenderSettings.ambientMode = restoreAmbientMode;
RenderSettings.ambientIntensity = restoreAmbientIntensity;
RenderSettings.skybox = restoreSkybox;
Object.DestroyImmediate(editor);
}
}
return null;
}
}
}
| |
// Generated by ProtoGen, Version=2.3.0.277, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace PhoneNumbers {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public static partial class Phonenumber {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
#endregion
#region Extensions
internal static readonly object Descriptor;
static Phonenumber() {
Descriptor = null;
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public sealed partial class PhoneNumber : pb::GeneratedMessageLite<PhoneNumber, PhoneNumber.Builder> {
private static readonly PhoneNumber defaultInstance = new Builder().BuildPartial();
public static PhoneNumber DefaultInstance {
get { return defaultInstance; }
}
public override PhoneNumber DefaultInstanceForType {
get { return defaultInstance; }
}
protected override PhoneNumber ThisMessage {
get { return this; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public static class Types {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public enum CountryCodeSource {
FROM_NUMBER_WITH_PLUS_SIGN = 1,
FROM_NUMBER_WITH_IDD = 5,
FROM_NUMBER_WITHOUT_PLUS_SIGN = 10,
FROM_DEFAULT_COUNTRY = 20,
}
}
#endregion
public const int CountryCodeFieldNumber = 1;
private bool hasCountryCode;
private int countryCode_ = 0;
public bool HasCountryCode {
get { return hasCountryCode; }
}
public int CountryCode {
get { return countryCode_; }
}
public const int NationalNumberFieldNumber = 2;
private bool hasNationalNumber;
private ulong nationalNumber_ = 0UL;
public bool HasNationalNumber {
get { return hasNationalNumber; }
}
public ulong NationalNumber {
get { return nationalNumber_; }
}
public const int ExtensionFieldNumber = 3;
private bool hasExtension;
private string extension_ = "";
public bool HasExtension {
get { return hasExtension; }
}
public string Extension {
get { return extension_; }
}
public const int ItalianLeadingZeroFieldNumber = 4;
private bool hasItalianLeadingZero;
private bool italianLeadingZero_ = false;
public bool HasItalianLeadingZero {
get { return hasItalianLeadingZero; }
}
public bool ItalianLeadingZero {
get { return italianLeadingZero_; }
}
public const int NumberOfLeadingZerosFieldNumber = 8;
private bool hasNumberOfLeadingZeros;
private int numberOfLeadingZeros_ = 1;
public bool HasNumberOfLeadingZeros {
get { return hasNumberOfLeadingZeros; }
}
public int NumberOfLeadingZeros {
get { return numberOfLeadingZeros_; }
}
public const int RawInputFieldNumber = 5;
private bool hasRawInput;
private string rawInput_ = "";
public bool HasRawInput {
get { return hasRawInput; }
}
public string RawInput {
get { return rawInput_; }
}
public const int CountryCodeSourceFieldNumber = 6;
private bool hasCountryCodeSource;
private global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource countryCodeSource_ = global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
public bool HasCountryCodeSource {
get { return hasCountryCodeSource; }
}
public global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource CountryCodeSource {
get { return countryCodeSource_; }
}
public const int PreferredDomesticCarrierCodeFieldNumber = 7;
private bool hasPreferredDomesticCarrierCode;
private string preferredDomesticCarrierCode_ = "";
public bool HasPreferredDomesticCarrierCode {
get { return hasPreferredDomesticCarrierCode; }
}
public string PreferredDomesticCarrierCode {
get { return preferredDomesticCarrierCode_; }
}
public override bool IsInitialized {
get {
if (!hasCountryCode) return false;
if (!hasNationalNumber) return false;
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
int size = SerializedSize;
if (HasCountryCode) {
output.WriteInt32(1, CountryCode);
}
if (HasNationalNumber) {
output.WriteUInt64(2, NationalNumber);
}
if (HasExtension) {
output.WriteString(3, Extension);
}
if (HasItalianLeadingZero) {
output.WriteBool(4, ItalianLeadingZero);
}
if (HasRawInput) {
output.WriteString(5, RawInput);
}
if (HasCountryCodeSource) {
output.WriteEnum(6, (int) CountryCodeSource);
}
if (HasPreferredDomesticCarrierCode) {
output.WriteString(7, PreferredDomesticCarrierCode);
}
if (HasNumberOfLeadingZeros) {
output.WriteInt32(8, NumberOfLeadingZeros);
}
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (HasCountryCode) {
size += pb::CodedOutputStream.ComputeInt32Size(1, CountryCode);
}
if (HasNationalNumber) {
size += pb::CodedOutputStream.ComputeUInt64Size(2, NationalNumber);
}
if (HasExtension) {
size += pb::CodedOutputStream.ComputeStringSize(3, Extension);
}
if (HasItalianLeadingZero) {
size += pb::CodedOutputStream.ComputeBoolSize(4, ItalianLeadingZero);
}
if (HasNumberOfLeadingZeros) {
size += pb::CodedOutputStream.ComputeInt32Size(8, NumberOfLeadingZeros);
}
if (HasRawInput) {
size += pb::CodedOutputStream.ComputeStringSize(5, RawInput);
}
if (HasCountryCodeSource) {
size += pb::CodedOutputStream.ComputeEnumSize(6, (int) CountryCodeSource);
}
if (HasPreferredDomesticCarrierCode) {
size += pb::CodedOutputStream.ComputeStringSize(7, PreferredDomesticCarrierCode);
}
memoizedSerializedSize = size;
return size;
}
}
#region Lite runtime methods
public override int GetHashCode() {
int hash = GetType().GetHashCode();
if (hasCountryCode) hash ^= countryCode_.GetHashCode();
if (hasNationalNumber) hash ^= nationalNumber_.GetHashCode();
if (hasExtension) hash ^= extension_.GetHashCode();
if (hasItalianLeadingZero) hash ^= italianLeadingZero_.GetHashCode();
if (hasNumberOfLeadingZeros) hash ^= numberOfLeadingZeros_.GetHashCode();
if (hasRawInput) hash ^= rawInput_.GetHashCode();
if (hasCountryCodeSource) hash ^= countryCodeSource_.GetHashCode();
if (hasPreferredDomesticCarrierCode) hash ^= preferredDomesticCarrierCode_.GetHashCode();
return hash;
}
public override bool Equals(object obj) {
PhoneNumber other = obj as PhoneNumber;
if (other == null) return false;
if (hasCountryCode != other.hasCountryCode || (hasCountryCode && !countryCode_.Equals(other.countryCode_))) return false;
if (hasNationalNumber != other.hasNationalNumber || (hasNationalNumber && !nationalNumber_.Equals(other.nationalNumber_))) return false;
if (hasExtension != other.hasExtension || (hasExtension && !extension_.Equals(other.extension_))) return false;
if (hasItalianLeadingZero != other.hasItalianLeadingZero || (hasItalianLeadingZero && !italianLeadingZero_.Equals(other.italianLeadingZero_))) return false;
if (hasNumberOfLeadingZeros != other.hasNumberOfLeadingZeros || (hasNumberOfLeadingZeros && !numberOfLeadingZeros_.Equals(other.numberOfLeadingZeros_))) return false;
if (hasRawInput != other.hasRawInput || (hasRawInput && !rawInput_.Equals(other.rawInput_))) return false;
if (hasCountryCodeSource != other.hasCountryCodeSource || (hasCountryCodeSource && !countryCodeSource_.Equals(other.countryCodeSource_))) return false;
if (hasPreferredDomesticCarrierCode != other.hasPreferredDomesticCarrierCode || (hasPreferredDomesticCarrierCode && !preferredDomesticCarrierCode_.Equals(other.preferredDomesticCarrierCode_))) return false;
return true;
}
public override void PrintTo(global::System.IO.TextWriter writer) {
PrintField("country_code", hasCountryCode, countryCode_, writer);
PrintField("national_number", hasNationalNumber, nationalNumber_, writer);
PrintField("extension", hasExtension, extension_, writer);
PrintField("italian_leading_zero", hasItalianLeadingZero, italianLeadingZero_, writer);
PrintField("raw_input", hasRawInput, rawInput_, writer);
PrintField("country_code_source", hasCountryCodeSource, countryCodeSource_, writer);
PrintField("preferred_domestic_carrier_code", hasPreferredDomesticCarrierCode, preferredDomesticCarrierCode_, writer);
PrintField("number_of_leading_zeros", hasNumberOfLeadingZeros, numberOfLeadingZeros_, writer);
}
#endregion
public static PhoneNumber ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PhoneNumber ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PhoneNumber ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PhoneNumber ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(PhoneNumber prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProtoGen", "2.3.0.277")]
public sealed partial class Builder : pb::GeneratedBuilderLite<PhoneNumber, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
PhoneNumber result = new PhoneNumber();
protected override PhoneNumber MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new PhoneNumber();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override PhoneNumber DefaultInstanceForType {
get { return global::PhoneNumbers.PhoneNumber.DefaultInstance; }
}
public override PhoneNumber BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
PhoneNumber returnMe = result;
result = null;
return returnMe;
}
public override Builder MergeFrom(pb::IMessageLite other) {
if (other is PhoneNumber) {
return MergeFrom((PhoneNumber) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(PhoneNumber other) {
if (other == global::PhoneNumbers.PhoneNumber.DefaultInstance) return this;
if (other.HasCountryCode) {
CountryCode = other.CountryCode;
}
if (other.HasNationalNumber) {
NationalNumber = other.NationalNumber;
}
if (other.HasExtension) {
Extension = other.Extension;
}
if (other.HasItalianLeadingZero) {
ItalianLeadingZero = other.ItalianLeadingZero;
}
if (other.HasNumberOfLeadingZeros) {
NumberOfLeadingZeros = other.NumberOfLeadingZeros;
}
if (other.HasRawInput) {
RawInput = other.RawInput;
}
if (other.HasCountryCodeSource) {
CountryCodeSource = other.CountryCodeSource;
}
if (other.HasPreferredDomesticCarrierCode) {
PreferredDomesticCarrierCode = other.PreferredDomesticCarrierCode;
}
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
return this;
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
return this;
}
ParseUnknownField(input, extensionRegistry, tag);
break;
}
case 8: {
CountryCode = input.ReadInt32();
break;
}
case 16: {
NationalNumber = input.ReadUInt64();
break;
}
case 26: {
Extension = input.ReadString();
break;
}
case 32: {
ItalianLeadingZero = input.ReadBool();
break;
}
case 42: {
RawInput = input.ReadString();
break;
}
case 48: {
int rawValue = input.ReadEnum();
if (!global::System.Enum.IsDefined(typeof(global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource), rawValue)) {
} else {
CountryCodeSource = (global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource) rawValue;
}
break;
}
case 58: {
PreferredDomesticCarrierCode = input.ReadString();
break;
}
case 64: {
NumberOfLeadingZeros = input.ReadInt32();
break;
}
}
}
}
public bool HasCountryCode {
get { return result.HasCountryCode; }
}
public int CountryCode {
get { return result.CountryCode; }
set { SetCountryCode(value); }
}
public Builder SetCountryCode(int value) {
result.hasCountryCode = true;
result.countryCode_ = value;
return this;
}
public Builder ClearCountryCode() {
result.hasCountryCode = false;
result.countryCode_ = 0;
return this;
}
public bool HasNationalNumber {
get { return result.HasNationalNumber; }
}
public ulong NationalNumber {
get { return result.NationalNumber; }
set { SetNationalNumber(value); }
}
public Builder SetNationalNumber(ulong value) {
result.hasNationalNumber = true;
result.nationalNumber_ = value;
return this;
}
public Builder ClearNationalNumber() {
result.hasNationalNumber = false;
result.nationalNumber_ = 0UL;
return this;
}
public bool HasExtension {
get { return result.HasExtension; }
}
public string Extension {
get { return result.Extension; }
set { SetExtension(value); }
}
public Builder SetExtension(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasExtension = true;
result.extension_ = value;
return this;
}
public Builder ClearExtension() {
result.hasExtension = false;
result.extension_ = "";
return this;
}
public bool HasItalianLeadingZero {
get { return result.HasItalianLeadingZero; }
}
public bool ItalianLeadingZero {
get { return result.ItalianLeadingZero; }
set { SetItalianLeadingZero(value); }
}
public Builder SetItalianLeadingZero(bool value) {
result.hasItalianLeadingZero = true;
result.italianLeadingZero_ = value;
return this;
}
public Builder ClearItalianLeadingZero() {
result.hasItalianLeadingZero = false;
result.italianLeadingZero_ = false;
return this;
}
public bool HasNumberOfLeadingZeros {
get { return result.HasNumberOfLeadingZeros; }
}
public int NumberOfLeadingZeros {
get { return result.NumberOfLeadingZeros; }
set { SetNumberOfLeadingZeros(value); }
}
public Builder SetNumberOfLeadingZeros(int value) {
result.hasNumberOfLeadingZeros = true;
result.numberOfLeadingZeros_ = value;
return this;
}
public Builder ClearNumberOfLeadingZeros() {
result.hasNumberOfLeadingZeros = false;
result.numberOfLeadingZeros_ = 1;
return this;
}
public bool HasRawInput {
get { return result.HasRawInput; }
}
public string RawInput {
get { return result.RawInput; }
set { SetRawInput(value); }
}
public Builder SetRawInput(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasRawInput = true;
result.rawInput_ = value;
return this;
}
public Builder ClearRawInput() {
result.hasRawInput = false;
result.rawInput_ = "";
return this;
}
public bool HasCountryCodeSource {
get { return result.HasCountryCodeSource; }
}
public global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource CountryCodeSource {
get { return result.CountryCodeSource; }
set { SetCountryCodeSource(value); }
}
public Builder SetCountryCodeSource(global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource value) {
result.hasCountryCodeSource = true;
result.countryCodeSource_ = value;
return this;
}
public Builder ClearCountryCodeSource() {
result.hasCountryCodeSource = false;
result.countryCodeSource_ = global::PhoneNumbers.PhoneNumber.Types.CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
return this;
}
public bool HasPreferredDomesticCarrierCode {
get { return result.HasPreferredDomesticCarrierCode; }
}
public string PreferredDomesticCarrierCode {
get { return result.PreferredDomesticCarrierCode; }
set { SetPreferredDomesticCarrierCode(value); }
}
public Builder SetPreferredDomesticCarrierCode(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
result.hasPreferredDomesticCarrierCode = true;
result.preferredDomesticCarrierCode_ = value;
return this;
}
public Builder ClearPreferredDomesticCarrierCode() {
result.hasPreferredDomesticCarrierCode = false;
result.preferredDomesticCarrierCode_ = "";
return this;
}
}
static PhoneNumber() {
object.ReferenceEquals(global::PhoneNumbers.Phonenumber.Descriptor, null);
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Runtime.Remoting.Channels;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting;
using EnvDTE;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using SPALM.SPSF.SharePointBridge;
using Microsoft.Win32;
namespace SPALM.SPSF.Library
{
public class SharePointBrigdeHelper
{
private System.Diagnostics.Process bridgeProcess = null;
private SharePointRemoteObject remoteObj = null;
private DTE dte = null;
private string toolsPath = "";
public SharePointBrigdeHelper(DTE dte)
{
this.dte = dte;
string version = Helpers.GetInstalledSharePointVersion();
string sharePointBridgeExe = "SharePointBridge" + version + ".exe";
DirectoryInfo assemblyFolder = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
toolsPath = assemblyFolder + @"\" + sharePointBridgeExe;
if (!File.Exists(toolsPath))
{
//ok, file is not in the current directory (issue that executing assembly is located in a different folder
//let's check the registry for the installation location of SPSF
RegistryKey packageKey = Registry.LocalMachine.OpenSubKey(dte.RegistryRoot + @"\BindingPaths\{93c68916-6e2b-43fb-9940-bf7c943cf0d9}", true);
if (packageKey != null)
{
foreach (string s in packageKey.GetValueNames())
{
toolsPath = s + @"\" + sharePointBridgeExe;
if (File.Exists(s))
{
break;
}
}
if (!File.Exists(toolsPath))
{
Helpers.LogMessage(dte, dte, "Error: SharePointBridge '" + sharePointBridgeExe + "' not found ('" + toolsPath + "')");
throw new Exception("File not found " + toolsPath);
}
}
}
Helpers.ShowProgress(dte, string.Format("Connecting to SharePoint {0}...", version == "14"?"2010":"2013"), 10);
Helpers.LogMessage(dte, dte, string.Format("Connecting to SharePoint {0}. Please wait...", version == "14" ? "2010" : "2013"));
if (IsBridgeNeeded)
{
StartBridge();
}
else
{
remoteObj = new SharePointRemoteObject();
}
}
private int GetOSArchitecture()
{
string pa =
Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
return ((String.IsNullOrEmpty(pa) ||
String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? 32 : 64);
}
public bool IsBridgeNeeded
{
get
{
return true;
//is the environment 64bit but the process is 32bit?
/*
if (IntPtr.Size == 4)
{
if (GetOSArchitecture() == 64)
{
Helpers.LogMessage(dte, dte, "Detected: Running as 32bit process on 64bit machine");
return true;
}
}
Helpers.LogMessage(dte, dte, "Detected: No bridge needed");
return false;
* */
}
}
~SharePointBrigdeHelper()
{
StopBridge();
}
public Version GetSharePointVersion()
{
Version x = new Version();
try
{
Helpers.ShowProgress(dte, "Retrieving SharePoint version...", 60);
x = remoteObj.GetSharePointVersion();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return x;
}
public string GetPathToTraceLogs()
{
string path = "";
try
{
Helpers.ShowProgress(dte, "Retrieving SharePoint Trace Log Location...", 60);
path = remoteObj.GetPathToTraceLogs();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return path;
}
public void ExportContent(SharePointExportSettings exportSettings, string tempExportDir, string tempFilename, string tempLogFilePath)
{
try
{
Helpers.ShowProgress(dte, "Exporting SharePoint solution...", 60);
remoteObj.ExportContent(exportSettings, tempExportDir, tempFilename, tempLogFilePath);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
public void ExportSolutionAsFile(string solutionName, string saveAsfilename)
{
try
{
Helpers.ShowProgress(dte, "Exporting SharePoint solution...", 60);
remoteObj.ExportSolutionAsFile(solutionName, saveAsfilename);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
public void DeleteFailedDeploymentJobs()
{
try
{
remoteObj.DeleteFailedDeploymentJobs();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
private void StartBridge()
{
try
{
//IChannel ichannel = new IpcChannel("myClient");
//ChannelServices.RegisterChannel(ichannel, false);
string channelName = "SPSF" + Guid.NewGuid().ToString();
bridgeProcess = new System.Diagnostics.Process();
bridgeProcess.StartInfo.FileName = toolsPath;
bridgeProcess.StartInfo.CreateNoWindow = true;
bridgeProcess.StartInfo.Arguments = channelName;
bridgeProcess.StartInfo.UseShellExecute = false;
bridgeProcess.StartInfo.RedirectStandardInput = true;
bridgeProcess.StartInfo.RedirectStandardOutput = true;
bridgeProcess.StartInfo.RedirectStandardError = true;
bridgeProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(toolsPath);
bridgeProcess.OutputDataReceived += new DataReceivedEventHandler(bridgeProcess_OutputDataReceived);
bridgeProcess.ErrorDataReceived += new DataReceivedEventHandler(bridgeProcess_ErrorDataReceived);
bridgeProcess.EnableRaisingEvents = true;
bridgeProcess.Start();
bridgeProcess.BeginOutputReadLine();
TimeSpan waitTime = new TimeSpan(0, 0, 5);
System.Threading.Thread.Sleep(waitTime);
try
{
remoteObj = Activator.GetObject(typeof(SharePointRemoteObject), "ipc://" + channelName + "/RemoteObj") as SharePointRemoteObject;
}
catch { }
if (remoteObj == null)
{
for (int i = 0; i < 5; i++)
{
System.Threading.Thread.Sleep(waitTime);
remoteObj = Activator.GetObject(typeof(SharePointRemoteObject), "ipc://" + channelName + "/RemoteObj") as SharePointRemoteObject;
if (remoteObj == null)
{
break;
}
}
}
}
catch (Exception ex)
{
throw new Exception("Could not start SPSF SharePointBridge. Make sure that IIS and SharePoint are running (" + ex.Message + ")");
}
if (remoteObj == null)
{
throw new Exception("Could not access SharePointRemoteObject");
}
//Helpers.LogMessage(dte, dte, "SharePointBridge started");
}
void bridgeProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Helpers.LogMessage(dte, dte, "SharePointBridge error: " + e.Data);
}
void bridgeProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (string.IsNullOrEmpty(e.Data))
{
return;
}
string message = e.Data;
int percentage = 0;
//to retrieve progress we have pipe as separator
if (message.Contains("%"))
{
try
{
percentage = Int32.Parse(message.Substring(0, message.IndexOf("%")));
message = message.Substring(message.IndexOf("%") + 1);
}
catch { }
}
if (percentage > 0)
{
Helpers.ShowProgress(dte, message, percentage);
}
Helpers.LogMessage(dte, dte, message);
}
private void StopBridge()
{
if (bridgeProcess != null)
{
if (!bridgeProcess.HasExited)
{
//Helpers.LogMessage(dte, dte, "Closing connection to SharePoint");
bridgeProcess.Kill();
}
}
}
public string GetCentralAdministrationUrl()
{
string res = "";
try
{
Helpers.ShowProgress(dte, "Retrieving url of Central Administration...", 60);
res = remoteObj.GetCentralAdministrationUrl();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public void PerformDeploymentOperation(string operation, List<SharePointDeploymentJob> deploymentJobs)
{
try
{
remoteObj.PerformDeploymentOperation(operation, deploymentJobs);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
public void ExportListAsTemplate(string weburl, Guid listId, string tempPath)
{
try
{
Helpers.ShowProgress(dte, "Exporting list template...", 60);
remoteObj.ExportListAsTemplate(weburl, listId, tempPath);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
public List<SharePointWebApplication> GetAllWebApplications()
{
List<SharePointWebApplication> res = new List<SharePointWebApplication>();
try
{
Helpers.ShowProgress(dte, "Retrieving webapplication list...", 60);
res = remoteObj.GetAllWebApplications();
LogMessage("SharePointBrigdeHelper: GetAllWebApplications retrieved " + res.Count.ToString() + " items");
}
catch (Exception ex)
{
LogMessage("SharePointBrigdeHelper: " + ex.ToString());
Helpers.LogMessage(dte, dte, ex.Message);
Helpers.LogMessage(dte, dte, "Ensure that WWW Service and SharePoint database are running on your machine");
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
private static void LogMessage(string p)
{
//string logFile = Path.Combine(GetAssemblyDirectory(), "SharePointBridge.log");
//File.AppendAllText(logFile, p + Environment.NewLine);
}
private static string GetAssemblyDirectory()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
public SharePointWeb GetRootWebOfSite(string siteCollection)
{
SharePointWeb res = null;
try
{
Helpers.ShowProgress(dte, "Retrieving webs of site " + siteCollection + "...", 60);
res = remoteObj.GetRootWebOfSite(siteCollection);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Helpers.LogMessage(dte, dte, ex.ToString());
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public SharePointWeb GetWeb(string webUrl)
{
SharePointWeb res = null;
try
{
Helpers.ShowProgress(dte, "Retrieving web " + webUrl + "...", 60);
res = remoteObj.GetWeb(webUrl);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Helpers.LogMessage(dte, dte, ex.ToString());
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public List<SharePointSiteCollection> GetAllSiteCollections()
{
List<SharePointSiteCollection> res = new List<SharePointSiteCollection>();
try
{
Helpers.ShowProgress(dte, "Retrieving site collections list...", 60);
res = remoteObj.GetAllSiteCollections();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Helpers.LogMessage(dte, dte, ex.ToString());
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public List<SharePointField> GetSiteColumns(string siteUrl)
{
List<SharePointField> res = new List<SharePointField>();
try
{
Helpers.ShowProgress(dte, "Retrieving content type list...", 60);
res = remoteObj.GetSiteColumns(siteUrl);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public List<SharePointContentType> GetContentTypes(string siteUrl)
{
List<SharePointContentType> res = new List<SharePointContentType>();
try
{
Helpers.ShowProgress(dte, "Retrieving content type list...", 60);
res = remoteObj.GetContentTypes(siteUrl);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Helpers.LogMessage(dte, dte, ex.ToString());
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public List<SharePointSolution> GetAllSharePointSolutions()
{
List<SharePointSolution> res = new List<SharePointSolution>();
try
{
Helpers.ShowProgress(dte, "Retrieving solutions list...", 60);
res = remoteObj.GetAllSharePointSolutions();
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
return res;
}
public void CheckBrokenFields(string siteCollectionUrl)
{
try
{
Helpers.ShowProgress(dte, "Checking for broken fields in site collection " + siteCollectionUrl, 60);
remoteObj.CheckBrokenFields(siteCollectionUrl);
}
catch (Exception ex)
{
Helpers.LogMessage(dte, dte, ex.Message);
}
finally
{
Helpers.HideProgress(dte);
StopBridge();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security.Permissions;
namespace System.ComponentModel
{
/// <summary>
/// <para>Provides a type converter to convert <see cref='System.Globalization.CultureInfo'/>
/// objects to and from various other representations.</para>
/// </summary>
public class CultureInfoConverter : TypeConverter
{
private StandardValuesCollection _values;
/// <summary>
/// Retrieves the "default" name for our culture.
/// </summary>
private string DefaultCultureString => SR.CultureInfoConverterDefaultCultureString;
const string DefaultInvariantCultureString = "(Default)";
/// <summary>
/// Retrieves the Name for a input CultureInfo.
/// </summary>
protected virtual string GetCultureName(CultureInfo culture)
{
return culture.Name;
}
/// <summary>
/// <para>
/// Gets a value indicating whether this converter can
/// convert an object in the given source type to a System.Globalization.CultureInfo
/// object using
/// the specified context.
/// </para>
/// </summary>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// <para>Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.</para>
/// </summary>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
/// <summary>
/// <para>
/// Converts the specified value object to a <see cref='System.Globalization.CultureInfo'/>
/// object.
/// </para>
/// </summary>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
// Hack, Only when GetCultureName returns culture.Name, we use CultureInfoMapper
// (Since CultureInfoMapper will transfer Culture.DisplayName to Culture.Name).
// Otherwise, we just keep the value unchange.
string text = (string)value;
if (GetCultureName(CultureInfo.InvariantCulture).Equals(""))
{
text = CultureInfoMapper.GetCultureInfoName((string)value);
}
CultureInfo retVal = null;
string defaultCultureString = DefaultCultureString;
if (culture != null && culture.Equals(CultureInfo.InvariantCulture))
{
defaultCultureString = DefaultInvariantCultureString;
}
// Look for the default culture info.
//
if (text == null || text.Length == 0 || string.Compare(text, defaultCultureString, StringComparison.Ordinal) == 0)
{
retVal = CultureInfo.InvariantCulture;
}
// Now look in our set of installed cultures.
//
if (retVal == null)
{
foreach (CultureInfo info in GetStandardValues(context))
{
if (info != null && string.Compare(GetCultureName(info), text, StringComparison.Ordinal) == 0)
{
retVal = info;
break;
}
}
}
// Now try to create a new culture info from this value
//
if (retVal == null)
{
try
{
retVal = new CultureInfo(text);
}
catch { }
}
// Finally, try to find a partial match
//
if (retVal == null)
{
text = text.ToLower(CultureInfo.CurrentCulture);
foreach (CultureInfo info in _values)
{
if (info != null && GetCultureName(info).ToLower(CultureInfo.CurrentCulture).StartsWith(text))
{
retVal = info;
break;
}
}
}
// No good. We can't support it.
//
if (retVal == null)
{
throw new ArgumentException(SR.Format(SR.CultureInfoConverterInvalidCulture, (string)value));
}
return retVal;
}
return base.ConvertFrom(context, culture, value);
}
/// <summary>
/// <para>
/// Converts the given
/// value object to the
/// specified destination type.
/// </para>
/// </summary>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException(nameof(destinationType));
}
if (destinationType == typeof(string))
{
string retVal;
string defaultCultureString = DefaultCultureString;
if (culture != null && culture.Equals(CultureInfo.InvariantCulture))
{
defaultCultureString = DefaultInvariantCultureString;
}
if (value == null || value == CultureInfo.InvariantCulture)
{
retVal = defaultCultureString;
}
else
{
retVal = GetCultureName(((CultureInfo)value));
}
return retVal;
}
if (destinationType == typeof(InstanceDescriptor) && value is CultureInfo)
{
CultureInfo c = (CultureInfo)value;
ConstructorInfo ctor = typeof(CultureInfo).GetConstructor(new Type[] { typeof(string) });
if (ctor != null)
{
return new InstanceDescriptor(ctor, new object[] { c.Name });
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <summary>
/// <para>
/// Gets a collection of standard values collection for a System.Globalization.CultureInfo
/// object using the specified context.
/// </para>
/// </summary>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
if (_values == null)
{
CultureInfo[] installedCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures | CultureTypes.NeutralCultures);
int invariantIndex = Array.IndexOf(installedCultures, CultureInfo.InvariantCulture);
CultureInfo[] array;
if (invariantIndex != -1)
{
Debug.Assert(invariantIndex >= 0 && invariantIndex < installedCultures.Length);
installedCultures[invariantIndex] = null;
array = new CultureInfo[installedCultures.Length];
}
else
{
array = new CultureInfo[installedCultures.Length + 1];
}
Array.Copy(installedCultures, array, installedCultures.Length);
Array.Sort(array, new CultureComparer(this));
Debug.Assert(array[0] == null);
if (array[0] == null)
{
//we replace null with the real default culture because there are code paths
// where the propgrid will send values from this returned array directly -- instead
// of converting it to a string and then back to a value (which this relied on).
array[0] = CultureInfo.InvariantCulture; //null isn't the value here -- invariantculture is.
}
_values = new StandardValuesCollection(array);
}
return _values;
}
/// <summary>
/// <para>
/// Gets a value indicating whether the list of standard values returned from
/// System.ComponentModel.CultureInfoConverter.GetStandardValues is an exclusive list.
/// </para>
/// </summary>
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
/// <summary>
/// <para>
/// Gets a value indicating whether this object supports a
/// standard set of values that can be picked from a list using the specified
/// context.
/// </para>
/// </summary>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
/// <summary>
/// IComparer object used for sorting CultureInfos
/// WARNING: If you change where null is positioned, then you must fix CultureConverter.GetStandardValues!
/// </summary>
private class CultureComparer : IComparer
{
private CultureInfoConverter _converter;
public CultureComparer(CultureInfoConverter cultureConverter)
{
Debug.Assert(cultureConverter != null);
_converter = cultureConverter;
}
public int Compare(object item1, object item2)
{
if (item1 == null)
{
// If both are null, then they are equal
//
if (item2 == null)
{
return 0;
}
// Otherwise, item1 is null, but item2 is valid (greater)
//
return -1;
}
if (item2 == null)
{
// item2 is null, so item 1 is greater
//
return 1;
}
String itemName1 = _converter.GetCultureName(((CultureInfo)item1));
String itemName2 = _converter.GetCultureName(((CultureInfo)item2));
CompareInfo compInfo = (CultureInfo.CurrentCulture).CompareInfo;
return compInfo.Compare(itemName1, itemName2, CompareOptions.StringSort);
}
}
private static class CultureInfoMapper
{
/// Dictionary of CultureInfo.DisplayName, CultureInfo.Name for cultures that have changed DisplayName over releases.
/// This is to workaround an issue with CultureInfoConverter that serializes DisplayName (fixing it would introduce breaking changes).
private static readonly Dictionary<string, string> s_cultureInfoNameMap = CreateMap();
private static Dictionary<string,string> CreateMap()
{
const int Count = 274;
var result = new Dictionary<string, string>(Count) {
{"Afrikaans", "af"},
{"Afrikaans (South Africa)", "af-ZA"},
{"Albanian", "sq"},
{"Albanian (Albania)", "sq-AL"},
{"Alsatian (France)", "gsw-FR"},
{"Amharic (Ethiopia)", "am-ET"},
{"Arabic", "ar"},
{"Arabic (Algeria)", "ar-DZ"},
{"Arabic (Bahrain)", "ar-BH"},
{"Arabic (Egypt)", "ar-EG"},
{"Arabic (Iraq)", "ar-IQ"},
{"Arabic (Jordan)", "ar-JO"},
{"Arabic (Kuwait)", "ar-KW"},
{"Arabic (Lebanon)", "ar-LB"},
{"Arabic (Libya)", "ar-LY"},
{"Arabic (Morocco)", "ar-MA"},
{"Arabic (Oman)", "ar-OM"},
{"Arabic (Qatar)", "ar-QA"},
{"Arabic (Saudi Arabia)", "ar-SA"},
{"Arabic (Syria)", "ar-SY"},
{"Arabic (Tunisia)", "ar-TN"},
{"Arabic (U.A.E.)", "ar-AE"},
{"Arabic (Yemen)", "ar-YE"},
{"Armenian", "hy"},
{"Armenian (Armenia)", "hy-AM"},
{"Assamese (India)", "as-IN"},
{"Azeri", "az"},
{"Azeri (Cyrillic, Azerbaijan)", "az-Cyrl-AZ"},
{"Azeri (Latin, Azerbaijan)", "az-Latn-AZ"},
{"Bashkir (Russia)", "ba-RU"},
{"Basque", "eu"},
{"Basque (Basque)", "eu-ES"},
{"Belarusian", "be"},
{"Belarusian (Belarus)", "be-BY"},
{"Bengali (Bangladesh)", "bn-BD"},
{"Bengali (India)", "bn-IN"},
{"Bosnian (Cyrillic, Bosnia and Herzegovina)", "bs-Cyrl-BA"},
{"Bosnian (Latin, Bosnia and Herzegovina)", "bs-Latn-BA"},
{"Breton (France)", "br-FR"},
{"Bulgarian", "bg"},
{"Bulgarian (Bulgaria)", "bg-BG"},
{"Catalan", "ca"},
{"Catalan (Catalan)", "ca-ES"},
{"Chinese (Hong Kong S.A.R.)", "zh-HK"},
{"Chinese (Macao S.A.R.)", "zh-MO"},
{"Chinese (People's Republic of China)", "zh-CN"},
{"Chinese (Simplified)", "zh-CHS"},
{"Chinese (Singapore)", "zh-SG"},
{"Chinese (Taiwan)", "zh-TW"},
{"Chinese (Traditional)", "zh-CHT"},
{"Corsican (France)", "co-FR"},
{"Croatian", "hr"},
{"Croatian (Croatia)", "hr-HR"},
{"Croatian (Latin, Bosnia and Herzegovina)", "hr-BA"},
{"Czech", "cs"},
{"Czech (Czech Republic)", "cs-CZ"},
{"Danish", "da"},
{"Danish (Denmark)", "da-DK"},
{"Dari (Afghanistan)", "prs-AF"},
{"Divehi", "dv"},
{"Divehi (Maldives)", "dv-MV"},
{"Dutch", "nl"},
{"Dutch (Belgium)", "nl-BE"},
{"Dutch (Netherlands)", "nl-NL"},
{"English", "en"},
{"English (Australia)", "en-AU"},
{"English (Belize)", "en-BZ"},
{"English (Canada)", "en-CA"},
{"English (Caribbean)", "en-029"},
{"English (India)", "en-IN"},
{"English (Ireland)", "en-IE"},
{"English (Jamaica)", "en-JM"},
{"English (Malaysia)", "en-MY"},
{"English (New Zealand)", "en-NZ"},
{"English (Republic of the Philippines)", "en-PH"},
{"English (Singapore)", "en-SG"},
{"English (South Africa)", "en-ZA"},
{"English (Trinidad and Tobago)", "en-TT"},
{"English (United Kingdom)", "en-GB"},
{"English (United States)", "en-US"},
{"English (Zimbabwe)", "en-ZW"},
{"Estonian", "et"},
{"Estonian (Estonia)", "et-EE"},
{"Faroese", "fo"},
{"Faroese (Faroe Islands)", "fo-FO"},
{"Filipino (Philippines)", "fil-PH"},
{"Finnish", "fi"},
{"Finnish (Finland)", "fi-FI"},
{"French", "fr"},
{"French (Belgium)", "fr-BE"},
{"French (Canada)", "fr-CA"},
{"French (France)", "fr-FR"},
{"French (Luxembourg)", "fr-LU"},
{"French (Principality of Monaco)", "fr-MC"},
{"French (Switzerland)", "fr-CH"},
{"Frisian (Netherlands)", "fy-NL"},
{"Galician", "gl"},
{"Galician (Galician)", "gl-ES"},
{"Georgian", "ka"},
{"Georgian (Georgia)", "ka-GE"},
{"German", "de"},
{"German (Austria)", "de-AT"},
{"German (Germany)", "de-DE"},
{"German (Liechtenstein)", "de-LI"},
{"German (Luxembourg)", "de-LU"},
{"German (Switzerland)", "de-CH"},
{"Greek", "el"},
{"Greek (Greece)", "el-GR"},
{"Greenlandic (Greenland)", "kl-GL"},
{"Gujarati", "gu"},
{"Gujarati (India)", "gu-IN"},
{"Hausa (Latin, Nigeria)", "ha-Latn-NG"},
{"Hebrew", "he"},
{"Hebrew (Israel)", "he-IL"},
{"Hindi", "hi"},
{"Hindi (India)", "hi-IN"},
{"Hungarian", "hu"},
{"Hungarian (Hungary)", "hu-HU"},
{"Icelandic", "is"},
{"Icelandic (Iceland)", "is-IS"},
{"Igbo (Nigeria)", "ig-NG"},
{"Indonesian", "id"},
{"Indonesian (Indonesia)", "id-ID"},
{"Inuktitut (Latin, Canada)", "iu-Latn-CA"},
{"Inuktitut (Syllabics, Canada)", "iu-Cans-CA"},
{"Invariant Language (Invariant Country)", ""},
{"Irish (Ireland)", "ga-IE"},
{"isiXhosa (South Africa)", "xh-ZA"},
{"isiZulu (South Africa)", "zu-ZA"},
{"Italian", "it"},
{"Italian (Italy)", "it-IT"},
{"Italian (Switzerland)", "it-CH"},
{"Japanese", "ja"},
{"Japanese (Japan)", "ja-JP"},
{"K'iche (Guatemala)", "qut-GT"},
{"Kannada", "kn"},
{"Kannada (India)", "kn-IN"},
{"Kazakh", "kk"},
{"Kazakh (Kazakhstan)", "kk-KZ"},
{"Khmer (Cambodia)", "km-KH"},
{"Kinyarwanda (Rwanda)", "rw-RW"},
{"Kiswahili", "sw"},
{"Kiswahili (Kenya)", "sw-KE"},
{"Konkani", "kok"},
{"Konkani (India)", "kok-IN"},
{"Korean", "ko"},
{"Korean (Korea)", "ko-KR"},
{"Kyrgyz", "ky"},
{"Kyrgyz (Kyrgyzstan)", "ky-KG"},
{"Lao (Lao P.D.R.)", "lo-LA"},
{"Latvian", "lv"},
{"Latvian (Latvia)", "lv-LV"},
{"Lithuanian", "lt"},
{"Lithuanian (Lithuania)", "lt-LT"},
{"Lower Sorbian (Germany)", "dsb-DE"},
{"Luxembourgish (Luxembourg)", "lb-LU"},
{"Macedonian", "mk"},
{"Macedonian (Former Yugoslav Republic of Macedonia)", "mk-MK"},
{"Malay", "ms"},
{"Malay (Brunei Darussalam)", "ms-BN"},
{"Malay (Malaysia)", "ms-MY"},
{"Malayalam (India)", "ml-IN"},
{"Maltese (Malta)", "mt-MT"},
{"Maori (New Zealand)", "mi-NZ"},
{"Mapudungun (Chile)", "arn-CL"},
{"Marathi", "mr"},
{"Marathi (India)", "mr-IN"},
{"Mohawk (Mohawk)", "moh-CA"},
{"Mongolian", "mn"},
{"Mongolian (Cyrillic, Mongolia)", "mn-MN"},
{"Mongolian (Traditional Mongolian, PRC)", "mn-Mong-CN"},
{"Nepali (Nepal)", "ne-NP"},
{"Norwegian", "no"},
{"Norwegian, Bokm\u00E5l (Norway)", "nb-NO"},
{"Norwegian, Nynorsk (Norway)", "nn-NO"},
{"Occitan (France)", "oc-FR"},
{"Oriya (India)", "or-IN"},
{"Pashto (Afghanistan)", "ps-AF"},
{"Persian", "fa"},
{"Persian (Iran)", "fa-IR"},
{"Polish", "pl"},
{"Polish (Poland)", "pl-PL"},
{"Portuguese", "pt"},
{"Portuguese (Brazil)", "pt-BR"},
{"Portuguese (Portugal)", "pt-PT"},
{"Punjabi", "pa"},
{"Punjabi (India)", "pa-IN"},
{"Quechua (Bolivia)", "quz-BO"},
{"Quechua (Ecuador)", "quz-EC"},
{"Quechua (Peru)", "quz-PE"},
{"Romanian", "ro"},
{"Romanian (Romania)", "ro-RO"},
{"Romansh (Switzerland)", "rm-CH"},
{"Russian", "ru"},
{"Russian (Russia)", "ru-RU"},
{"Sami, Inari (Finland)", "smn-FI"},
{"Sami, Lule (Norway)", "smj-NO"},
{"Sami, Lule (Sweden)", "smj-SE"},
{"Sami, Northern (Finland)", "se-FI"},
{"Sami, Northern (Norway)", "se-NO"},
{"Sami, Northern (Sweden)", "se-SE"},
{"Sami, Skolt (Finland)", "sms-FI"},
{"Sami, Southern (Norway)", "sma-NO"},
{"Sami, Southern (Sweden)", "sma-SE"},
{"Sanskrit", "sa"},
{"Sanskrit (India)", "sa-IN"},
{"Serbian", "sr"},
{"Serbian (Cyrillic, Bosnia and Herzegovina)", "sr-Cyrl-BA"},
{"Serbian (Cyrillic, Serbia)", "sr-Cyrl-CS"},
{"Serbian (Latin, Bosnia and Herzegovina)", "sr-Latn-BA"},
{"Serbian (Latin, Serbia)", "sr-Latn-CS"},
{"Sesotho sa Leboa (South Africa)", "nso-ZA"},
{"Setswana (South Africa)", "tn-ZA"},
{"Sinhala (Sri Lanka)", "si-LK"},
{"Slovak", "sk"},
{"Slovak (Slovakia)", "sk-SK"},
{"Slovenian", "sl"},
{"Slovenian (Slovenia)", "sl-SI"},
{"Spanish", "es"},
{"Spanish (Argentina)", "es-AR"},
{"Spanish (Bolivia)", "es-BO"},
{"Spanish (Chile)", "es-CL"},
{"Spanish (Colombia)", "es-CO"},
{"Spanish (Costa Rica)", "es-CR"},
{"Spanish (Dominican Republic)", "es-DO"},
{"Spanish (Ecuador)", "es-EC"},
{"Spanish (El Salvador)", "es-SV"},
{"Spanish (Guatemala)", "es-GT"},
{"Spanish (Honduras)", "es-HN"},
{"Spanish (Mexico)", "es-MX"},
{"Spanish (Nicaragua)", "es-NI"},
{"Spanish (Panama)", "es-PA"},
{"Spanish (Paraguay)", "es-PY"},
{"Spanish (Peru)", "es-PE"},
{"Spanish (Puerto Rico)", "es-PR"},
{"Spanish (Spain)", "es-ES"},
{"Spanish (United States)", "es-US"},
{"Spanish (Uruguay)", "es-UY"},
{"Spanish (Venezuela)", "es-VE"},
{"Swedish", "sv"},
{"Swedish (Finland)", "sv-FI"},
{"Swedish (Sweden)", "sv-SE"},
{"Syriac", "syr"},
{"Syriac (Syria)", "syr-SY"},
{"Tajik (Cyrillic, Tajikistan)", "tg-Cyrl-TJ"},
{"Tamazight (Latin, Algeria)", "tzm-Latn-DZ"},
{"Tamil", "ta"},
{"Tamil (India)", "ta-IN"},
{"Tatar", "tt"},
{"Tatar (Russia)", "tt-RU"},
{"Telugu", "te"},
{"Telugu (India)", "te-IN"},
{"Thai", "th"},
{"Thai (Thailand)", "th-TH"},
{"Tibetan (PRC)", "bo-CN"},
{"Turkish", "tr"},
{"Turkish (Turkey)", "tr-TR"},
{"Turkmen (Turkmenistan)", "tk-TM"},
{"Uighur (PRC)", "ug-CN"},
{"Ukrainian", "uk"},
{"Ukrainian (Ukraine)", "uk-UA"},
{"Upper Sorbian (Germany)", "hsb-DE"},
{"Urdu", "ur"},
{"Urdu (Islamic Republic of Pakistan)", "ur-PK"},
{"Uzbek", "uz"},
{"Uzbek (Cyrillic, Uzbekistan)", "uz-Cyrl-UZ"},
{"Uzbek (Latin, Uzbekistan)", "uz-Latn-UZ"},
{"Vietnamese", "vi"},
{"Vietnamese (Vietnam)", "vi-VN"},
{"Welsh (United Kingdom)", "cy-GB"},
{"Wolof (Senegal)", "wo-SN"},
{"Yakut (Russia)", "sah-RU"},
{"Yi (PRC)", "ii-CN"},
{"Yoruba (Nigeria)", "yo-NG"}
};
Debug.Assert(result.Count == Count);
return result;
}
public static string GetCultureInfoName(string cultureInfoDisplayName)
{
string name;
return s_cultureInfoNameMap.TryGetValue(cultureInfoDisplayName, out name) ?
name :
cultureInfoDisplayName;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Drawing;
using GPrintLib.Interfaces;
namespace GPrintLib {
/// <summary>
///
/// </summary>
public class PrintableDocument {
private IList<PrintablePage> printPageList;
private PrintDocument docToPrint = new PrintDocument();
private string documentName = "";
private int pages;
private int currentPage;
private bool landscape = false;
private bool color = true;
private PaperSize paperSize = null;
private PaperSource paperSource = null;
private PaperKind? paperKindIfSupported = null;
private PaperKind? paperKindOrNothing = null;
/// <summary>
/// Gets or sets the name of the document.
/// </summary>
/// <value>The name of the document.</value>
public string DocumentName {
get {
return this.documentName;
}
set {
this.documentName = value;
}
}
/// <summary>
/// Gets or sets the print page list.
/// </summary>
/// <value>The print page list.</value>
public IList<PrintablePage> PrintPageList {
get {
return this.printPageList;
}
set {
this.printPageList = value;
}
}
/// <summary>
/// Gets or sets the paper kind if supported.
/// </summary>
/// <value>The paper kind if supported.</value>
public PaperKind? PaperKindIfSupported {
get {
return this.paperKindIfSupported;
}
set {
this.paperKindIfSupported = value;
}
}
/// <summary>
/// Gets or sets the paper kind or nothing.
/// </summary>
/// <value>The paper kind or nothing.</value>
public PaperKind? PaperKindOrNothing {
get {
return this.paperKindOrNothing;
}
set {
this.paperKindOrNothing = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="PrintableDocument"/> is landscape.
/// </summary>
/// <value><c>true</c> if landscape; otherwise, <c>false</c>.</value>
public bool Landscape {
get {
return this.landscape;
}
set {
this.landscape = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="PrintableDocument"/> is color.
/// </summary>
/// <value><c>true</c> if color; otherwise, <c>false</c>.</value>
public bool Color {
get {
return this.color;
}
set {
this.color = value;
}
}
/// <summary>
/// Gets or sets the size of the paper.
/// </summary>
/// <value>The size of the paper.</value>
public PaperSize PaperSize {
get {
return this.paperSize;
}
set {
this.paperSize = value;
}
}
/// <summary>
/// Gets or sets the paper source.
/// </summary>
/// <value>The paper source.</value>
public PaperSource PaperSource {
get {
return this.paperSource;
}
set {
this.paperSource = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PrintableDocument"/> class.
/// </summary>
public PrintableDocument() {
printPageList = new List<PrintablePage>();
}
/// <summary>
/// Adds the print page.
/// </summary>
/// <param name="page">The page.</param>
public void AddPrintPage(PrintablePage page) {
this.printPageList.Add(page);
}
/// <summary>
/// Does the print.
/// </summary>
/// <returns>null if OK, the PrintDialog if the Papersize is not supported!!</returns>
public PrintDialog DoPrint() {
return DoPrint(null);
}
/// <summary>
/// Printername
/// </summary>
public string PrinterName {
get { return this.docToPrint.PrinterSettings.PrinterName; }
set { this.docToPrint.PrinterSettings.PrinterName = value; }
}
/// <summary>
/// is Valid
/// </summary>
/// <returns></returns>
public bool isValid() {
return this.docToPrint.PrinterSettings.IsValid;
}
/// <summary>
/// Does the print.
/// </summary>
/// <returns>null if OK, the PrintDialog if the Papersize is not supported!!</returns>
public PrintDialog DoPrint(PrintDialog printDialogParam) {
return DoPrint(null, true);
}
/// <summary>
/// Does the print.
/// </summary>
/// <returns>null if OK, the PrintDialog if the Papersize is not supported!!</returns>
public PrintDialog DoPrint(PrintDialog printDialogParam, bool showPrintDialog) {
PrintDialog printDialog;
if (printDialogParam == null) {
printDialog = new PrintDialog();
} else {
printDialog = printDialogParam;
}
docToPrint.DocumentName = this.documentName;
docToPrint.DefaultPageSettings.Landscape = this.landscape;
if (this.paperSource != null) {
docToPrint.DefaultPageSettings.PaperSource = this.paperSource;
}
if (this.paperSize != null) {
docToPrint.DefaultPageSettings.PaperSize = this.paperSize;
}
docToPrint.DefaultPageSettings.Color = this.color;
printDialog.AllowSomePages = true;
printDialog.ShowHelp = true;
printDialog.Document = docToPrint;
if (this.paperKindOrNothing != null) {
foreach (PaperSize ps in printDialog.PrinterSettings.PaperSizes) {
if (ps.Kind == this.paperKindOrNothing) {
docToPrint.DefaultPageSettings.PaperSize = ps;
break;
}
}
}
else if (this.paperKindIfSupported != null) {
foreach (PaperSize ps in printDialog.PrinterSettings.PaperSizes) {
if (ps.Kind == this.paperKindIfSupported) {
docToPrint.DefaultPageSettings.PaperSize = ps;
break;
}
}
}
if (showPrintDialog)
{
if (printDialogParam == null)
{
DialogResult result = printDialog.ShowDialog();
if (result != DialogResult.OK)
{
return null;
}
}
}
if (this.paperKindOrNothing != null) {
bool paperSizeSupported = false;
foreach (PaperSize ps in printDialog.PrinterSettings.PaperSizes) {
if (ps.Kind == this.paperKindOrNothing) {
docToPrint.DefaultPageSettings.PaperSize = ps;
paperSizeSupported = true;
break;
}
}
if (!paperSizeSupported) {
return printDialog;
}
}
else if (this.paperKindIfSupported != null) {
foreach(PaperSize ps in printDialog.PrinterSettings.PaperSizes) {
if (ps.Kind == this.paperKindIfSupported) {
docToPrint.DefaultPageSettings.PaperSize = ps;
break;
}
}
}
docToPrint.PrintPage += new PrintPageEventHandler(document_PrintPage);
pages = this.printPageList.Count;
currentPage = 0;
if (this.printPageList.Count <= 0) {
return null;
}
try {
docToPrint.Print();
} catch (Exception e) {
MessageBox.Show("Error while printing: " + e.ToString());
}
return null;
}
/// <summary>
/// Handles the PrintPage event of the document control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Drawing.Printing.PrintPageEventArgs"/> instance containing the event data.</param>
private void document_PrintPage(object sender,
PrintPageEventArgs e) {
PrintablePage ppd = this.printPageList[currentPage];
foreach (IPrintableObject po in ppd.PrintableObjectList) {
po.AddToGraphics(e.Graphics);
}
currentPage++;
if (--pages > 0)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
/// <summary>
/// Duplicates the specified number.
/// </summary>
/// <param name="number">The number.</param>
public void duplicate(int number) {
IList<PrintablePage> newPrintPageList = new List<PrintablePage>();
for (int i = 0; i < number; i++) {
foreach (PrintablePage pp in printPageList) {
newPrintPageList.Add(pp);
}
}
this.printPageList = newPrintPageList;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A pool in the Azure Batch service.
/// </summary>
public partial class CloudPool : ITransportObjectProvider<Models.PoolAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<Common.AllocationState?> AllocationStateProperty;
public readonly PropertyAccessor<DateTime?> AllocationStateTransitionTimeProperty;
public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty;
public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty;
public readonly PropertyAccessor<string> AutoScaleFormulaProperty;
public readonly PropertyAccessor<AutoScaleRun> AutoScaleRunProperty;
public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty;
public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<int?> CurrentDedicatedComputeNodesProperty;
public readonly PropertyAccessor<int?> CurrentLowPriorityComputeNodesProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<IList<MountConfiguration>> MountConfigurationProperty;
public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty;
public readonly PropertyAccessor<IReadOnlyList<ResizeError>> ResizeErrorsProperty;
public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty;
public readonly PropertyAccessor<StartTask> StartTaskProperty;
public readonly PropertyAccessor<Common.PoolState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<PoolStatistics> StatisticsProperty;
public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty;
public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty;
public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty;
public readonly PropertyAccessor<int?> TaskSlotsPerNodeProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty;
public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty;
public readonly PropertyAccessor<string> VirtualMachineSizeProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AllocationStateProperty = this.CreatePropertyAccessor<Common.AllocationState?>(nameof(AllocationState), BindingAccess.None);
this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(AllocationStateTransitionTime), BindingAccess.None);
this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleRunProperty = this.CreatePropertyAccessor<AutoScaleRun>(nameof(AutoScaleRun), BindingAccess.None);
this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None);
this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentDedicatedComputeNodes), BindingAccess.None);
this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentLowPriorityComputeNodes), BindingAccess.None);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write);
this.MountConfigurationProperty = this.CreatePropertyAccessor<IList<MountConfiguration>>(nameof(MountConfiguration), BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write);
this.ResizeErrorsProperty = this.CreatePropertyAccessor<IReadOnlyList<ResizeError>>(nameof(ResizeErrors), BindingAccess.None);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write);
this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.PoolState?>(nameof(State), BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<PoolStatistics>(nameof(Statistics), BindingAccess.None);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write);
this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor<int?>(nameof(TaskSlotsPerNode), BindingAccess.Read | BindingAccess.Write);
this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None);
this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudPool protocolObject) : base(BindingState.Bound)
{
this.AllocationStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.AllocationState, Common.AllocationState>(protocolObject.AllocationState),
nameof(AllocationState),
BindingAccess.Read);
this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.AllocationStateTransitionTime,
nameof(AllocationStateTransitionTime),
BindingAccess.Read);
this.ApplicationLicensesProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o),
nameof(ApplicationLicenses),
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),
nameof(ApplicationPackageReferences),
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableAutoScale,
nameof(AutoScaleEnabled),
BindingAccess.Read);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleEvaluationInterval,
nameof(AutoScaleEvaluationInterval),
BindingAccess.Read);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleFormula,
nameof(AutoScaleFormula),
BindingAccess.Read);
this.AutoScaleRunProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AutoScaleRun, o => new AutoScaleRun(o).Freeze()),
nameof(AutoScaleRun),
BindingAccess.Read);
this.CertificateReferencesProperty = this.CreatePropertyAccessor(
CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences),
nameof(CertificateReferences),
BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o).Freeze()),
nameof(CloudServiceConfiguration),
BindingAccess.Read);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
nameof(CreationTime),
BindingAccess.Read);
this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.CurrentDedicatedNodes,
nameof(CurrentDedicatedComputeNodes),
BindingAccess.Read);
this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.CurrentLowPriorityNodes,
nameof(CurrentLowPriorityComputeNodes),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
nameof(ETag),
BindingAccess.Read);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableInterNodeCommunication,
nameof(InterComputeNodeCommunicationEnabled),
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
nameof(LastModified),
BindingAccess.Read);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
nameof(Metadata),
BindingAccess.Read | BindingAccess.Write);
this.MountConfigurationProperty = this.CreatePropertyAccessor(
Batch.MountConfiguration.ConvertFromProtocolCollectionAndFreeze(protocolObject.MountConfiguration),
nameof(MountConfiguration),
BindingAccess.Read);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()),
nameof(NetworkConfiguration),
BindingAccess.Read);
this.ResizeErrorsProperty = this.CreatePropertyAccessor(
ResizeError.ConvertFromProtocolCollectionReadOnly(protocolObject.ResizeErrors),
nameof(ResizeErrors),
BindingAccess.Read);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor(
protocolObject.ResizeTimeout,
nameof(ResizeTimeout),
BindingAccess.Read);
this.StartTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)),
nameof(StartTask),
BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.PoolState, Common.PoolState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new PoolStatistics(o).Freeze()),
nameof(Statistics),
BindingAccess.Read);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetDedicatedNodes,
nameof(TargetDedicatedComputeNodes),
BindingAccess.Read);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetLowPriorityNodes,
nameof(TargetLowPriorityComputeNodes),
BindingAccess.Read);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o).Freeze()),
nameof(TaskSchedulingPolicy),
BindingAccess.Read);
this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor(
protocolObject.TaskSlotsPerNode,
nameof(TaskSlotsPerNode),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
this.UserAccountsProperty = this.CreatePropertyAccessor(
UserAccount.ConvertFromProtocolCollectionAndFreeze(protocolObject.UserAccounts),
nameof(UserAccounts),
BindingAccess.Read);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o).Freeze()),
nameof(VirtualMachineConfiguration),
BindingAccess.Read);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(
protocolObject.VmSize,
nameof(VirtualMachineSize),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CloudPool"/> class.
/// </summary>
/// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param>
/// <param name='baseBehaviors'>The base behaviors to use.</param>
internal CloudPool(
BatchClient parentBatchClient,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.propertyContainer = new PropertyContainer();
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
}
internal CloudPool(
BatchClient parentBatchClient,
Models.CloudPool protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudPool"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudPool
/// <summary>
/// Gets an <see cref="Common.AllocationState"/> which indicates what node allocation activity is occurring on the
/// pool.
/// </summary>
public Common.AllocationState? AllocationState
{
get { return this.propertyContainer.AllocationStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the pool entered its current <see cref="AllocationState"/>.
/// </summary>
public DateTime? AllocationStateTransitionTime
{
get { return this.propertyContainer.AllocationStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets the list of application licenses the Batch service will make available on each compute node in the
/// pool.
/// </summary>
/// <remarks>
/// <para>The list of application licenses must be a subset of available Batch service application licenses.</para><para>The
/// permitted licenses available on the pool are 'maya', 'vray', '3dsmax', 'arnold'. An additional charge applies
/// for each application license added to the pool.</para>
/// </remarks>
public IList<string> ApplicationLicenses
{
get { return this.propertyContainer.ApplicationLicensesProperty.Value; }
set
{
this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets a list of application packages to be installed on each compute node in the pool.
/// </summary>
/// <remarks>
/// Changes to application package references affect all new compute nodes joining the pool, but do not affect compute
/// nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application
/// package references on any given pool.
/// </remarks>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether the pool size should automatically adjust according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// <para>If true, the <see cref="AutoScaleFormula"/> property is required, the pool automatically resizes according
/// to the formula, and <see cref="TargetDedicatedComputeNodes"/> and <see cref="TargetLowPriorityComputeNodes"/>
/// must be null.</para> <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/>
/// properties is required.</para><para>The default value is false.</para>
/// </remarks>
public bool? AutoScaleEnabled
{
get { return this.propertyContainer.AutoScaleEnabledProperty.Value; }
set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; }
}
/// <summary>
/// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// The default value is 15 minutes. The minimum allowed value is 5 minutes.
/// </remarks>
public TimeSpan? AutoScaleEvaluationInterval
{
get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; }
set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; }
}
/// <summary>
/// Gets or sets a formula for the desired number of compute nodes in the pool.
/// </summary>
/// <remarks>
/// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/.
/// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled
/// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid,
/// an exception is thrown when you try to commit the <see cref="CloudPool"/>.</para>
/// </remarks>
public string AutoScaleFormula
{
get { return this.propertyContainer.AutoScaleFormulaProperty.Value; }
set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; }
}
/// <summary>
/// Gets the results and errors from the last execution of the <see cref="AutoScaleFormula"/>.
/// </summary>
public AutoScaleRun AutoScaleRun
{
get { return this.propertyContainer.AutoScaleRunProperty.Value; }
}
/// <summary>
/// Gets or sets a list of certificates to be installed on each compute node in the pool.
/// </summary>
public IList<CertificateReference> CertificateReferences
{
get { return this.propertyContainer.CertificateReferencesProperty.Value; }
set
{
this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool.
/// </summary>
public CloudServiceConfiguration CloudServiceConfiguration
{
get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; }
set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets the creation time for the pool.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets the number of dedicated compute nodes currently in the pool.
/// </summary>
public int? CurrentDedicatedComputeNodes
{
get { return this.propertyContainer.CurrentDedicatedComputeNodesProperty.Value; }
}
/// <summary>
/// Gets the number of low-priority compute nodes currently in the pool.
/// </summary>
/// <remarks>
/// Low-priority compute nodes which have been preempted are included in this count.
/// </remarks>
public int? CurrentLowPriorityComputeNodes
{
get { return this.propertyContainer.CurrentLowPriorityComputeNodesProperty.Value; }
}
/// <summary>
/// Gets or sets the display name of the pool.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets the ETag for the pool.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets or sets the id of the pool.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether the pool permits direct communication between its compute nodes.
/// </summary>
/// <remarks>
/// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes
/// of the pool. This may result in the pool not reaching its desired size.
/// </remarks>
public bool? InterComputeNodeCommunicationEnabled
{
get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; }
set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the pool.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with the pool as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets a list of file systems to mount on each node in the pool.
/// </summary>
/// <remarks>
/// This supports Azure Files, NFS, CIFS/SMB, and Blobfuse.
/// </remarks>
public IList<MountConfiguration> MountConfiguration
{
get { return this.propertyContainer.MountConfigurationProperty.Value; }
set
{
this.propertyContainer.MountConfigurationProperty.Value = ConcurrentChangeTrackedModifiableList<MountConfiguration>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the network configuration of the pool.
/// </summary>
public NetworkConfiguration NetworkConfiguration
{
get { return this.propertyContainer.NetworkConfigurationProperty.Value; }
set { this.propertyContainer.NetworkConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets a list of errors encountered while performing the last resize on the <see cref="CloudPool"/>. Errors are
/// returned only when the Batch service encountered an error while resizing the pool, and when the pool's <see cref="CloudPool.AllocationState"/>
/// is <see cref="Common.AllocationState.Steady">Steady</see>.
/// </summary>
public IReadOnlyList<ResizeError> ResizeErrors
{
get { return this.propertyContainer.ResizeErrorsProperty.Value; }
}
/// <summary>
/// Gets or sets the timeout for allocation of compute nodes to the pool.
/// </summary>
public TimeSpan? ResizeTimeout
{
get { return this.propertyContainer.ResizeTimeoutProperty.Value; }
set { this.propertyContainer.ResizeTimeoutProperty.Value = value; }
}
/// <summary>
/// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to
/// the pool or when the node is restarted.
/// </summary>
public StartTask StartTask
{
get { return this.propertyContainer.StartTaskProperty.Value; }
set { this.propertyContainer.StartTaskProperty.Value = value; }
}
/// <summary>
/// Gets the current state of the pool.
/// </summary>
public Common.PoolState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the pool entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets the resource usage statistics for the pool.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudPool"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch
/// service performs periodic roll-up of statistics. The typical delay is about 30 minutes.
/// </remarks>
public PoolStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets or sets the desired number of dedicated compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property
/// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false.
/// If not specified, the default is 0.
/// </remarks>
public int? TargetDedicatedComputeNodes
{
get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; }
set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets the desired number of low-priority compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/>
/// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default
/// is 0.
/// </remarks>
public int? TargetLowPriorityComputeNodes
{
get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; }
set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets how tasks are distributed among compute nodes in the pool.
/// </summary>
public TaskSchedulingPolicy TaskSchedulingPolicy
{
get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; }
set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; }
}
/// <summary>
/// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool.
/// </summary>
/// <remarks>
/// The default value is 1. The maximum value is the smaller of 4 times the number of cores of the <see cref="VirtualMachineSize"/>
/// of the pool or 256.
/// </remarks>
public int? TaskSlotsPerNode
{
get { return this.propertyContainer.TaskSlotsPerNodeProperty.Value; }
set { this.propertyContainer.TaskSlotsPerNodeProperty.Value = value; }
}
/// <summary>
/// Gets the URL of the pool.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets the list of user accounts to be created on each node in the pool.
/// </summary>
public IList<UserAccount> UserAccounts
{
get { return this.propertyContainer.UserAccountsProperty.Value; }
set
{
this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool.
/// </summary>
public VirtualMachineConfiguration VirtualMachineConfiguration
{
get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; }
set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size.
/// </summary>
/// <remarks>
/// <para>For information about available sizes of virtual machines in pools, see Choose a VM size for compute nodes
/// in an Azure Batch pool (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes).</para>
/// </remarks>
public string VirtualMachineSize
{
get { return this.propertyContainer.VirtualMachineSizeProperty.Value; }
set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; }
}
#endregion // CloudPool
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.PoolAddParameter ITransportObjectProvider<Models.PoolAddParameter>.GetTransportObject()
{
Models.PoolAddParameter result = new Models.PoolAddParameter()
{
ApplicationLicenses = this.ApplicationLicenses,
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
EnableAutoScale = this.AutoScaleEnabled,
AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval,
AutoScaleFormula = this.AutoScaleFormula,
CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences),
CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
Id = this.Id,
EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled,
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
MountConfiguration = UtilitiesInternal.ConvertToProtocolCollection(this.MountConfiguration),
NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()),
ResizeTimeout = this.ResizeTimeout,
StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()),
TargetDedicatedNodes = this.TargetDedicatedComputeNodes,
TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes,
TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()),
TaskSlotsPerNode = this.TaskSlotsPerNode,
UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts),
VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()),
VmSize = this.VirtualMachineSize,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using NetworkedPlanet.Brightstar;
using NetworkedPlanet.Brightstar.Storage;
using NetworkedPlanet.Rdf;
using VDS.RDF;
using VDS.RDF.Parsing;
using VDS.RDF.Query;
using System.Linq;
namespace NetworkedPlanet.Brightstar.Tests.Sparql11TestSuite {
[TestClass]
public partial class Aggregates : SparqlTest {
public Aggregates() : base()
{
}
[TestInitialize]
public void SetUp()
{
CreateStore();
}
[TestCleanup]
public void TearDown()
{
DeleteStore();
}
#region Test Methods
[TestMethod]
public void Count1() {
ImportData(@"aggregates/agg01.ttl");
var result = ExecuteQuery(@"aggregates/agg01.rq");
CheckResult(result, @"aggregates/agg01.srx", false);
}
[TestMethod]
public void Count2() {
ImportData(@"aggregates/agg01.ttl");
var result = ExecuteQuery(@"aggregates/agg02.rq");
CheckResult(result, @"aggregates/agg02.srx", false);
}
[TestMethod]
public void Count3() {
ImportData(@"aggregates/agg01.ttl");
var result = ExecuteQuery(@"aggregates/agg03.rq");
CheckResult(result, @"aggregates/agg03.srx", false);
}
[TestMethod]
public void Count4() {
ImportData(@"aggregates/agg01.ttl");
var result = ExecuteQuery(@"aggregates/agg04.rq");
CheckResult(result, @"aggregates/agg04.srx", false);
}
[TestMethod]
public void Count5() {
ImportData(@"aggregates/agg01.ttl");
var result = ExecuteQuery(@"aggregates/agg05.rq");
CheckResult(result, @"aggregates/agg05.srx", false);
}
[TestMethod]
public void Count6() {
ImportData(@"aggregates/agg01.ttl");
var result = ExecuteQuery(@"aggregates/agg06.rq");
CheckResult(result, @"aggregates/agg06.srx", false);
}
[TestMethod]
public void Count7() {
ImportData(@"aggregates/agg01.ttl");
var result = ExecuteQuery(@"aggregates/agg07.rq");
CheckResult(result, @"aggregates/agg07.srx", false);
}
[TestMethod]
public void Count8b() {
ImportData(@"aggregates/agg08.ttl");
var result = ExecuteQuery(@"aggregates/agg08b.rq");
CheckResult(result, @"aggregates/agg08b.srx", false);
}
[TestMethod]
public void ErrorInAvg() {
ImportData(@"aggregates/agg-err-01.ttl");
var result = ExecuteQuery(@"aggregates/agg-err-01.rq");
CheckResult(result, @"aggregates/agg-err-01.srx", false);
}
[TestMethod]
public void ProtectFromErrorInAvg() {
ImportData(@"aggregates/agg-err-02.ttl");
var result = ExecuteQuery(@"aggregates/agg-err-02.rq");
CheckResult(result, @"aggregates/agg-err-02.srx", false);
}
[TestMethod]
public void Group_concat1() {
ImportData(@"aggregates/agg-groupconcat-1.ttl");
var result = ExecuteQuery(@"aggregates/agg-groupconcat-1.rq");
CheckResult(result, @"aggregates/agg-groupconcat-1.srx", false);
}
[TestMethod]
public void Group_concat2() {
ImportData(@"aggregates/agg-groupconcat-1.ttl");
var result = ExecuteQuery(@"aggregates/agg-groupconcat-2.rq");
CheckResult(result, @"aggregates/agg-groupconcat-2.srx", false);
}
[TestMethod]
public void Group_concatWithSeparator() {
ImportData(@"aggregates/agg-groupconcat-1.ttl");
var result = ExecuteQuery(@"aggregates/agg-groupconcat-3.rq");
CheckResult(result, @"aggregates/agg-groupconcat-3.srx", false);
}
[TestMethod]
public void Avg() {
ImportData(@"aggregates/agg-numeric.ttl");
var result = ExecuteQuery(@"aggregates/agg-avg-01.rq");
CheckResult(result, @"aggregates/agg-avg-01.srx", false);
}
[TestMethod]
public void AvgWithGroupBy() {
ImportData(@"aggregates/agg-numeric2.ttl");
var result = ExecuteQuery(@"aggregates/agg-avg-02.rq");
CheckResult(result, @"aggregates/agg-avg-02.srx", false);
}
[TestMethod]
public void Min() {
ImportData(@"aggregates/agg-numeric.ttl");
var result = ExecuteQuery(@"aggregates/agg-min-01.rq");
CheckResult(result, @"aggregates/agg-min-01.srx", false);
}
[TestMethod]
public void MinWithGroupBy() {
ImportData(@"aggregates/agg-numeric.ttl");
var result = ExecuteQuery(@"aggregates/agg-min-02.rq");
CheckResult(result, @"aggregates/agg-min-02.srx", false);
}
[TestMethod]
public void Max() {
ImportData(@"aggregates/agg-numeric.ttl");
var result = ExecuteQuery(@"aggregates/agg-max-01.rq");
CheckResult(result, @"aggregates/agg-max-01.srx", false);
}
[TestMethod]
public void MaxWithGroupBy() {
ImportData(@"aggregates/agg-numeric.ttl");
var result = ExecuteQuery(@"aggregates/agg-max-02.rq");
CheckResult(result, @"aggregates/agg-max-02.srx", false);
}
[TestMethod]
public void Sum() {
ImportData(@"aggregates/agg-numeric.ttl");
var result = ExecuteQuery(@"aggregates/agg-sum-01.rq");
CheckResult(result, @"aggregates/agg-sum-01.srx", false);
}
[TestMethod]
public void SumWithGroupBy() {
ImportData(@"aggregates/agg-numeric2.ttl");
var result = ExecuteQuery(@"aggregates/agg-sum-02.rq");
CheckResult(result, @"aggregates/agg-sum-02.srx", false);
}
[TestMethod]
public void Sample() {
ImportData(@"aggregates/agg-numeric.ttl");
var result = ExecuteQuery(@"aggregates/agg-sample-01.rq");
CheckResult(result, @"aggregates/agg-sample-01.srx", false);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
namespace BLToolkit.TypeBuilder.Builders
{
using Properties;
using Reflection;
using Reflection.Emit;
public class DefaultTypeBuilder : AbstractTypeBuilderBase
{
#region Interface Overrides
public override bool IsCompatible(BuildContext context, IAbstractTypeBuilder typeBuilder)
{
return IsRelative(typeBuilder) == false;
}
public override bool IsApplied(BuildContext context, AbstractTypeBuilderList builders)
{
if (context == null) throw new ArgumentNullException("context");
if (context.IsAbstractProperty && context.IsBeforeOrBuildStep)
{
return context.CurrentProperty.GetIndexParameters().Length <= 1;
}
return context.BuildElement == BuildElement.Type && context.IsAfterStep;
}
#endregion
#region Get/Set Implementation
protected override void BuildAbstractGetter()
{
FieldBuilder field = GetField();
ParameterInfo[] index = Context.CurrentProperty.GetIndexParameters();
switch (index.Length)
{
case 0:
Context.MethodBuilder.Emitter
.ldarg_0
.ldfld (field)
.stloc (Context.ReturnValue)
;
break;
case 1:
Context.MethodBuilder.Emitter
.ldarg_0
.ldfld (field)
.ldarg_1
.boxIfValueType (index[0].ParameterType)
.callvirt (typeof(Hashtable), "get_Item", typeof(object))
.castType (Context.CurrentProperty.PropertyType)
.stloc (Context.ReturnValue)
;
break;
}
}
protected override void BuildAbstractSetter()
{
FieldBuilder field = GetField();
ParameterInfo[] index = Context.CurrentProperty.GetIndexParameters();
switch (index.Length)
{
case 0:
Context.MethodBuilder.Emitter
.ldarg_0
.ldarg_1
.stfld (field)
;
//Context.MethodBuilder.Emitter.AddMaxStackSize(6);
break;
case 1:
Context.MethodBuilder.Emitter
.ldarg_0
.ldfld (field)
.ldarg_1
.boxIfValueType (index[0].ParameterType)
.ldarg_2
.boxIfValueType (Context.CurrentProperty.PropertyType)
.callvirt (typeof(Hashtable), "set_Item", typeof(object), typeof(object))
;
break;
}
}
#endregion
#region Call Base Method
protected override void BuildVirtualGetter()
{
CallBaseMethod();
}
protected override void BuildVirtualSetter()
{
CallBaseMethod();
}
protected override void BuildVirtualMethod()
{
CallBaseMethod();
}
private void CallBaseMethod()
{
EmitHelper emit = Context.MethodBuilder.Emitter;
MethodInfo method = Context.MethodBuilder.OverriddenMethod;
ParameterInfo[] ps = method.GetParameters();
emit.ldarg_0.end();
for (int i = 0; i < ps.Length; i++)
emit.ldarg(i + 1);
emit.call(method);
if (Context.ReturnValue != null)
emit.stloc(Context.ReturnValue);
}
#endregion
#region Properties
private static TypeHelper _initContextType;
protected static TypeHelper InitContextType
{
get
{
if (_initContextType == null)
_initContextType = new TypeHelper(typeof(InitContext));
return _initContextType;
}
}
#endregion
#region Field Initialization
#region Overrides
protected override void BeforeBuildAbstractGetter()
{
CallLazyInstanceInsurer(GetField());
}
protected override void BeforeBuildAbstractSetter()
{
FieldBuilder field = GetField();
if (field.FieldType != Context.CurrentProperty.PropertyType)
CallLazyInstanceInsurer(field);
}
#endregion
#region Common
protected FieldBuilder GetField()
{
PropertyInfo propertyInfo = Context.CurrentProperty;
string fieldName = GetFieldName();
Type fieldType = GetFieldType();
FieldBuilder field = Context.GetField(fieldName);
if (field == null)
{
field = Context.CreatePrivateField(propertyInfo, fieldName, fieldType);
if (TypeAccessor.IsInstanceBuildable(fieldType))
{
bool noInstance = propertyInfo.GetCustomAttributes(typeof(NoInstanceAttribute), true).Length > 0;
if (IsObjectHolder && noInstance)
{
BuildHolderInstance(Context.TypeBuilder.DefaultConstructor.Emitter);
BuildHolderInstance(Context.TypeBuilder.InitConstructor.Emitter);
}
else if (!noInstance)
{
if (fieldType.IsClass && IsLazyInstance(fieldType))
{
BuildLazyInstanceEnsurer();
}
else
{
BuildDefaultInstance();
BuildInitContextInstance();
}
}
}
}
return field;
}
#endregion
#region Build
private void BuildHolderInstance(EmitHelper emit)
{
string fieldName = GetFieldName();
FieldBuilder field = Context.GetField(fieldName);
TypeHelper fieldType = new TypeHelper(field.FieldType);
TypeHelper objectType = new TypeHelper(GetObjectType());
ConstructorInfo ci = fieldType.GetPublicDefaultConstructor();
if (ci != null)
{
emit
.ldarg_0
.newobj (ci)
.stfld (field)
;
}
else
{
if (!CheckObjectHolderCtor(fieldType, objectType))
return;
emit
.ldarg_0
.ldnull
.newobj (fieldType, objectType)
.stfld (field)
;
}
}
private void CreateDefaultInstance(
FieldBuilder field, TypeHelper fieldType, TypeHelper objectType, EmitHelper emit)
{
if (!CheckObjectHolderCtor(fieldType, objectType))
return;
if (objectType.Type == typeof(string))
{
emit
.ldarg_0
.LoadInitValue (objectType)
;
}
else if (objectType.IsArray)
{
FieldBuilder initializer = GetArrayInitializer(objectType);
emit
.ldarg_0
.ldsfld (initializer)
;
}
else
{
ConstructorInfo ci = objectType.GetPublicDefaultConstructor();
if (ci == null)
{
if (objectType.Type.IsValueType)
return;
string message = string.Format(
Resources.TypeBuilder_PropertyTypeHasNoPublicDefaultCtor,
Context.CurrentProperty.Name,
Context.Type.FullName,
objectType.FullName);
emit
.ldstr (message)
.newobj (typeof(TypeBuilderException), typeof(string))
.@throw
.end()
;
return;
}
else
{
emit
.ldarg_0
.newobj (ci)
;
}
}
if (IsObjectHolder)
{
emit
.newobj (fieldType, objectType)
;
}
emit
.stfld (field)
;
}
private void CreateParametrizedInstance(
FieldBuilder field, TypeHelper fieldType, TypeHelper objectType, EmitHelper emit, object[] parameters)
{
if (!CheckObjectHolderCtor(fieldType, objectType))
return;
Stack<ConstructorInfo> genericNestedConstructors;
if (parameters.Length == 1)
{
object o = parameters[0];
if (o == null)
{
if (objectType.IsValueType == false)
emit
.ldarg_0
.ldnull
.end()
;
if (IsObjectHolder)
{
emit
.newobj (fieldType, objectType)
;
}
else
{
if (objectType.Type.IsGenericType)
{
Type nullableType = null;
genericNestedConstructors = GetGenericNestedConstructors(
objectType,
delegate(TypeHelper typeHelper)
{
return
typeHelper.IsValueType == false ||
(typeHelper.Type.IsGenericType &&
typeHelper.Type.GetGenericTypeDefinition() == typeof(Nullable<>));
},
delegate(TypeHelper typeHelper) { nullableType = typeHelper.Type; },
delegate() { return nullableType != null; });
if (nullableType == null)
throw new Exception("Cannot find nullable type in generic types chain");
if (nullableType.IsValueType == false)
{
emit
.ldarg_0
.ldnull
.end()
;
}
else
{
LocalBuilder nullable = emit.DeclareLocal(nullableType);
emit
.ldloca(nullable)
.initobj(nullableType)
.ldarg_0
.ldloc(nullable)
;
if (genericNestedConstructors != null)
{
while (genericNestedConstructors.Count != 0)
{
emit
.newobj(genericNestedConstructors.Pop())
;
}
}
}
}
}
emit
.stfld (field)
;
return;
}
if (objectType.Type == o.GetType())
{
if (objectType.Type == typeof(string))
{
emit
.ldarg_0
.ldstr ((string)o)
.stfld (field)
;
return;
}
if (objectType.IsValueType)
{
emit.ldarg_0.end();
if (emit.LoadWellKnownValue(o) == false)
{
emit
.ldsfld (GetParameterField())
.ldc_i4_0
.ldelem_ref
.end()
;
}
emit.stfld(field);
return;
}
}
}
Type[] types = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i] != null)
{
Type t = parameters[i].GetType();
types[i] = (t.IsEnum) ? Enum.GetUnderlyingType(t) : t;
}
else
types[i] = typeof(object);
}
// Do some heuristics for Nullable<DateTime> and EditableValue<Decimal>
//
ConstructorInfo objectCtor = null;
genericNestedConstructors = GetGenericNestedConstructors(
objectType,
delegate(TypeHelper typeHelper) { return true; },
delegate(TypeHelper typeHelper) { objectCtor = typeHelper.GetPublicConstructor(types); },
delegate() { return objectCtor != null; }
);
if (objectCtor == null)
{
if (objectType.IsValueType)
return;
throw new TypeBuilderException(
string.Format(types.Length == 0?
Resources.TypeBuilder_PropertyTypeHasNoPublicDefaultCtor:
Resources.TypeBuilder_PropertyTypeHasNoPublicCtor,
Context.CurrentProperty.Name,
Context.Type.FullName,
objectType.FullName));
}
ParameterInfo[] pi = objectCtor.GetParameters();
emit.ldarg_0.end();
for (int i = 0; i < parameters.Length; i++)
{
object o = parameters[i];
Type oType = o.GetType();
if (emit.LoadWellKnownValue(o))
{
if (oType.IsValueType)
{
if (!pi[i].ParameterType.IsValueType)
emit.box(oType);
else if (Type.GetTypeCode(oType) != Type.GetTypeCode(pi[i].ParameterType))
emit.conv(pi[i].ParameterType);
}
}
else
{
emit
.ldsfld (GetParameterField())
.ldc_i4 (i)
.ldelem_ref
.CastFromObject (types[i])
;
if (oType.IsValueType && !pi[i].ParameterType.IsValueType)
emit.box(oType);
}
}
emit
.newobj (objectCtor)
;
if (genericNestedConstructors != null)
{
while (genericNestedConstructors.Count != 0)
{
emit
.newobj(genericNestedConstructors.Pop())
;
}
}
if (IsObjectHolder)
{
emit
.newobj (fieldType, objectType)
;
}
emit
.stfld (field)
;
}
#if !FW3
/// <summary>Encapsulates a method that has no parameters and returns a value of the type specified by the <paramref name="TResult" /> parameter.</summary>
/// <returns>The return value of the method that this delegate encapsulates.</returns>
private delegate TResult Func<TResult>();
#endif
private Stack<ConstructorInfo> GetGenericNestedConstructors(TypeHelper objectType,
Predicate<TypeHelper> isActionable,
Action<TypeHelper> action,
Func<bool> isBreakCondition)
{
Stack<ConstructorInfo> genericNestedConstructors = null;
if (isActionable(objectType))
action(objectType);
while (objectType.Type.IsGenericType && !isBreakCondition())
{
Type[] typeArgs = objectType.Type.GetGenericArguments();
if (typeArgs.Length == 1)
{
ConstructorInfo genericCtor = objectType.GetPublicConstructor(typeArgs[0]);
if (genericCtor != null)
{
if (genericNestedConstructors == null)
genericNestedConstructors = new Stack<ConstructorInfo>();
genericNestedConstructors.Push(genericCtor);
objectType = typeArgs[0];
if (isActionable(objectType))
action(objectType);
}
}
else
{
throw new TypeBuilderException(
string.Format(Resources.TypeBuilder_GenericShouldBeSingleTyped,
Context.CurrentProperty.Name,
Context.Type.FullName,
objectType.FullName));
}
}
return genericNestedConstructors;
}
#endregion
#region Build InitContext Instance
private void BuildInitContextInstance()
{
string fieldName = GetFieldName();
FieldBuilder field = Context.GetField(fieldName);
TypeHelper fieldType = new TypeHelper(field.FieldType);
TypeHelper objectType = new TypeHelper(GetObjectType());
EmitHelper emit = Context.TypeBuilder.InitConstructor.Emitter;
object[] parameters = TypeHelper.GetPropertyParameters(Context.CurrentProperty);
ConstructorInfo ci = objectType.GetPublicConstructor(typeof(InitContext));
if (ci != null && ci.GetParameters()[0].ParameterType != typeof(InitContext))
ci = null;
if (ci != null || objectType.IsAbstract)
CreateAbstractInitContextInstance(field, fieldType, objectType, emit, parameters);
else if (parameters == null)
CreateDefaultInstance(field, fieldType, objectType, emit);
else
CreateParametrizedInstance(field, fieldType, objectType, emit, parameters);
}
private void CreateAbstractInitContextInstance(
FieldBuilder field, TypeHelper fieldType, TypeHelper objectType, EmitHelper emit, object[] parameters)
{
if (!CheckObjectHolderCtor(fieldType, objectType))
return;
MethodInfo memberParams = InitContextType.GetProperty("MemberParameters").GetSetMethod();
LocalBuilder parentField = (LocalBuilder)Context.Items["$BLToolkit.InitContext.Parent"];
if (parentField == null)
{
Context.Items["$BLToolkit.InitContext.Parent"] = parentField = emit.DeclareLocal(typeof(object));
Label label = emit.DefineLabel();
emit
.ldarg_1
.brtrue_s (label)
.newobj (InitContextType.GetPublicDefaultConstructor())
.starg (1)
.ldarg_1
.ldc_i4_1
.callvirt (InitContextType.GetProperty("IsInternal").GetSetMethod())
.MarkLabel (label)
.ldarg_1
.callvirt (InitContextType.GetProperty("Parent").GetGetMethod())
.stloc (parentField)
;
}
emit
.ldarg_1
.ldarg_0
.callvirt (InitContextType.GetProperty("Parent").GetSetMethod())
;
object isDirty = Context.Items["$BLToolkit.InitContext.DirtyParameters"];
if (parameters != null)
{
emit
.ldarg_1
.ldsfld (GetParameterField())
.callvirt (memberParams)
;
}
else if (isDirty != null && (bool)isDirty)
{
emit
.ldarg_1
.ldnull
.callvirt (memberParams)
;
}
Context.Items["$BLToolkit.InitContext.DirtyParameters"] = parameters != null;
if (objectType.IsAbstract)
{
emit
.ldarg_0
.ldsfld (GetTypeAccessorField())
.ldarg_1
.callvirtNoGenerics (typeof(TypeAccessor), "CreateInstanceEx", _initContextType)
.isinst (objectType)
;
}
else
{
emit
.ldarg_0
.ldarg_1
.newobj (objectType.GetPublicConstructor(typeof(InitContext)))
;
}
if (IsObjectHolder)
{
emit
.newobj (fieldType, objectType)
;
}
emit
.stfld (field)
;
}
#endregion
#region Build Default Instance
private void BuildDefaultInstance()
{
string fieldName = GetFieldName();
FieldBuilder field = Context.GetField(fieldName);
TypeHelper fieldType = new TypeHelper(field.FieldType);
TypeHelper objectType = new TypeHelper(GetObjectType());
EmitHelper emit = Context.TypeBuilder.DefaultConstructor.Emitter;
object[] ps = TypeHelper.GetPropertyParameters(Context.CurrentProperty);
ConstructorInfo ci = objectType.GetPublicConstructor(typeof(InitContext));
if (ci != null && ci.GetParameters()[0].ParameterType != typeof(InitContext))
ci = null;
if (ci != null || objectType.IsAbstract)
CreateInitContextDefaultInstance(
"$BLToolkit.DefaultInitContext.", field, fieldType, objectType, emit, ps);
else if (ps == null)
CreateDefaultInstance(field, fieldType, objectType, emit);
else
CreateParametrizedInstance(field, fieldType, objectType, emit, ps);
}
private bool CheckObjectHolderCtor(TypeHelper fieldType, TypeHelper objectType)
{
if (IsObjectHolder)
{
ConstructorInfo holderCi = fieldType.GetPublicConstructor(objectType);
if (holderCi == null)
{
string message = string.Format(
Resources.TypeBuilder_PropertyTypeHasNoCtorWithParamType,
Context.CurrentProperty.Name,
Context.Type.FullName,
fieldType.FullName,
objectType.FullName);
Context.TypeBuilder.DefaultConstructor.Emitter
.ldstr (message)
.newobj (typeof(TypeBuilderException), typeof(string))
.@throw
.end()
;
return false;
}
}
return true;
}
private void CreateInitContextDefaultInstance(
string initContextName,
FieldBuilder field,
TypeHelper fieldType,
TypeHelper objectType,
EmitHelper emit,
object[] parameters)
{
if (!CheckObjectHolderCtor(fieldType, objectType))
return;
LocalBuilder initField = GetInitContextBuilder(initContextName, emit);
MethodInfo memberParams = InitContextType.GetProperty("MemberParameters").GetSetMethod();
if (parameters != null)
{
emit
.ldloc (initField)
.ldsfld (GetParameterField())
.callvirt (memberParams)
;
}
else if ((bool)Context.Items["$BLToolkit.Default.DirtyParameters"])
{
emit
.ldloc (initField)
.ldnull
.callvirt (memberParams)
;
}
Context.Items["$BLToolkit.Default.DirtyParameters"] = parameters != null;
if (objectType.IsAbstract)
{
emit
.ldarg_0
.ldsfld (GetTypeAccessorField())
.ldloc (initField)
.callvirtNoGenerics (typeof(TypeAccessor), "CreateInstanceEx", _initContextType)
.isinst (objectType)
;
}
else
{
emit
.ldarg_0
.ldloc (initField)
.newobj (objectType.GetPublicConstructor(typeof(InitContext)))
;
}
if (IsObjectHolder)
{
emit
.newobj (fieldType, objectType)
;
}
emit
.stfld (field)
;
}
private LocalBuilder GetInitContextBuilder(
string initContextName, EmitHelper emit)
{
LocalBuilder initField = (LocalBuilder)Context.Items[initContextName];
if (initField == null)
{
Context.Items[initContextName] = initField = emit.DeclareLocal(InitContextType);
emit
.newobj (InitContextType.GetPublicDefaultConstructor())
.dup
.ldarg_0
.callvirt (InitContextType.GetProperty("Parent").GetSetMethod())
.dup
.ldc_i4_1
.callvirt (InitContextType.GetProperty("IsInternal").GetSetMethod())
.stloc (initField)
;
Context.Items.Add("$BLToolkit.Default.DirtyParameters", false);
}
return initField;
}
#endregion
#region Build Lazy Instance
private bool IsLazyInstance(Type type)
{
object[] attrs =
Context.CurrentProperty.GetCustomAttributes(typeof(LazyInstanceAttribute), true);
if (attrs.Length > 0)
return ((LazyInstanceAttribute)attrs[0]).IsLazy;
attrs = Context.Type.GetAttributes(typeof(LazyInstancesAttribute));
foreach (LazyInstancesAttribute a in attrs)
if (a.Type == typeof(object) || type == a.Type || type.IsSubclassOf(a.Type))
return a.IsLazy;
return false;
}
private void BuildLazyInstanceEnsurer()
{
string fieldName = GetFieldName();
FieldBuilder field = Context.GetField(fieldName);
TypeHelper fieldType = new TypeHelper(field.FieldType);
TypeHelper objectType = new TypeHelper(GetObjectType());
MethodBuilderHelper ensurer = Context.TypeBuilder.DefineMethod(
string.Format("$EnsureInstance{0}", fieldName),
MethodAttributes.Private | MethodAttributes.HideBySig);
EmitHelper emit = ensurer.Emitter;
Label end = emit.DefineLabel();
emit
.ldarg_0
.ldfld (field)
.brtrue_s (end)
;
object[] parameters = TypeHelper.GetPropertyParameters(Context.CurrentProperty);
ConstructorInfo ci = objectType.GetPublicConstructor(typeof(InitContext));
if (ci != null || objectType.IsAbstract)
CreateInitContextLazyInstance(field, fieldType, objectType, emit, parameters);
else if (parameters == null)
CreateDefaultInstance(field, fieldType, objectType, emit);
else
CreateParametrizedInstance(field, fieldType, objectType, emit, parameters);
emit
.MarkLabel(end)
.ret()
;
Context.Items.Add("$BLToolkit.FieldInstanceEnsurer." + fieldName, ensurer);
}
private void CreateInitContextLazyInstance(
FieldBuilder field,
TypeHelper fieldType,
TypeHelper objectType,
EmitHelper emit,
object[] parameters)
{
if (!CheckObjectHolderCtor(fieldType, objectType))
return;
LocalBuilder initField = emit.DeclareLocal(InitContextType);
emit
.newobj (InitContextType.GetPublicDefaultConstructor())
.dup
.ldarg_0
.callvirt (InitContextType.GetProperty("Parent").GetSetMethod())
.dup
.ldc_i4_1
.callvirt (InitContextType.GetProperty("IsInternal").GetSetMethod())
.dup
.ldc_i4_1
.callvirt (InitContextType.GetProperty("IsLazyInstance").GetSetMethod())
;
if (parameters != null)
{
emit
.dup
.ldsfld (GetParameterField())
.callvirt (InitContextType.GetProperty("MemberParameters").GetSetMethod())
;
}
emit
.stloc (initField);
if (objectType.IsAbstract)
{
emit
.ldarg_0
.ldsfld (GetTypeAccessorField())
.ldloc (initField)
.callvirtNoGenerics (typeof(TypeAccessor), "CreateInstanceEx", _initContextType)
.isinst (objectType)
;
}
else
{
emit
.ldarg_0
.ldloc (initField)
.newobj (objectType.GetPublicConstructor(typeof(InitContext)))
;
}
if (IsObjectHolder)
{
emit
.newobj (fieldType, objectType)
;
}
emit
.stfld (field)
;
}
#endregion
#region Finalize Type
protected override void AfterBuildType()
{
object isDirty = Context.Items["$BLToolkit.InitContext.DirtyParameters"];
if (isDirty != null && (bool)isDirty)
{
Context.TypeBuilder.InitConstructor.Emitter
.ldarg_1
.ldnull
.callvirt (InitContextType.GetProperty("MemberParameters").GetSetMethod())
;
}
LocalBuilder parentField = (LocalBuilder)Context.Items["$BLToolkit.InitContext.Parent"];
if (parentField != null)
{
Context.TypeBuilder.InitConstructor.Emitter
.ldarg_1
.ldloc (parentField)
.callvirt (InitContextType.GetProperty("Parent").GetSetMethod())
;
}
FinalizeDefaultConstructors();
FinalizeInitContextConstructors();
}
private void FinalizeDefaultConstructors()
{
ConstructorInfo ci = Context.Type.GetDefaultConstructor();
if (ci == null || Context.TypeBuilder.IsDefaultConstructorDefined)
{
EmitHelper emit = Context.TypeBuilder.DefaultConstructor.Emitter;
if (ci != null)
{
emit.ldarg_0.call(ci);
}
else
{
ci = Context.Type.GetConstructor(typeof(InitContext));
if (ci != null)
{
LocalBuilder initField = GetInitContextBuilder("$BLToolkit.DefaultInitContext.", emit);
emit
.ldarg_0
.ldloc (initField)
.call (ci);
}
else
{
if (Context.Type.GetConstructors().Length > 0)
throw new TypeBuilderException(string.Format(
Resources.TypeBuilder_NoDefaultCtor,
Context.Type.FullName));
}
}
}
}
private void FinalizeInitContextConstructors()
{
ConstructorInfo ci = Context.Type.GetConstructor(typeof(InitContext));
if (ci != null || Context.TypeBuilder.IsInitConstructorDefined)
{
EmitHelper emit = Context.TypeBuilder.InitConstructor.Emitter;
if (ci != null)
{
emit
.ldarg_0
.ldarg_1
.call (ci);
}
else
{
ci = Context.Type.GetDefaultConstructor();
if (ci != null)
{
emit.ldarg_0.call(ci);
}
else
{
if (Context.Type.GetConstructors().Length > 0)
throw new TypeBuilderException(
string.Format(Resources.TypeBuilder_NoDefaultCtor,
Context.Type.FullName));
}
}
}
}
#endregion
#endregion
}
}
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2010 Liquidbit Ltd.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace ServiceStack.Redis.Generic
{
internal class RedisClientList<T>
: IRedisList<T>
{
private readonly RedisTypedClient<T> client;
private readonly string listId;
private const int PageLimit = 1000;
public RedisClientList(RedisTypedClient<T> client, string listId)
{
this.listId = listId;
this.client = client;
}
public string Id
{
get { return listId; }
}
public IEnumerator<T> GetEnumerator()
{
return this.Count <= PageLimit
? client.GetAllItemsFromList(this).GetEnumerator()
: GetPagingEnumerator();
}
public IEnumerator<T> GetPagingEnumerator()
{
var skip = 0;
List<T> pageResults;
do
{
pageResults = client.GetRangeFromList(this, skip, PageLimit);
foreach (var result in pageResults)
{
yield return result;
}
skip += PageLimit;
} while (pageResults.Count == PageLimit);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(T item)
{
client.AddItemToList(this, item);
}
public void Clear()
{
client.RemoveAllFromList(this);
}
public bool Contains(T item)
{
//TODO: replace with native implementation when exists
foreach (var existingItem in this)
{
if (Equals(existingItem, item)) return true;
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
var allItemsInList = client.GetAllItemsFromList(this);
allItemsInList.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
return client.RemoveItemFromList(this, item) > 0;
}
public int Count
{
get
{
return client.GetListCount(this);
}
}
public bool IsReadOnly { get { return false; } }
public int IndexOf(T item)
{
//TODO: replace with native implementation when exists
var i = 0;
foreach (var existingItem in this)
{
if (Equals(existingItem, item)) return i;
i++;
}
return -1;
}
public void Insert(int index, T item)
{
//TODO: replace with implementation involving creating on new temp list then replacing
//otherwise wait for native implementation
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
//TODO: replace with native implementation when one exists
var markForDelete = Guid.NewGuid().ToString();
client.NativeClient.LSet(listId, index, Encoding.UTF8.GetBytes(markForDelete));
const int removeAll = 0;
client.NativeClient.LRem(listId, removeAll, Encoding.UTF8.GetBytes(markForDelete));
}
public T this[int index]
{
get { return client.GetItemFromList(this, index); }
set { client.SetItemInList(this, index, value); }
}
public List<T> GetAll()
{
return client.GetAllItemsFromList(this);
}
public List<T> GetRange(int startingFrom, int endingAt)
{
return client.GetRangeFromList(this, startingFrom, endingAt);
}
public List<T> GetRangeFromSortedList(int startingFrom, int endingAt)
{
return client.SortList(this, startingFrom, endingAt);
}
public void RemoveAll()
{
client.RemoveAllFromList(this);
}
public void Trim(int keepStartingFrom, int keepEndingAt)
{
client.TrimList(this, keepStartingFrom, keepEndingAt);
}
public int RemoveValue(T value)
{
return client.RemoveItemFromList(this, value);
}
public int RemoveValue(T value, int noOfMatches)
{
return client.RemoveItemFromList(this, value, noOfMatches);
}
public void Append(T value)
{
Add(value);
}
public void Prepend(T value)
{
client.PrependItemToList(this, value);
}
public T RemoveStart()
{
return client.RemoveStartFromList(this);
}
public T BlockingRemoveStart(TimeSpan? timeOut)
{
return client.BlockingRemoveStartFromList(this, timeOut);
}
public T RemoveEnd()
{
return client.RemoveEndFromList(this);
}
public void Enqueue(T value)
{
client.EnqueueItemOnList(this, value);
}
public T Dequeue()
{
return client.DequeueItemFromList(this);
}
public T BlockingDequeue(TimeSpan? timeOut)
{
return client.BlockingDequeueItemFromList(this, timeOut);
}
public void Push(T value)
{
client.PushItemToList(this, value);
}
public T Pop()
{
return client.PopItemFromList(this);
}
public T BlockingPop(TimeSpan? timeOut)
{
return client.BlockingPopItemFromList(this, timeOut);
}
public T PopAndPush(IRedisList<T> toList)
{
return client.PopAndPushItemBetweenLists(this, toList);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using System.Xml;
using System.Reflection;
using System.Text;
using System.Security;
using System.Security.Permissions;
using SharpVectors.Dom.Events;
using SharpVectors.Dom.Svg;
using SharpVectors.Xml;
using SharpVectors.Renderer.Gdi;
using SharpVectors.Renderer;
using SharpVectors.Dom.Svg.Rendering;
using SharpVectors.Dom;
using SharpVectors.Dom.Css;
using SharpVectors.Scripting;
using SharpVectors.Collections;
using SharpVectors.Net;
using System.Threading;
[assembly: AllowPartiallyTrustedCallers]
namespace SvgComponents
{
public class SvgPictureBox : System.Windows.Forms.Control
{
private static readonly string UserAgentCssFileName = "useragent.css";
private static readonly string UserCssFileName = "user.css";
private GdiRenderer renderer;
#region Constructors
public SvgPictureBox()
{
InitializeComponent();
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
scriptEngineByMimeType = new TypeDictionary();
SetMimeTypeEngineType("application/ecmascript", typeof(JScriptEngine));
renderer = new GdiRenderer();
renderer.OnRender = new RenderEvent(this.OnRender);
window = new SvgWindow(this, renderer);
}
#endregion
#region Events
public void OnRender(RectangleF updatedRect)
{
if (surface != null)
{
if (updatedRect == RectangleF.Empty)
Draw(surface);
else
Draw(surface, updatedRect);
}
else
{
surface = CreateGraphics();
if (updatedRect == RectangleF.Empty)
Draw(surface);
else
Draw(surface, updatedRect);
surface.Dispose();
surface = null;
}
// Collect the rendering regions for later updates
SvgDocument doc = (window.Document as SvgDocument);
SvgElement root = (doc.RootElement as SvgElement);
//root.CacheRenderingRegion(renderer);
}
private int lastX = -1;
private int lastY = -1;
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (lastX == e.X && lastY == e.Y) return;
lastX = e.X;
lastY = e.Y;
renderer.OnMouseEvent("mousemove", e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
renderer.OnMouseEvent("mousedown", e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
renderer.OnMouseEvent("mouseup", e);
}
#endregion
#region Private fields
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private SvgWindow window;
private bool autoSize = false;
private bool loaded = false;
//private Thread renderThread;
#endregion
#region Public properties
/// <summary>
/// Source URL for the Svg Content
/// </summary>
[Category("Data")]
[DefaultValue("")]
[Description("The URL of the document currently being display in this SvgPictureBox")]
public string SourceURL
{
get
{
return window.Src;
}
set
{
Load(value);
}
}
/// <summary>
/// Return current SvgWindow used by this control
/// </summary>
[Category("Data")]
[DefaultValue("")]
[Description("The Window Interface connected to the SvgPictureBox")]
public ISvgWindow Window
{
get
{
return window;
}
}
/// <summary>
/// Forces the component to autosize to fit the svg
/// </summary>
public bool AutoSize
{
get
{
return autoSize;
}
set
{
autoSize = value;
}
}
#endregion
#region Public methods
public void Load(string value)
{
#if RELEASE
try
{
#endif
// Worry about clearing the graphics nodes map...
renderer.ClearMap();
System.GC.Collect();
System.Threading.Thread.Sleep(1);
if(value != null && value.Length > 0)
{
// Load the source
window.Src = value;
// Initialize the style sheets
SetupStyleSheets();
// Execute all script elements
UnloadEngines();
InitializeEvents();
ExecuteScripts();
//JR
if (autoSize)
{
ISvgSvgElement svgEl = window.Document.RootElement;
this.Width = (int)svgEl.Width.BaseVal.Value;
this.Height = (int)svgEl.Height.BaseVal.Value;
}
renderer.InvalidRect = RectangleF.Empty;
Render();
loaded = true;
}
#if RELEASE
}
catch(Exception e)
{
MessageBox.Show("An error occured while loading the document.\n" + e.Message);
}
#endif
}
public void LoadXml(string xml)
{
#if RELEASE
try
{
#endif
// Worry about clearing the graphics nodes map...
renderer.ClearMap();
System.GC.Collect();
System.Threading.Thread.Sleep(1);
if(xml != null && xml.Length > 0)
{
if(xml != null && xml.Length > 0)
{
SvgDocument doc = window.CreateEmptySvgDocument();
doc.LoadXml(xml);
window.Document = doc;
SetupStyleSheets();
//JR
if (autoSize)
{
ISvgRect r = window.Document.RootElement.GetBBox();
this.Width = (int)r.Width;
this.Height = (int)r.Height;
}
Render();
loaded = true;
}
}
#if RELEASE
}
catch(Exception e)
{
MessageBox.Show("An error occured while loading the document.\n" + e.Message);
}
#endif
}
public void Render()
{
if ( this.window != null )
{
renderAndInvalidate();
}
}
public void Update(RectangleF rect)
{
if ( this.window != null )
{
updateAndInvalidate(rect);
}
}
public void CacheRenderingRegions()
{
// Collect the rendering regions for later updates
System.Threading.Thread.Sleep(1);
SvgDocument doc = (window.Document as SvgDocument);
SvgElement root = (doc.RootElement as SvgElement);
root.CacheRenderingRegion(renderer);
}
private Graphics surface;
public Graphics Surface
{
get { return surface; }
set { surface = value; }
}
public RectangleF InvalidRect
{
get { return renderer.InvalidRect; }
}
/// <summary>
/// Create an empty SvgDocument and GdiRenderer for this control. The empty SvgDocument is returned. This method is needed only in situations where the library user needs to create an SVG DOM tree outside of the usual window Src setting mechanism.
/// </summary>
public SvgDocument CreateEmptySvgDocument()
{
SvgDocument svgDocument = window.CreateEmptySvgDocument();
SetupStyleSheets();
return svgDocument;
}
#endregion
#region Protected methods
private void renderAndInvalidate()
{
#if RELEASE
try
{
#endif
renderer.Render(window.Document as SvgDocument);
#if RELEASE
}
catch(Exception e)
{
MessageBox.Show("An exception occured while rendering: " + e.Message);
}
#endif
}
private void updateAndInvalidate(RectangleF rect)
{
renderer.InvalidateRect(rect);
renderAndInvalidate();
}
public void DrawTo(IntPtr hdc)
{
if ( !this.DesignMode )
{
if ( window != null )
{
GraphicsWrapper gw = GraphicsWrapper.FromHdc(hdc, true);
GdiRenderer r = ((GdiRenderer)window.Renderer);
gw.Clear(r.BackColor);
r.GraphicsWrapper = gw;
window.Renderer.Render((SvgDocument)window.Document);
r.GraphicsWrapper = null;
gw.Dispose();
}
}
}
public void Draw(Graphics gr)
{
if ( !this.DesignMode )
{
if ( window != null )
{
Bitmap rasterImage = ((GdiRenderer) window.Renderer).RasterImage;
if ( rasterImage != null )
{
gr.DrawImage(rasterImage, 0, 0, rasterImage.Width, rasterImage.Height);
}
}
}
}
public void Draw(Graphics gr, int offsetX, int offsetY)
{
if ( !this.DesignMode )
{
if ( window != null )
{
Bitmap rasterImage = ((GdiRenderer) window.Renderer).RasterImage;
if ( rasterImage != null )
{
gr.DrawImage(rasterImage, offsetX, offsetY, rasterImage.Width, rasterImage.Height);
}
}
}
}
public void Draw(Graphics gr, RectangleF rect)
{
if ( !this.DesignMode )
{
if ( window != null )
{
Bitmap rasterImage = ((GdiRenderer) window.Renderer).RasterImage;
if ( rasterImage != null )
{
gr.DrawImage(rasterImage, rect, rect, GraphicsUnit.Pixel);
}
}
}
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
if (surface != null)
{
Draw(surface);
}
else
Draw(e.Graphics);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (loaded)
{
// Worry about clearing the graphics nodes map...
System.GC.Collect();
System.Threading.Thread.Sleep(1);
(window as SvgWindow).Resize(this.Width, this.Height);
renderAndInvalidate();
}
}
/// <summary>
/// Loads the default user and agent stylesheets into the current SvgDocument
/// </summary>
protected virtual void SetupStyleSheets()
{
CssXmlDocument cssDocument = (CssXmlDocument) window.Document;
string appRootPath = SharpVectors.ApplicationContext.ExecutableDirectory.FullName;
FileInfo userAgentCssPath = new FileInfo(appRootPath + "\\" + UserAgentCssFileName);
FileInfo userCssPath = new FileInfo(appRootPath + "\\" + UserCssFileName);
if(userAgentCssPath.Exists)
{
cssDocument.SetUserAgentStyleSheet((new Uri("file:/" + userAgentCssPath.FullName)).AbsoluteUri);
}
if(userCssPath.Exists)
{
cssDocument.SetUserStyleSheet((new Uri("file:/" + userCssPath.FullName)).AbsoluteUri);
}
}
#endregion
#region Scripting Methods and Properties
private TypeDictionary scriptEngineByMimeType;
private Hashtable scriptEngines = new Hashtable();
public void SetMimeTypeEngineType(string mimeType, Type engineType)
{
scriptEngineByMimeType[mimeType] = engineType;
}
public ScriptEngine GetScriptEngineByMimeType(string mimeType)
{
ScriptEngine engine = null;
if (mimeType == "")
mimeType = ((ISvgWindow)window).Document.RootElement.GetAttribute("contentScriptType");
if (mimeType == "" || mimeType == "text/ecmascript" || mimeType == "text/javascript" || mimeType == "application/javascript")
mimeType = "application/ecmascript";
if (!scriptEngines.Contains(mimeType))
{
object[] args = new object[] { (window as ISvgWindow) };
engine = (ScriptEngine)scriptEngineByMimeType.CreateInstance(mimeType, args);
scriptEngines.Add(mimeType,engine);
engine.Initialise();
}
if (engine == null)
engine = (ScriptEngine) scriptEngines[mimeType];
return engine;
}
/// <summary>
/// Clears the existing script engine list from any previously running instances
/// </summary>
private void UnloadEngines()
{
// Dispose of all running engines from previous document instances
foreach (string mimeType in scriptEngines.Keys)
{
ScriptEngine engine = (ScriptEngine)scriptEngines[mimeType];
engine.Close();
engine = null;
}
// Clear the list
scriptEngines.Clear();
ClosureEventMonitor.Clear();
ScriptTimerMonitor.Reset();
}
/// <summary>
/// Add event listeners for on* events within the document
/// </summary>
private void InitializeEvents()
{
SvgDocument document = (SvgDocument)window.Document;
document.NamespaceManager.AddNamespace("svg", "http://www.w3.org/2000/svg");
XmlNodeList nodes = document.SelectNodes(@"//*[namespace-uri()='http://www.w3.org/2000/svg']
[local-name()='svg' or
local-name()='g' or
local-name()='defs' or
local-name()='symbol' or
local-name()='use' or
local-name()='switch' or
local-name()='image' or
local-name()='path' or
local-name()='rect' or
local-name()='circle' or
local-name()='ellipse' or
local-name()='line' or
local-name()='polyline' or
local-name()='polygon' or
local-name()='text' or
local-name()='tref' or
local-name()='tspan' or
local-name()='textPath' or
local-name()='altGlyph' or
local-name()='a' or
local-name()='foreignObject']
/@*[name()='onfocusin' or
name()='onfocusout' or
name()='onactivate' or
name()='onclick' or
name()='onmousedown' or
name()='onmouseup' or
name()='onmouseover' or
name()='onmousemove' or
name()='onmouseout' or
name()='onload']", document.NamespaceManager);
foreach (XmlNode node in nodes)
{
IAttribute att = (IAttribute)node;
IEventTarget targ = (IEventTarget)att.OwnerElement;
ScriptEventMonitor mon = new ScriptEventMonitor((VsaScriptEngine)GetScriptEngineByMimeType(""), att, window);
string eventName = null;
switch (att.Name)
{
case "onfocusin":
eventName = "focusin";
break;
case "onfocusout":
eventName = "focusout";
break;
case "onactivate":
eventName = "activate";
break;
case "onclick":
eventName = "click";
break;
case "onmousedown":
eventName = "mousedown";
break;
case "onmouseup":
eventName = "mouseup";
break;
case "onmouseover":
eventName = "mouseover";
break;
case "onmousemove":
eventName = "mousemove";
break;
case "onmouseout":
eventName = "mouseout";
break;
case "onload":
eventName = "SVGLoad";
break;
}
targ.AddEventListener(eventName, new EventListener(mon.EventHandler), false);
}
}
/// <summary>
/// Collect the text in all script elements, build engine and execute.
/// </summary>
private void ExecuteScripts()
{
Hashtable codeByMimeType = new Hashtable();
StringBuilder codeBuilder;
SvgDocument document = (SvgDocument)window.Document;
XmlNodeList scripts = document.GetElementsByTagName("script", SvgDocument.SvgNamespace);
StringBuilder code = new StringBuilder();
foreach ( XmlElement script in scripts )
{
string type = script.GetAttribute("type");
if ( GetScriptEngineByMimeType(type) != null )
{
// make sure we have a StringBuilder for this MIME type
if ( !codeByMimeType.Contains(type) )
codeByMimeType[type] = new StringBuilder();
// grab this MIME type's codeBuilder
codeBuilder = (StringBuilder) codeByMimeType[type];
if ( script.HasChildNodes )
{
// process each child that is text node or a CDATA section
foreach ( XmlNode node in script.ChildNodes )
{
if ( node.NodeType == XmlNodeType.CDATA || node.NodeType == XmlNodeType.Text )
{
codeBuilder.Append(node.Value);
}
}
}
if (script.HasAttribute("href", "http://www.w3.org/1999/xlink"))
{
string href = script.GetAttribute("href", "http://www.w3.org/1999/xlink");
Uri baseUri = new Uri(((XmlDocument)((ISvgWindow)window).Document).BaseURI);
Uri hUri = new Uri(baseUri, href);
ExtendedHttpWebRequestCreator creator = new ExtendedHttpWebRequestCreator();
ExtendedHttpWebRequest request = (ExtendedHttpWebRequest)creator.Create(hUri);
ExtendedHttpWebResponse response = (ExtendedHttpWebResponse)request.GetResponse();
Stream rs = response.GetResponseStream();
StreamReader sr = new StreamReader(rs);
codeBuilder.Append(sr.ReadToEnd());
rs.Close();
}
}
}
// execute code for all script engines
foreach ( string mimeType in codeByMimeType.Keys )
{
codeBuilder = (StringBuilder) codeByMimeType[mimeType];
if ( codeBuilder.Length > 0 )
{
ScriptEngine engine = GetScriptEngineByMimeType(mimeType);
engine.Execute( codeBuilder.ToString() );
}
}
// load the root element
((ISvgWindow)window).Document.RootElement.DispatchEvent(new Event("SVGLoad", false, true));
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Name = "SvgPictureBox";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
renderer.Dispose();
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.