context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Windows.Forms;
using OpenLiveWriter.Api;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.PostEditor.Tagging
{
/// <summary>
/// Summary description for TagOptions.
/// </summary>
public class TagOptions : BaseForm
{
private ListBox listBoxOptions;
private Label labelTagProviders;
private Button buttonClose;
private Button buttonAdd;
private Button buttonEdit;
private Button buttonDelete;
private Button buttonRestoreDefaults;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public TagOptions()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.buttonClose.Text = Res.Get(StringId.CloseButton);
this.buttonAdd.Text = Res.Get(StringId.AddButton);
this.buttonEdit.Text = Res.Get(StringId.EditButton);
this.buttonDelete.Text = Res.Get(StringId.DeleteButton);
this.labelTagProviders.Text = Res.Get(StringId.TagsTagProvidersLabel);
this.buttonRestoreDefaults.Text = Res.Get(StringId.TagsRestoreDefaults);
this.Text = Res.Get(StringId.TagsTagOptions);
listBoxOptions.KeyUp += TagOptions_KeyUp;
KeyUp += TagOptions_KeyUp;
}
void TagOptions_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
DeleteProvider();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
using (new AutoGrow(this, AnchorStyles.Right, false))
{
DisplayHelper.AutoFitSystemButton(buttonRestoreDefaults);
if (buttonRestoreDefaults.Right > listBoxOptions.Right)
{
int oldWidth = listBoxOptions.Width;
listBoxOptions.Width = buttonRestoreDefaults.Width;
buttonClose.Left =
buttonEdit.Left = buttonDelete.Left = buttonAdd.Left = buttonAdd.Left + listBoxOptions.Width - oldWidth;
}
LayoutHelper.EqualizeButtonWidthsVert(AnchorStyles.Left, buttonClose.Width, int.MaxValue,
buttonAdd, buttonEdit, buttonDelete, buttonClose);
}
}
public void Initialize(TagProviderManager manager)
{
_manager = manager;
RefreshProviders(true);
}
private TagProviderManager _manager;
public void SetContext(TagContext context)
{
_context = context;
}
private TagContext _context;
private void RefreshProviders(bool defaultSelect)
{
if (listBoxOptions != null)
{
listBoxOptions.Items.Clear();
listBoxOptions.Items.AddRange(_manager.TagProviders);
listBoxOptions.Sorted = true;
if (defaultSelect)
listBoxOptions.SelectedIndex = 0;
buttonDelete.Enabled = listBoxOptions.Items.Count > 1;
}
}
/// <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()
{
this.listBoxOptions = new System.Windows.Forms.ListBox();
this.buttonClose = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.labelTagProviders = new System.Windows.Forms.Label();
this.buttonRestoreDefaults = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// listBoxOptions
//
this.listBoxOptions.Location = new System.Drawing.Point(8, 24);
this.listBoxOptions.Name = "listBoxOptions";
this.listBoxOptions.Size = new System.Drawing.Size(200, 134);
this.listBoxOptions.TabIndex = 4;
//
// buttonClose
//
this.buttonClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonClose.Location = new System.Drawing.Point(216, 176);
this.buttonClose.Name = "buttonClose";
this.buttonClose.TabIndex = 6;
this.buttonClose.Text = "&Close";
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
//
// buttonAdd
//
this.buttonAdd.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonAdd.Location = new System.Drawing.Point(216, 24);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.TabIndex = 0;
this.buttonAdd.Text = "A&dd...";
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonEdit
//
this.buttonEdit.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonEdit.Location = new System.Drawing.Point(216, 56);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.TabIndex = 1;
this.buttonEdit.Text = "&Edit...";
this.buttonEdit.Click += new System.EventHandler(this.buttonEdit_Click);
//
// buttonDelete
//
this.buttonDelete.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonDelete.Location = new System.Drawing.Point(216, 136);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.TabIndex = 2;
this.buttonDelete.Text = "&Delete";
this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click);
//
// labelTagProviders
//
this.labelTagProviders.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelTagProviders.Location = new System.Drawing.Point(8, 8);
this.labelTagProviders.Name = "labelTagProviders";
this.labelTagProviders.Size = new System.Drawing.Size(224, 16);
this.labelTagProviders.TabIndex = 3;
this.labelTagProviders.Text = "&Tag providers:";
//
// buttonRestoreDefaults
//
this.buttonRestoreDefaults.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonRestoreDefaults.Location = new System.Drawing.Point(8, 176);
this.buttonRestoreDefaults.Name = "buttonRestoreDefaults";
this.buttonRestoreDefaults.Size = new System.Drawing.Size(128, 23);
this.buttonRestoreDefaults.TabIndex = 5;
this.buttonRestoreDefaults.Text = "&Restore Defaults";
this.buttonRestoreDefaults.Click += new System.EventHandler(this.buttonRestoreDefaults_Click);
//
// TagOptions
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.CancelButton = this.buttonClose;
this.ClientSize = new System.Drawing.Size(299, 214);
this.Controls.Add(this.buttonRestoreDefaults);
this.Controls.Add(this.labelTagProviders);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonEdit);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.listBoxOptions);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "TagOptions";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Tag Options";
this.ResumeLayout(false);
}
#endregion
private void buttonClose_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void buttonAdd_Click(object sender, EventArgs e)
{
EditTagForm tagForm = new EditTagForm();
tagForm.Provider = new TagProvider();
DialogResult result = tagForm.ShowDialog(this);
if (result == DialogResult.OK)
{
TagProvider provider = tagForm.Provider;
_manager.Save(provider);
RefreshProviders(false);
listBoxOptions.SelectedItem = provider;
if (_context != null)
_context.CurrentProvider = provider;
}
}
private void buttonEdit_Click(object sender, EventArgs e)
{
if (!IsValid())
return;
TagProvider provider = (TagProvider)listBoxOptions.SelectedItem;
EditTagForm tagForm = new EditTagForm();
tagForm.Provider = provider;
DialogResult result = tagForm.ShowDialog(this);
if (result == DialogResult.OK)
{
_manager.Save(tagForm.Provider);
RefreshProviders(false);
listBoxOptions.SelectedItem = tagForm.Provider;
}
}
private void DeleteProvider()
{
if (!IsValid())
return;
TagProvider provider = (TagProvider)listBoxOptions.SelectedItem;
DialogResult result = DisplayMessage.Show(MessageId.TagConfirmDeleteProvider, provider.Name);
if (result == DialogResult.Yes)
{
_manager.Delete(provider);
RefreshProviders(true);
}
}
private void buttonDelete_Click(object sender, EventArgs e)
{
DeleteProvider();
}
private bool IsValid()
{
if (listBoxOptions.SelectedIndex == -1)
{
DisplayMessage.Show(MessageId.TagSelectProvider);
return false;
}
return true;
}
private void buttonRestoreDefaults_Click(object sender, EventArgs e)
{
DialogResult result = DisplayMessage.Show(MessageId.TagConfirmRestoreProviders);
if (result == DialogResult.Yes)
_manager.RestoreDefaults();
RefreshProviders(true);
}
}
}
| |
// ScriptCompiler.cs
// Script#/Core/Compiler
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using ScriptSharp.CodeModel;
using ScriptSharp.Compiler;
using ScriptSharp.Generator;
using ScriptSharp.Importer;
using ScriptSharp.ResourceModel;
using ScriptSharp.ScriptModel;
using ScriptSharp.Validator;
namespace ScriptSharp {
/// <summary>
/// The Script# compiler.
/// </summary>
public sealed class ScriptCompiler : IErrorHandler {
private CompilerOptions _options;
private IErrorHandler _errorHandler;
private ParseNodeList _compilationUnitList;
private SymbolSet _symbols;
private ICollection<TypeSymbol> _importedSymbols;
private ICollection<TypeSymbol> _appSymbols;
private bool _hasErrors;
#if DEBUG
private string _testOutput;
#endif
public ScriptCompiler()
: this(null) {
}
public ScriptCompiler(IErrorHandler errorHandler) {
_errorHandler = errorHandler;
}
private void BuildCodeModel() {
_compilationUnitList = new ParseNodeList();
CodeModelBuilder codeModelBuilder = new CodeModelBuilder(_options, this);
CodeModelValidator codeModelValidator = new CodeModelValidator(this);
CodeModelProcessor validationProcessor = new CodeModelProcessor(codeModelValidator, _options);
foreach (IStreamSource source in _options.Sources) {
CompilationUnitNode compilationUnit = codeModelBuilder.BuildCodeModel(source);
if (compilationUnit != null) {
validationProcessor.Process(compilationUnit);
_compilationUnitList.Append(compilationUnit);
}
}
}
private void BuildImplementation() {
CodeBuilder codeBuilder = new CodeBuilder(_options, this);
ICollection<SymbolImplementation> implementations = codeBuilder.BuildCode(_symbols);
if (_options.Minimize) {
foreach (SymbolImplementation impl in implementations) {
if (impl.Scope == null) {
continue;
}
SymbolObfuscator obfuscator = new SymbolObfuscator();
SymbolImplementationTransformer transformer = new SymbolImplementationTransformer(obfuscator);
transformer.TransformSymbolImplementation(impl);
}
}
}
private void BuildMetadata() {
if ((_options.Resources != null) && (_options.Resources.Count != 0)) {
ResourcesBuilder resourcesBuilder = new ResourcesBuilder(_symbols);
resourcesBuilder.BuildResources(_options.Resources);
}
MetadataBuilder mdBuilder = new MetadataBuilder(this);
_appSymbols = mdBuilder.BuildMetadata(_compilationUnitList, _symbols, _options);
// Check if any of the types defined in this assembly conflict.
Dictionary<string, TypeSymbol> types = new Dictionary<string, TypeSymbol>();
foreach (TypeSymbol appType in _appSymbols) {
if ((appType.IsApplicationType == false) || (appType.Type == SymbolType.Delegate)) {
// Skip the check for types that are marked as imported, as they
// aren't going to be generated into the script.
// Delegates are implicitly imported types, as they're never generated into
// the script.
continue;
}
if ((appType.Type == SymbolType.Class) &&
(((ClassSymbol)appType).PrimaryPartialClass != appType)) {
// Skip the check for partial types, since they should only be
// checked once.
continue;
}
// TODO: We could allow conflicting types as long as both aren't public
// since they won't be on the exported types list. Internal types that
// conflict could be generated using full name.
string name = appType.GeneratedName;
if (types.ContainsKey(name)) {
string error = "The type '" + appType.FullName + "' conflicts with with '" + types[name].FullName + "' as they have the same name.";
((IErrorHandler)this).ReportError(error, null);
}
else {
types[name] = appType;
}
}
// Capture whether there are any test types in the project
// when not compiling the test flavor script. This is used to determine
// if the test flavor script should be compiled in the build task.
if (_options.IncludeTests == false) {
foreach (TypeSymbol appType in _appSymbols) {
if (appType.IsApplicationType && appType.IsTestType) {
_options.HasTestTypes = true;
}
}
}
#if DEBUG
if (_options.InternalTestType == "metadata") {
StringWriter testWriter = new StringWriter();
testWriter.WriteLine("Metadata");
testWriter.WriteLine("================================================================");
SymbolSetDumper symbolDumper = new SymbolSetDumper(testWriter);
symbolDumper.DumpSymbols(_symbols);
testWriter.WriteLine();
testWriter.WriteLine();
_testOutput = testWriter.ToString();
}
#endif // DEBUG
ISymbolTransformer transformer = null;
if (_options.Minimize) {
transformer = new SymbolObfuscator();
}
else {
transformer = new SymbolInternalizer();
}
if (transformer != null) {
SymbolSetTransformer symbolSetTransformer = new SymbolSetTransformer(transformer);
ICollection<Symbol> transformedSymbols = symbolSetTransformer.TransformSymbolSet(_symbols, /* useInheritanceOrder */ true);
#if DEBUG
if (_options.InternalTestType == "minimizationMap") {
StringWriter testWriter = new StringWriter();
testWriter.WriteLine("Minimization Map");
testWriter.WriteLine("================================================================");
List<Symbol> sortedTransformedSymbols = new List<Symbol>(transformedSymbols);
sortedTransformedSymbols.Sort(delegate(Symbol s1, Symbol s2) {
return String.Compare(s1.Name, s2.Name);
});
foreach (Symbol transformedSymbol in sortedTransformedSymbols) {
Debug.Assert(transformedSymbol is MemberSymbol);
testWriter.WriteLine(" Member '" + transformedSymbol.Name + "' renamed to '" + transformedSymbol.GeneratedName + "'");
}
testWriter.WriteLine();
testWriter.WriteLine();
_testOutput = testWriter.ToString();
}
#endif // DEBUG
}
}
public bool Compile(CompilerOptions options) {
if (options == null) {
throw new ArgumentNullException("options");
}
_options = options;
_hasErrors = false;
_symbols = new SymbolSet();
ImportMetadata();
if (_hasErrors) {
return false;
}
BuildCodeModel();
if (_hasErrors) {
return false;
}
BuildMetadata();
if (_hasErrors) {
return false;
}
BuildImplementation();
if (_hasErrors) {
return false;
}
GenerateScript();
if (_hasErrors) {
return false;
}
return true;
}
private void GenerateScript() {
Stream outputStream = null;
TextWriter outputWriter = null;
try {
outputStream = _options.ScriptFile.GetStream();
if (outputStream == null) {
((IErrorHandler)this).ReportError("Unable to write to file " + _options.ScriptFile.FullName,
_options.ScriptFile.FullName);
return;
}
outputWriter = new StreamWriter(outputStream);
#if DEBUG
if (_options.InternalTestMode) {
if (_testOutput != null) {
outputWriter.Write(_testOutput);
outputWriter.WriteLine("Script");
outputWriter.WriteLine("================================================================");
outputWriter.WriteLine();
outputWriter.WriteLine();
}
}
#endif // DEBUG
string script = GenerateScriptWithTemplate();
outputWriter.Write(script);
}
catch (Exception e) {
Debug.Fail(e.ToString());
}
finally {
if (outputWriter != null) {
outputWriter.Flush();
}
if (outputStream != null) {
_options.ScriptFile.CloseStream(outputStream);
}
}
}
private string GenerateScriptCore() {
StringWriter scriptWriter = new StringWriter();
try {
ScriptGenerator scriptGenerator = new ScriptGenerator(scriptWriter, _options, _symbols);
scriptGenerator.GenerateScript(_symbols);
}
catch (Exception e) {
Debug.Fail(e.ToString());
}
finally {
scriptWriter.Flush();
}
return scriptWriter.ToString();
}
private string GenerateScriptWithTemplate() {
string script = GenerateScriptCore();
string template = _options.ScriptInfo.Template;
if (String.IsNullOrEmpty(template)) {
return script;
}
template = PreprocessTemplate(template);
StringBuilder requiresBuilder = new StringBuilder();
StringBuilder dependenciesBuilder = new StringBuilder();
StringBuilder depLookupBuilder = new StringBuilder();
bool firstDependency = true;
foreach (ScriptReference dependency in _symbols.Dependencies) {
if (dependency.DelayLoaded) {
continue;
}
if (firstDependency) {
depLookupBuilder.Append("var ");
}
else {
requiresBuilder.Append(", ");
dependenciesBuilder.Append(", ");
depLookupBuilder.Append(",\r\n ");
}
string name = dependency.Name;
if (name == "ss") {
// TODO: This is a hack... to make generated node.js scripts
// be able to reference the 'scriptsharp' node module.
// Fix this in a better/1st class manner by allowing
// script assemblies to declare such things.
name = "scriptsharp";
}
requiresBuilder.Append("'" + dependency.Path + "'");
dependenciesBuilder.Append(dependency.Identifier);
depLookupBuilder.Append(dependency.Identifier);
depLookupBuilder.Append(" = require('" + name + "')");
firstDependency = false;
}
depLookupBuilder.Append(";");
return template.TrimStart()
.Replace("{name}", _symbols.ScriptName)
.Replace("{description}", _options.ScriptInfo.Description ?? String.Empty)
.Replace("{copyright}", _options.ScriptInfo.Copyright ?? String.Empty)
.Replace("{version}", _options.ScriptInfo.Version ?? String.Empty)
.Replace("{compiler}", typeof(ScriptCompiler).Assembly.GetName().Version.ToString())
.Replace("{description}", _options.ScriptInfo.Description)
.Replace("{requires}", requiresBuilder.ToString())
.Replace("{dependencies}", dependenciesBuilder.ToString())
.Replace("{dependenciesLookup}", depLookupBuilder.ToString())
.Replace("{script}", script);
}
private void ImportMetadata() {
MetadataImporter mdImporter = new MetadataImporter(_options, this);
_importedSymbols = mdImporter.ImportMetadata(_options.References, _symbols);
}
private string PreprocessTemplate(string template) {
if (_options.IncludeResolver == null) {
return template;
}
Regex includePattern = new Regex("\\{include:([^\\}]+)\\}", RegexOptions.Multiline | RegexOptions.CultureInvariant);
return includePattern.Replace(template, delegate(Match include) {
string includedScript = String.Empty;
if (include.Groups.Count == 2) {
string includePath = include.Groups[1].Value;
IStreamSource includeSource = _options.IncludeResolver.Resolve(includePath);
if (includeSource != null) {
Stream includeStream = includeSource.GetStream();
StreamReader reader = new StreamReader(includeStream);
includedScript = reader.ReadToEnd();
includeSource.CloseStream(includeStream);
}
}
return includedScript;
});
}
#region Implementation of IErrorHandler
void IErrorHandler.ReportError(string errorMessage, string location) {
_hasErrors = true;
if (_errorHandler != null) {
_errorHandler.ReportError(errorMessage, location);
return;
}
if (String.IsNullOrEmpty(location) == false) {
Console.Error.Write(location);
Console.Error.Write(": ");
}
Console.Error.WriteLine(errorMessage);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TypeUtil.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Configuration.Internal;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Web;
namespace System.Configuration {
internal static class TypeUtil {
//
// Since the config APIs were originally implemented in System.dll,
// references to types without assembly names could be resolved to
// System.dll in Everett. Emulate that behavior by trying to get the
// type from System.dll
//
static private Type GetLegacyType(string typeString) {
Type type = null;
//
// Ignore all exceptions, otherwise callers will get unexpected
// exceptions not related to the original failure to load the
// desired type.
//
try {
Assembly systemAssembly = typeof(ConfigurationException).Assembly;
type = systemAssembly.GetType(typeString, false);
}
catch {
}
return type;
}
//
// Get the type specified by typeString. If it fails, try to retrieve it
// as a type from System.dll. If that fails, return null or throw the original
// exception as indicated by throwOnError.
//
static private Type GetTypeImpl(string typeString, bool throwOnError) {
Type type = null;
Exception originalException = null;
try {
type = Type.GetType(typeString, throwOnError);
}
catch (Exception e) {
originalException = e;
}
if (type == null) {
type = GetLegacyType(typeString);
if (type == null && originalException != null) {
throw originalException;
}
}
return type;
}
//
// Ask the host to get the type specified by typeString. If it fails, try to retrieve it
// as a type from System.dll. If that fails, return null or throw the original
// exception as indicated by throwOnError.
//
static internal Type GetTypeWithReflectionPermission(IInternalConfigHost host, string typeString, bool throwOnError) {
Type type = null;
Exception originalException = null;
try {
type = host.GetConfigType(typeString, throwOnError);
}
catch (Exception e) {
originalException = e;
}
if (type == null) {
type = GetLegacyType(typeString);
if (type == null && originalException != null) {
throw originalException;
}
}
return type;
}
static internal Type GetTypeWithReflectionPermission(string typeString, bool throwOnError) {
return GetTypeImpl(typeString, throwOnError);
}
static internal T CreateInstance<T>(string typeString) {
return CreateInstanceRestricted<T>(null, typeString);
}
static internal T CreateInstanceRestricted<T>(Type callingType, string typeString) {
Type type = GetTypeImpl(typeString, true); // catch the errors and report them
VerifyAssignableType(typeof(T), type, true /* throwOnError */);
return (T)CreateInstanceRestricted(callingType, type);
}
[ReflectionPermission(SecurityAction.Assert, Flags = ReflectionPermissionFlag.MemberAccess)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "This assert is potentially dangerous and shouldn't be present but is necessary for back-compat.")]
static internal object CreateInstanceWithReflectionPermission(Type type) {
object result = Activator.CreateInstance(type, true); // create non-public types
return result;
}
// This is intended to be similar to CreateInstanceWithReflectionPermission, but there is
// an extra check to make sure that the calling type is allowed to access the target type.
static internal object CreateInstanceRestricted(Type callingType, Type targetType) {
if (CallerHasMemberAccessOrAspNetPermission()) {
// If the caller asserts MemberAccess (or this is a full-trust AD),
// access to any type in any assembly is allowed.
return CreateInstanceWithReflectionPermission(targetType);
}
else {
// This DynamicMethod is just a thin wrapper around Activator.CreateInstance, but it is
// crafted to make the call site of CreateInstance look like it belongs to 'callingType'.
// If the calling type cannot be determined, an AHDM will be used so Activator.CreateInstance
// doesn't think System.Configuration.dll is the immediate caller.
DynamicMethod dm = CreateDynamicMethod(callingType, returnType: typeof(object), parameterTypes: new Type[] { typeof(Type) });
// type => Activator.CreateInstance(type, true)
var ilGen = dm.GetILGenerator();
ilGen.Emit(OpCodes.Ldarg_0); // stack = { type }
ilGen.Emit(OpCodes.Ldc_I4_1); // stack = { type, TRUE }
ilGen.Emit(OpCodes.Call, typeof(Activator).GetMethod("CreateInstance", new Type[] { typeof(Type), typeof(bool) })); // stack = { retVal }
PreventTailCall(ilGen); // stack = { retVal }
ilGen.Emit(OpCodes.Ret);
var createInstanceDel = (Func<Type, object>)dm.CreateDelegate(typeof(Func<Type, object>));
return createInstanceDel(targetType);
}
}
// This is intended to be similar to Delegate.CreateDelegate, but there is
// an extra check to make sure that the calling type is allowed to access the target method.
static internal Delegate CreateDelegateRestricted(Type callingType, Type delegateType, MethodInfo targetMethod) {
if (CallerHasMemberAccessOrAspNetPermission()) {
// If the caller asserts MemberAccess (or this is a full-trust AD),
// access to any type in any assembly is allowed. Note: the original
// code path didn't assert before the call to CreateDelegate, so we
// won't, either.
return Delegate.CreateDelegate(delegateType, targetMethod);
}
else {
// This DynamicMethod is just a thin wrapper around Delegate.CreateDelegate, but it is
// crafted to make the call site of CreateInstance look like it belongs to 'callingType'.
// If the calling type cannot be determined, an AHDM will be used so Activator.CreateInstance
// doesn't think System.Configuration.dll is the immediate caller.
DynamicMethod dm = CreateDynamicMethod(callingType, returnType: typeof(Delegate), parameterTypes: new Type[] { typeof(Type), typeof(MethodInfo) });
// (type, method) => Delegate.CreateDelegate(type, method)
var ilGen = dm.GetILGenerator();
ilGen.Emit(OpCodes.Ldarg_0); // stack = { type }
ilGen.Emit(OpCodes.Ldarg_1); // stack = { type, method }
ilGen.Emit(OpCodes.Call, typeof(Delegate).GetMethod("CreateDelegate", new Type[] { typeof(Type), typeof(MethodInfo) })); // stack = { retVal }
PreventTailCall(ilGen); // stack = { retVal }
ilGen.Emit(OpCodes.Ret);
var createDelegateDel = (Func<Type, MethodInfo, Delegate>)dm.CreateDelegate(typeof(Func<Type, MethodInfo, Delegate>));
return createDelegateDel(delegateType, targetMethod);
}
}
private static DynamicMethod CreateDynamicMethod(Type owner, Type returnType, Type[] parameterTypes) {
if (owner != null) {
return CreateDynamicMethodWithUnrestrictedPermission(owner, returnType, parameterTypes);
}
else {
// Don't assert when creating AHDM instances.
return new DynamicMethod("temp-dynamic-method", returnType, parameterTypes);
}
}
// Injecting a DynamicMethod into another module could end up demanding more than the grant set of the destination assembly,
// so we'll need to assert full trust instead of just MemberAccess. This should be safe since simply creating the
// DynamicMethod doesn't result in user code being run, and invocation of the method does not occur under any assert.
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private static DynamicMethod CreateDynamicMethodWithUnrestrictedPermission(Type owner, Type returnType, Type[] parameterTypes) {
Debug.Assert(owner != null);
return new DynamicMethod("temp-dynamic-method", returnType, parameterTypes, owner);
}
// DevDiv #736562: If a dynamic method tail-calls into Activator.CreateInstance or Delegate.CreateDelegate, it could
// modify stack frames in such a way that a stack walk fails when it should have succeeded. A volatile field read
// prevents reordering so ensures that the dynamic method cannot tail-call into these methods.
//
// Stack transitional behavior: unchanged.
private static void PreventTailCall(ILGenerator ilGen) {
ilGen.Emit(OpCodes.Volatile);
ilGen.Emit(OpCodes.Ldsfld, typeof(String).GetField("Empty"));
ilGen.Emit(OpCodes.Pop);
}
static internal ConstructorInfo GetConstructorWithReflectionPermission(Type type, Type baseType, bool throwOnError) {
type = VerifyAssignableType(baseType, type, throwOnError);
if (type == null) {
return null;
}
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
ConstructorInfo ctor = type.GetConstructor(bindingFlags, null, CallingConventions.HasThis, Type.EmptyTypes, null);
if (ctor == null && throwOnError) {
throw new TypeLoadException(SR.GetString(SR.TypeNotPublic, type.AssemblyQualifiedName));
}
return ctor;
}
[ReflectionPermission(SecurityAction.Assert, Flags = ReflectionPermissionFlag.MemberAccess)]
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "A permission check is already performed by BaseConfigurationRecord.FindAndEnsureFactoryRecord before code execution reaches this point.")]
static internal object InvokeCtorWithReflectionPermission(ConstructorInfo ctor) {
return ctor.Invoke(null);
}
static internal bool IsTypeFromTrustedAssemblyWithoutAptca(Type type) {
Assembly assembly = type.Assembly;
return assembly.GlobalAssemblyCache && !HasAptcaBit(assembly);
}
static internal Type VerifyAssignableType(Type baseType, Type type, bool throwOnError) {
if (baseType.IsAssignableFrom(type)) {
return type;
}
if (throwOnError) {
throw new TypeLoadException(
SR.GetString(SR.Config_type_doesnt_inherit_from_type, type.FullName, baseType.FullName));
}
return null;
}
private static bool HasAptcaBit(Assembly assembly) {
Object[] attrs = assembly.GetCustomAttributes(
typeof(System.Security.AllowPartiallyTrustedCallersAttribute), /*inherit*/ false);
return (attrs != null && attrs.Length > 0);
}
static private volatile PermissionSet s_fullTrustPermissionSet;
private static readonly ReflectionPermission s_memberAccessPermission = new ReflectionPermission(ReflectionPermissionFlag.MemberAccess);
private static readonly AspNetHostingPermission s_aspNetHostingPermission = new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal);
// Check if the caller is fully trusted
static internal bool IsCallerFullTrust {
get {
bool isFullTrust = false;
try {
if (s_fullTrustPermissionSet == null) {
s_fullTrustPermissionSet = new PermissionSet(PermissionState.Unrestricted);
}
s_fullTrustPermissionSet.Demand();
isFullTrust = true;
}
catch {
}
return isFullTrust;
}
}
private static bool CallerHasMemberAccessOrAspNetPermission() {
try {
s_memberAccessPermission.Demand();
return true;
}
catch (SecurityException) { }
// ASP.NET partial trust scenarios don't have MemberAccess permission, but we want to allow
// all reflection in these scenarios since ASP.NET partial trust isn't a security boundary.
try {
s_aspNetHostingPermission.Demand();
return true;
}
catch (SecurityException) { }
// Fallback: Missing permission and not hosted in ASP.NET
return false;
}
// Check if the type is allowed to be used in config by checking the APTCA bit
internal static bool IsTypeAllowedInConfig(Type t) {
// Note:
// This code is copied from HttpRuntime.IsTypeAllowedInConfig, but modified in
// how it checks for fulltrust this can be called from non-ASP.NET apps.
// Allow everything in full trust
if (IsCallerFullTrust) {
return true;
}
// The APTCA bit is only relevant for assemblies living in the GAC, since the rest runs
// under partial trust (VSWhidbey 422183)
Assembly assembly = t.Assembly;
if (!assembly.GlobalAssemblyCache)
return true;
// If it has the APTCA bit, allow it
if (HasAptcaBit(assembly))
return true;
// It's a GAC type without APTCA in partial trust scenario: block it
return false;
}
}
}
| |
//
// LiteTestCase.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Util;
using NUnit.Framework;
using Sharpen;
using Couchbase.Lite.Tests;
using System.Threading.Tasks;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection;
using System.IO.Compression;
namespace Couchbase.Lite
{
[TestFixture]
public abstract class LiteTestCase
{
private const string Tag = "LiteTestCase";
public const string FacebookAppId = "78255794086";
ObjectWriter mapper = new ObjectWriter();
protected Manager manager = null;
protected Database database = null;
protected string DefaultTestDb = "cblitetest";
private static DirectoryInfo _rootDir;
public static DirectoryInfo RootDirectory {
get {
if (_rootDir == null) {
var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
_rootDir = new DirectoryInfo(Path.Combine(path, Path.Combine("couchbase", Path.Combine("tests", "files"))));
}
return _rootDir;
}
set {
var path = value.FullName;
_rootDir = new DirectoryInfo(Path.Combine(path, Path.Combine("couchbase", Path.Combine("tests", "files"))));;
}
}
[SetUp]
protected virtual void SetUp()
{
Log.V(Tag, "SetUp");
ManagerOptions.Default.CallbackScheduler = new SingleTaskThreadpoolScheduler();
LoadCustomProperties();
StartCBLite();
StartDatabase();
}
protected Stream GetAsset(string name)
{
var assetPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Assets." + name;
Log.D(Tag, "Fetching assembly resource: " + assetPath);
var stream = GetType().GetResourceAsStream(assetPath);
return stream;
}
protected string GetServerPath()
{
var filesDir = RootDirectory.FullName;
return filesDir;
}
/// <exception cref="System.IO.IOException"></exception>
protected void StartCBLite()
{
string serverPath = GetServerPath();
var path = new DirectoryInfo(serverPath);
if (path.Exists)
path.Delete(true);
path.Create();
var testPath = path.CreateSubdirectory("tests");
manager = new Manager(testPath, Manager.DefaultOptions);
}
protected void StopCBLite()
{
if (manager != null)
{
manager.Close();
}
}
protected Database StartDatabase()
{
if (database != null)
{
database.Close();
database.Delete();
database = null;
}
database = EnsureEmptyDatabase(DefaultTestDb);
return database;
}
protected void StopDatabase()
{
if (database != null)
{
database.Close();
}
}
protected Database EnsureEmptyDatabase(string dbName)
{
var db = manager.GetExistingDatabase(dbName);
if (db != null)
{
var status = false;;
try {
db.Delete();
db.Close();
status = true;
} catch (Exception e) {
Log.E(Tag, "Cannot delete database " + e.Message);
}
Assert.IsTrue(status);
}
db = manager.GetDatabase(dbName);
return db;
}
/// <exception cref="System.IO.IOException"></exception>
protected void LoadCustomProperties()
{
var systemProperties = Runtime.Properties;
InputStream mainProperties = GetAsset("test.properties");
if (mainProperties != null)
{
systemProperties.Load(mainProperties);
}
try
{
var localProperties = GetAsset("local-test.properties");
if (localProperties != null)
{
systemProperties.Load(localProperties);
}
}
catch (IOException)
{
Log.W(Tag, "Error trying to read from local-test.properties, does this file exist?");
}
}
protected string GetReplicationProtocol()
{
return Runtime.GetProperty("replicationProtocol");
}
protected string GetReplicationServer()
{
return Runtime.GetProperty("replicationServer").Trim();
}
protected int GetReplicationPort()
{
return Convert.ToInt32(Runtime.GetProperty("replicationPort"));
}
protected int GetReplicationAdminPort()
{
return Convert.ToInt32(Runtime.GetProperty("replicationAdminPort"));
}
protected string GetReplicationAdminUser()
{
return Runtime.GetProperty("replicationAdminUser");
}
protected string GetReplicationAdminPassword()
{
return Runtime.GetProperty("replicationAdminPassword");
}
protected string GetReplicationDatabase()
{
return Runtime.GetProperty("replicationDatabase");
}
protected Uri GetReplicationURL()
{
String path = null;
try
{
if (GetReplicationAdminUser() != null && GetReplicationAdminUser().Trim().Length > 0)
{
path = string.Format("{0}://{1}:{2}@{3}:{4}/{5}", GetReplicationProtocol(), GetReplicationAdminUser
(), GetReplicationAdminPassword(), GetReplicationServer(), GetReplicationPort(),
GetReplicationDatabase());
return new Uri(path);
}
else
{
path = string.Format("{0}://{1}:{2}/{3}", GetReplicationProtocol(), GetReplicationServer
(), GetReplicationPort(), GetReplicationDatabase());
return new Uri(path);
}
}
catch (UriFormatException e)
{
throw new ArgumentException(String.Format("Invalid replication URL: {0}", path), e);
}
}
protected bool IsTestingAgainstSyncGateway()
{
return GetReplicationPort() == 4984;
}
protected void AssertDictionariesAreEqual(IDictionary<string, object> first, IDictionary<string, object> second)
{
//I'm tired of NUnit misunderstanding that objects are dictionaries and trying to compare them as collections...
Assert.IsTrue(first.Keys.Count == second.Keys.Count);
foreach (var key in first.Keys) {
var firstObj = first[key];
var secondObj = second[key];
var firstDic = firstObj.AsDictionary<string, object>();
var secondDic = secondObj.AsDictionary<string, object>();
if (firstDic != null && secondDic != null) {
AssertDictionariesAreEqual(firstDic, secondDic);
} else {
Assert.AreEqual(firstObj, secondObj);
}
}
}
/// <exception cref="System.UriFormatException"></exception>
protected Uri GetReplicationURLWithoutCredentials()
{
return new Uri(string.Format("{0}://{1}:{2}/{3}", GetReplicationProtocol(), GetReplicationServer(), GetReplicationPort(), GetReplicationDatabase()));
}
protected Uri GetReplicationAdminURL()
{
return new Uri(string.Format("{0}://{1}:{2}/{3}", GetReplicationProtocol(), GetReplicationServer(), GetReplicationAdminPort(), GetReplicationDatabase()));
}
[TearDown]
protected virtual void TearDown()
{
Log.V(Tag, "tearDown");
StopDatabase();
StopCBLite();
Manager.DefaultOptions.RestoreDefaults();
}
protected virtual void RunReplication(Replication replication)
{
var replicationDoneSignal = new CountdownEvent(1);
var observer = new ReplicationObserver(replicationDoneSignal);
replication.Changed += observer.Changed;
replication.Start();
var success = replicationDoneSignal.Wait(TimeSpan.FromSeconds(60));
Assert.IsTrue(success);
replication.Changed -= observer.Changed;
}
protected IDictionary<string, object> UserProperties(IDictionary
<string, object> properties)
{
var result = new Dictionary<string, object>();
foreach (string key in properties.Keys)
{
if (!key.StartsWith ("_", StringComparison.Ordinal))
{
result.Put(key, properties[key]);
}
}
return result;
}
protected IDictionary<string, object> CreateAttachmentsStub(string name)
{
return new Dictionary<string, object> {
{ name, new Dictionary<string, object> {
{ "stub", true }
}
}
};
}
protected IDictionary<string, object> CreateAttachmentsDict(IEnumerable<byte> data, string name, string type, bool gzipped)
{
if (gzipped) {
using (var ms = new MemoryStream())
using (var gs = new GZipStream(ms, CompressionMode.Compress)) {
gs.Write(data.ToArray(), 0, data.Count());
data = ms.ToArray();
}
}
var att = new NonNullDictionary<string, object> {
{ "content_type", type },
{ "data", data },
{ "encoding", gzipped ? "gzip" : null }
};
return new Dictionary<string, object> {
{ name, att }
};
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetReplicationAuthParsedJson()
{
var authJson = "{\n" + " \"facebook\" : {\n" + " \"email\" : \"[email protected]\"\n"
+ " }\n" + " }\n";
mapper = new ObjectWriter();
var authProperties = mapper.ReadValue<Dictionary<string, object>>(authJson);
return authProperties;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetPushReplicationParsedJson()
{
IDictionary<string, object> authProperties = GetReplicationAuthParsedJson();
IDictionary<string, object> targetProperties = new Dictionary<string, object>();
targetProperties.Put("url", GetReplicationURL().ToString());
targetProperties["auth"] = authProperties;
IDictionary<string, object> properties = new Dictionary<string, object>();
properties["source"] = DefaultTestDb;
properties["target"] = targetProperties;
return properties;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual IDictionary<string, object> GetPullReplicationParsedJson()
{
IDictionary<string, object> authProperties = GetReplicationAuthParsedJson();
IDictionary<string, object> sourceProperties = new Dictionary<string, object>();
sourceProperties.Put("url", GetReplicationURL().ToString());
sourceProperties["auth"] = authProperties;
IDictionary<string, object> properties = new Dictionary<string, object>();
properties["source"] = sourceProperties;
properties["target"] = DefaultTestDb;
return properties;
}
internal static void CreateDocuments(Database db, int n)
{
for (int i = 0; i < n; i++) {
var properties = new Dictionary<string, object>();
properties.Add("testName", "testDatabase");
properties.Add("sequence", i);
CreateDocumentWithProperties(db, properties);
}
}
internal static Task CreateDocumentsAsync(Database database, int n)
{
return database.RunAsync(db =>
{
database.RunInTransaction(() =>
{
LiteTestCase.CreateDocuments(db, n);
return true;
});
});
}
internal static Document CreateDocumentWithProperties(Database db, IDictionary<string, object> properties)
{
var doc = db.CreateDocument();
Assert.IsNotNull(doc);
Assert.IsNull(doc.CurrentRevisionId);
Assert.IsNull(doc.CurrentRevision);
Assert.IsNotNull(doc.Id, "Document has no ID");
try
{
doc.PutProperties(properties);
}
catch (Exception e)
{
Log.E(Tag, "Error creating document", e);
Assert.IsTrue(false, "can't create new document in db:" + db.Name + " with properties:" + properties.ToString());
}
Assert.IsNotNull(doc.Id);
Assert.IsNotNull(doc.CurrentRevisionId);
Assert.IsNotNull(doc.CurrentRevision);
// should be same doc instance, since there should only ever be a single Document instance for a given document
Assert.AreEqual(db.GetDocument(doc.Id), doc);
Assert.AreEqual(db.GetDocument(doc.Id).Id, doc.Id);
return doc;
}
internal static Document CreateDocWithAttachment(Database database, string attachmentName, string content)
{
var properties = new Dictionary<string, object>();
properties.Put("foo", "bar");
var doc = CreateDocumentWithProperties(database, properties);
var rev = doc.CurrentRevision;
var attachment = rev.GetAttachment(attachmentName);
Assert.AreEqual(rev.Attachments.Count(), 0);
Assert.AreEqual(rev.AttachmentNames.Count(), 0);
Assert.IsNull(attachment);
var body = new MemoryStream(Encoding.UTF8.GetBytes(content));
var rev2 = doc.CreateRevision();
rev2.SetAttachment(attachmentName, "text/plain; charset=utf-8", body);
var rev3 = rev2.Save();
rev2.Dispose();
Assert.IsNotNull(rev3);
Assert.AreEqual(rev3.Attachments.Count(), 1);
Assert.AreEqual(rev3.AttachmentNames.Count(), 1);
attachment = rev3.GetAttachment(attachmentName);
Assert.IsNotNull(attachment);
Assert.AreEqual(doc, attachment.Document);
Assert.AreEqual(attachmentName, attachment.Name);
var attNames = new List<string>();
attNames.AddItem(attachmentName);
Assert.AreEqual(rev3.AttachmentNames, attNames);
Assert.AreEqual("text/plain; charset=utf-8", attachment.ContentType);
Assert.AreEqual(Encoding.UTF8.GetString(attachment.Content.ToArray()), content);
Assert.AreEqual(Encoding.UTF8.GetBytes(content).Length, attachment.Length);
attachment.Dispose();
return doc;
}
public void StopReplication(Replication replication)
{
if (replication.Status == ReplicationStatus.Stopped) {
return;
}
var replicationDoneSignal = new CountdownEvent(1);
var replicationStoppedObserver = new ReplicationObserver(replicationDoneSignal);
replication.Changed += replicationStoppedObserver.Changed;
replication.Stop();
var success = replicationDoneSignal.Wait(TimeSpan.FromSeconds(10));
Assert.IsTrue(success);
// give a little padding to give it a chance to save a checkpoint
Thread.Sleep(2 * 1000);
}
protected void AssertEnumerablesAreEqual(
IEnumerable list1,
IEnumerable list2)
{
var enumerator1 = list1.GetEnumerator();
var enumerator2 = list2.GetEnumerator();
while (enumerator1.MoveNext() && enumerator2.MoveNext())
{
var obj1 = enumerator1.Current;
var obj2 = enumerator1.Current;
if (obj1 is IDictionary<string, object> && obj2 is IDictionary<string, object>)
{
AssertPropertiesAreEqual((IDictionary<string, object>)obj1, (IDictionary<string, object>)obj2);
}
else if (obj1 is IEnumerable && obj2 is IEnumerable)
{
AssertEnumerablesAreEqual((IEnumerable)obj1, (IEnumerable)obj2);
}
else
{
Assert.AreEqual(obj1, obj2);
}
}
}
protected void AssertPropertiesAreEqual(
IDictionary<string, object> prop1,
IDictionary<string, object> prop2)
{
Assert.AreEqual(prop1.Count, prop2.Count);
foreach(var key in prop1.Keys)
{
Assert.IsTrue(prop1.ContainsKey(key));
object obj1 = prop1[key];
object obj2 = prop2[key];
if (obj1 is IDictionary && obj2 is IDictionary)
{
AssertPropertiesAreEqual((IDictionary<string, object>)obj1, (IDictionary<string, object>)obj2);
}
else if (obj1 is IEnumerable && obj2 is IEnumerable)
{
AssertEnumerablesAreEqual((IEnumerable)obj1, (IEnumerable)obj2);
}
else
{
Assert.AreEqual(obj1, obj2);
}
}
}
/// <exception cref="System.Exception"></exception>
public static SavedRevision CreateRevisionWithRandomProps(SavedRevision createRevFrom, bool allowConflict)
{
var properties = new Dictionary<string, object>();
properties.Put(Misc.CreateGUID(), "val");
var unsavedRevision = createRevFrom.CreateRevision();
unsavedRevision.SetUserProperties(properties);
return unsavedRevision.Save(allowConflict);
}
}
internal class ReplicationStoppedObserver
{
private readonly CountDownLatch doneSignal;
public ReplicationStoppedObserver(CountDownLatch doneSignal)
{
this.doneSignal = doneSignal;
}
public void Changed(ReplicationChangeEventArgs args)
{
var replicator = args.Source;
if (replicator.Status == ReplicationStatus.Stopped)
{
doneSignal.CountDown();
}
}
}
internal class ReplicationErrorObserver
{
private readonly CountDownLatch doneSignal;
public ReplicationErrorObserver(CountDownLatch doneSignal)
{
this.doneSignal = doneSignal;
}
public void Changed(ReplicationChangeEventArgs args)
{
var replicator = args.Source;
if (replicator.LastError != null)
{
doneSignal.CountDown();
}
}
}
}
| |
// 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.Linq;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
public class SslStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
[Fact]
public void SslStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var server = new SslStream(serverStream))
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));
auth[1] = server.AuthenticateAsServerAsync(certificate);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
}
}
[Fact]
public void SslStream_StreamToStream_Authentication_IncorrectServerName_Fail()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new SslStream(clientStream))
using (var server = new SslStream(serverStream))
using (var certificate = Configuration.Certificates.GetServerCertificate())
{
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync("incorrectServer");
auth[1] = server.AuthenticateAsServerAsync(certificate);
Assert.Throws<AuthenticationException>(() =>
{
auth[0].GetAwaiter().GetResult();
});
auth[1].GetAwaiter().GetResult();
}
}
[Fact]
public void SslStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
clientSslStream.Write(_sampleMsg);
serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
clientSslStream.Write(_sampleMsg);
serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SslStream_StreamToStream_LargeWrites_Sync_Success(bool randomizedData)
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer:false))
using (var serverStream = new VirtualNetworkStream(network, isServer:true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
Assert.True(DoHandshake(clientSslStream, serverSslStream), "Handshake complete");
byte[] largeMsg = new byte[4096 * 5]; // length longer than max read chunk size (16K + headers)
if (randomizedData)
{
new Random().NextBytes(largeMsg); // not very compressible
}
else
{
for (int i = 0; i < largeMsg.Length; i++)
{
largeMsg[i] = (byte)i; // very compressible
}
}
byte[] receivedLargeMsg = new byte[largeMsg.Length];
// First do a large write and read blocks at a time
clientSslStream.Write(largeMsg);
int bytesRead = 0, totalRead = 0;
while (totalRead < largeMsg.Length &&
(bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
{
totalRead += bytesRead;
}
Assert.Equal(receivedLargeMsg.Length, totalRead);
Assert.Equal(largeMsg, receivedLargeMsg);
// Then write again and read bytes at a time
clientSslStream.Write(largeMsg);
foreach (byte b in largeMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
[Fact]
public void SslStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
Task[] tasks = new Task[2];
tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length);
tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
bool finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
tasks[0] = serverSslStream.ReadAsync(recvBuf, 0, _sampleMsg.Length);
tasks[1] = clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
finished = Task.WaitAll(tasks, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
[Fact]
public void SslStream_StreamToStream_Write_ReadByte_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer:false))
using (var serverStream = new VirtualNetworkStream(network, isServer:true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
for (int i = 0; i < 3; i++)
{
clientSslStream.Write(_sampleMsg);
foreach (byte b in _sampleMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
}
private bool VerifyOutput(byte[] actualBuffer, byte[] expectedBuffer)
{
return expectedBuffer.SequenceEqual(actualBuffer);
}
private bool AllowAnyServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None;
if (!Capability.IsTrustedRootCertificateInstalled())
{
expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors;
}
Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors);
if (sslPolicyErrors == expectedSslPolicyErrors)
{
return true;
}
else
{
return false;
}
}
private bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
{
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Task[] auth = new Task[2];
auth[0] = clientSslStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));
auth[1] = serverSslStream.AuthenticateAsServerAsync(certificate);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
return finished;
}
}
}
}
| |
using System;
using NUnit.Framework;
using System.IO;
namespace System.Data.SQLite.Tests
{
[TestFixture]
public class SelectDataTypesFixture
{
[Test]
public void SelectGuidTest()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one uniqueidentifier, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('111d60b1-583f-4278-b91d-8bb65d889730',10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('ec334526-8aa9-4441-abf5-e584de00f089',20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('cfc6e3d2-d3e9-4e0b-8098-2861220abcaa',310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(Guid), reader["one"].GetType());
}
}
}
[Test]
public void SelectDateTimeTest()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one datetime, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('2013-01-04',10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('2013-01-04 14:02:33.34',20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('2013-01-04 14:02:33.34 -0600',310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(DateTime), reader["one"].GetType());
Assert.AreNotEqual(default(DateTime), reader["one"]);
}
}
}
[Test]
public void SelectLongTest()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one bigint, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(1,10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(-1,20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(533312314200 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(long), reader["one"].GetType());
Assert.AreNotEqual(default(long), reader["one"]);
}
}
}
[Test]
public void SelectIntegerTest()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one int, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(1,10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(-1,20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(int), reader["one"].GetType());
Assert.AreNotEqual(default(int), reader["one"]);
}
}
}
[Test]
public void SelectFloatingPoint1Test()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one double, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(1,10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(-1.0,20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231.0 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(double), reader["one"].GetType());
Assert.AreNotEqual(default(double), reader["one"]);
}
}
}
[Test]
public void SelectFloatingPoint2Test()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one float, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(1,10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(-1.0,20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231.0 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(double), reader["one"].GetType());
Assert.AreNotEqual(default(double), reader["one"]);
}
}
}
[Test]
public void SelectFloatingPoint3Test()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one decimal(9,5), two smallint);";
cmd.ExecuteNonQuery();
//cmd.CommandText = @"insert into tbl1 values(1,10);";
//cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(-1.1,20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231.1 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(double), reader["one"].GetType());
Assert.AreNotEqual(default(double), reader["one"]);
}
}
}
[Test]
public void SelectString1Test()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one text, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('test',10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('-1.0',20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231.0 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(string), reader["one"].GetType());
Assert.AreNotEqual(default(string), reader["one"]);
}
}
}
[Test]
public void SelectString2Test()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one char, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('test',10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('-1.0',20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231.0 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(string), reader["one"].GetType());
Assert.AreNotEqual(default(string), reader["one"]);
}
}
}
[Test]
public void SelectString3Test()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one varchar(255), two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('test',10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('-1.0',20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231.0 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(string), reader["one"].GetType());
Assert.AreNotEqual(default(string), reader["one"]);
}
}
}
[Test]
public void SelectString4Test()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one text, two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('test',10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('-1.0',20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231.0 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(string), reader["one"].GetType());
Assert.AreNotEqual(default(string), reader["one"]);
}
}
}
[Test]
public void SelectString5Test()
{
using(var con = new SQLiteConnection("Data Source=:memory:"))
using(var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = @"create table tbl1(one nchar(255), two smallint);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('test',10);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values('-1.0',20);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"insert into tbl1 values(53331231.0 ,310);";
cmd.ExecuteNonQuery();
cmd.CommandText = @"select * from tbl1";
var reader = cmd.ExecuteReader();
while(reader.Read())
{
Assert.AreEqual(typeof(string), reader["one"].GetType());
Assert.AreNotEqual(default(string), reader["one"]);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace WebFormsSample
{
public class Auth0Client
{
private readonly string _clientId;
private readonly string _clientSecret;
private readonly RestClient _restClient;
public Auth0Client(string domain, string clientId, string clientSecret)
{
this._clientId = clientId;
this._clientSecret = clientSecret;
_restClient = new RestClient("https://" + domain);
}
public TokenResult ExchangeAuthorizationCodePerAccessToken(string code, string redirectUri)
{
RestRequest restRequest = new RestRequest("/oauth/token", Method.POST);
restRequest.AddHeader("accept", "application/json");
restRequest.AddParameter("client_id", (object)_clientId, ParameterType.GetOrPost);
restRequest.AddParameter("client_secret", (object)_clientSecret, ParameterType.GetOrPost);
restRequest.AddParameter("code", (object)code, ParameterType.GetOrPost);
restRequest.AddParameter("grant_type", (object)"authorization_code", ParameterType.GetOrPost);
restRequest.AddParameter("redirect_uri", (object)redirectUri, ParameterType.GetOrPost);
Dictionary<string, string> data = _restClient.Execute<Dictionary<string, string>>((IRestRequest)restRequest).Data;
if (data.ContainsKey("error") || data.ContainsKey("error_description"))
throw new OAuthException(data["error_description"], data["error"]);
return new TokenResult()
{
AccessToken = data["access_token"],
IdToken = data.ContainsKey("id_token") ? data["id_token"] : string.Empty
};
}
public UserProfile GetUserInfo(TokenResult tokenResult)
{
if (tokenResult == null)
throw new ArgumentNullException("tokenResult");
UserProfile userProfileFromJson = this.GetUserProfileFromJson(!string.IsNullOrEmpty(tokenResult.IdToken) ? this.GetJsonProfileFromIdToken(tokenResult.IdToken) : this.GetJsonProfileFromAccessToken(tokenResult.AccessToken));
if (!string.IsNullOrEmpty(userProfileFromJson.UserId))
return userProfileFromJson;
return this.GetUserInfo(new TokenResult()
{
AccessToken = tokenResult.AccessToken
});
}
private UserProfile GetUserProfileFromJson(string jsonProfile)
{
string[] ignoredProperties = new string[5]
{
"iss",
"sub",
"aud",
"exp",
"iat"
};
string[] mappedProperties = new string[10]
{
"email",
"family_name",
"gender",
"given_name",
"locale",
"name",
"nickname",
"picture",
"user_id",
"identities"
};
UserProfile userProfile = JsonConvert.DeserializeObject<UserProfile>(jsonProfile);
Dictionary<string, object> responseData = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonProfile);
userProfile.ExtraProperties = responseData != null ? responseData.Keys.Where<string>((Func<string, bool>)(x => !((IEnumerable<string>)mappedProperties).Contains<string>(x) && !((IEnumerable<string>)ignoredProperties).Contains<string>(x))).ToDictionary<string, string, object>((Func<string, string>)(x => x), (Func<string, object>)(x => responseData[x])) : new Dictionary<string, object>();
for (int index = 0; index < userProfile.ExtraProperties.Count; ++index)
{
KeyValuePair<string, object> keyValuePair = userProfile.ExtraProperties.ElementAt<KeyValuePair<string, object>>(index);
if (keyValuePair.Value is JArray)
{
string[] array = ((IEnumerable<JToken>)keyValuePair.Value).Select<JToken, string>((Func<JToken, string>)(v => v.ToString())).ToArray<string>();
userProfile.ExtraProperties.Remove(keyValuePair.Key);
userProfile.ExtraProperties.Add(keyValuePair.Key, (object)array);
}
}
return userProfile;
}
private string GetJsonProfileFromIdToken(string idToken)
{
return Encoding.UTF8.GetString(Base64UrlDecode(idToken.Split('.')[1]));
}
private string GetJsonProfileFromAccessToken(string accessToken)
{
RestRequest restRequest = new RestRequest("/userinfo?access_token={accessToken}");
restRequest.AddHeader("accept", "application/json");
restRequest.AddParameter("accessToken", (object)accessToken, ParameterType.UrlSegment);
IRestResponse restResponse = _restClient.Execute((IRestRequest)restRequest);
if (restResponse.StatusCode == HttpStatusCode.Unauthorized)
throw new InvalidOperationException(GetErrorDetails(restResponse.Content));
return restResponse.Content;
}
private byte[] Base64UrlDecode(string input)
{
string s = input.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 0:
return Convert.FromBase64String(s);
case 2:
s += "==";
goto case 0;
case 3:
s += "=";
goto case 0;
default:
throw new InvalidOperationException("Illegal base64url string!");
}
}
private string GetErrorDetails(string resultContent)
{
try
{
return JsonConvert.DeserializeObject(resultContent).ToString();
}
catch (JsonReaderException ex)
{
}
return resultContent;
}
public class TokenResult
{
public string AccessToken { get; set; }
public string IdToken { get; set; }
}
public class OAuthException : Exception
{
public string Code { get; private set; }
public string Description
{
get
{
return this.Message;
}
}
public OAuthException(string description, string code)
: base(description)
{
this.Code = code;
}
}
[DataContract]
public class UserProfile
{
[DataMember(Name = "email")]
public string Email { get; set; }
[DataMember(Name = "family_name")]
public string FamilyName { get; set; }
[DataMember(Name = "gender")]
public string Gender { get; set; }
[DataMember(Name = "given_name")]
public string GivenName { get; set; }
[DataMember(Name = "locale")]
public string Locale { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "nickname")]
public string Nickname { get; set; }
[DataMember(Name = "picture")]
public string Picture { get; set; }
[DataMember(Name = "user_id")]
public string UserId { get; set; }
[DataMember(Name = "identities")]
public IEnumerable<UserProfile.Identity> Identities { get; set; }
public Dictionary<string, object> ExtraProperties { get; set; }
[DataContract]
public class Identity
{
[DataMember(Name = "access_token")]
public string AccessToken { get; set; }
[DataMember(Name = "provider")]
public string Provider { get; set; }
[DataMember(Name = "user_id")]
public string UserId { get; set; }
[DataMember(Name = "connection")]
public string Connection { get; set; }
[DataMember(Name = "isSocial")]
public bool IsSocial { get; set; }
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization; // For SR
using System.Security;
using System.Text;
using System.Globalization;
namespace System.Xml
{
public interface IXmlTextReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose);
void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose);
}
internal class XmlUTF8TextReader : XmlBaseReader, IXmlLineInfo, IXmlTextReaderInitializer
{
private const int MaxTextChunk = 2048;
private readonly PrefixHandle _prefix;
private readonly StringHandle _localName;
private int[] _rowOffsets;
private OnXmlDictionaryReaderClose _onClose;
private bool _buffered;
private int _maxBytesPerRead;
private static readonly byte[] s_charType = new byte[256]
{
/* 0 (.) */
CharType.None,
/* 1 (.) */
CharType.None,
/* 2 (.) */
CharType.None,
/* 3 (.) */
CharType.None,
/* 4 (.) */
CharType.None,
/* 5 (.) */
CharType.None,
/* 6 (.) */
CharType.None,
/* 7 (.) */
CharType.None,
/* 8 (.) */
CharType.None,
/* 9 (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.SpecialWhitespace,
/* A (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.SpecialWhitespace,
/* B (.) */
CharType.None,
/* C (.) */
CharType.None,
/* D (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace,
/* E (.) */
CharType.None,
/* F (.) */
CharType.None,
/* 10 (.) */
CharType.None,
/* 11 (.) */
CharType.None,
/* 12 (.) */
CharType.None,
/* 13 (.) */
CharType.None,
/* 14 (.) */
CharType.None,
/* 15 (.) */
CharType.None,
/* 16 (.) */
CharType.None,
/* 17 (.) */
CharType.None,
/* 18 (.) */
CharType.None,
/* 19 (.) */
CharType.None,
/* 1A (.) */
CharType.None,
/* 1B (.) */
CharType.None,
/* 1C (.) */
CharType.None,
/* 1D (.) */
CharType.None,
/* 1E (.) */
CharType.None,
/* 1F (.) */
CharType.None,
/* 20 ( ) */
CharType.None|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.AttributeText|CharType.SpecialWhitespace,
/* 21 (!) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 22 (") */
CharType.None|CharType.Comment|CharType.Text,
/* 23 (#) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 24 ($) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 25 (%) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 26 (&) */
CharType.None|CharType.Comment,
/* 27 (') */
CharType.None|CharType.Comment|CharType.Text,
/* 28 (() */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 29 ()) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2A (*) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2B (+) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2C (,) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2D (-) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 2E (.) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 2F (/) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 30 (0) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 31 (1) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 32 (2) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 33 (3) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 34 (4) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 35 (5) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 36 (6) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 37 (7) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 38 (8) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 39 (9) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 3A (:) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3B (;) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3C (<) */
CharType.None|CharType.Comment,
/* 3D (=) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3E (>) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3F (?) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 40 (@) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 41 (A) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 42 (B) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 43 (C) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 44 (D) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 45 (E) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 46 (F) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 47 (G) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 48 (H) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 49 (I) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4A (J) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4B (K) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4C (L) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4D (M) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4E (N) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4F (O) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 50 (P) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 51 (Q) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 52 (R) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 53 (S) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 54 (T) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 55 (U) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 56 (V) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 57 (W) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 58 (X) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 59 (Y) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 5A (Z) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 5B ([) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5C (\) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5D (]) */
CharType.None|CharType.Comment|CharType.AttributeText,
/* 5E (^) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5F (_) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 60 (`) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 61 (a) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 62 (b) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 63 (c) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 64 (d) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 65 (e) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 66 (f) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 67 (g) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 68 (h) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 69 (i) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6A (j) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6B (k) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6C (l) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6D (m) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6E (n) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6F (o) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 70 (p) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 71 (q) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 72 (r) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 73 (s) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 74 (t) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 75 (u) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 76 (v) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 77 (w) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 78 (x) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 79 (y) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 7A (z) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 7B ({) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7C (|) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7D (}) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7E (~) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7F (.) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 80 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 81 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 82 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 83 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 84 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 85 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 86 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 87 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 88 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 89 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8A (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8B (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8C (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8D (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8E (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8F (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 90 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 91 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 92 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 93 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 94 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 95 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 96 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 97 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 98 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 99 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9A (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9B (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9C (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9D (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9E (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9F (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A0 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AD (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* ED (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EF (?) */
CharType.None|CharType.FirstName|CharType.Name,
/* F0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
};
public XmlUTF8TextReader()
{
_prefix = new PrefixHandle(BufferReader);
_localName = new StringHandle(BufferReader);
}
public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
MoveToInitial(quotas, onClose);
ArraySegment<byte> seg = EncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding);
BufferReader.SetBuffer(seg.Array, seg.Offset, seg.Count, null, null);
_buffered = true;
}
public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream));
MoveToInitial(quotas, onClose);
stream = new EncodingStreamWrapper(stream, encoding);
BufferReader.SetBuffer(stream, null, null);
_buffered = false;
}
private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
MoveToInitial(quotas);
_maxBytesPerRead = quotas.MaxBytesPerRead;
_onClose = onClose;
}
public override void Close()
{
_rowOffsets = null;
base.Close();
OnXmlDictionaryReaderClose onClose = _onClose;
_onClose = null;
if (onClose != null)
{
try
{
onClose(this);
}
catch (Exception e)
{
if (DiagnosticUtility.IsFatal(e)) throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
}
private void SkipWhitespace()
{
while (!BufferReader.EndOfFile && (s_charType[BufferReader.GetByte()] & CharType.Whitespace) != 0)
BufferReader.SkipByte();
}
private void ReadDeclaration()
{
if (!_buffered)
BufferElement();
int offset;
byte[] buffer = BufferReader.GetBuffer(5, out offset);
if (buffer[offset + 0] != (byte)'?' ||
buffer[offset + 1] != (byte)'x' ||
buffer[offset + 2] != (byte)'m' ||
buffer[offset + 3] != (byte)'l' ||
(s_charType[buffer[offset + 4]] & CharType.Whitespace) == 0)
{
XmlExceptionHelper.ThrowProcessingInstructionNotSupported(this);
}
// If anything came before the "<?xml ?>" it's an error.
if (this.Node.ReadState != ReadState.Initial)
{
XmlExceptionHelper.ThrowDeclarationNotFirst(this);
}
BufferReader.Advance(5);
int localNameOffset = offset + 1;
int localNameLength = 3;
int valueOffset = BufferReader.Offset;
SkipWhitespace();
ReadAttributes();
int valueLength = BufferReader.Offset - valueOffset;
// Backoff the spaces
while (valueLength > 0)
{
byte ch = BufferReader.GetByte(valueOffset + valueLength - 1);
if ((s_charType[ch] & CharType.Whitespace) == 0)
break;
valueLength--;
}
buffer = BufferReader.GetBuffer(2, out offset);
if (buffer[offset + 0] != (byte)'?' ||
buffer[offset + 1] != (byte)'>')
{
XmlExceptionHelper.ThrowTokenExpected(this, "?>", Encoding.UTF8.GetString(buffer, offset, 2));
}
BufferReader.Advance(2);
XmlDeclarationNode declarationNode = MoveToDeclaration();
declarationNode.LocalName.SetValue(localNameOffset, localNameLength);
declarationNode.Value.SetValue(ValueHandleType.UTF8, valueOffset, valueLength);
}
private void VerifyNCName(string s)
{
try
{
XmlConvert.VerifyNCName(s);
}
catch (XmlException exception)
{
XmlExceptionHelper.ThrowXmlException(this, exception);
}
}
private void ReadQualifiedName(PrefixHandle prefix, StringHandle localName)
{
int offset;
int offsetMax;
byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax);
int ch = 0;
int anyChar = 0;
int prefixChar = 0;
int prefixOffset = offset;
if (offset < offsetMax)
{
ch = buffer[offset];
prefixChar = ch;
if ((s_charType[ch] & CharType.FirstName) == 0)
anyChar |= 0x80;
anyChar |= ch;
offset++;
while (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.Name) == 0)
break;
anyChar |= ch;
offset++;
}
}
else
{
anyChar |= 0x80;
ch = 0;
}
if (ch == ':')
{
int prefixLength = offset - prefixOffset;
if (prefixLength == 1 && prefixChar >= 'a' && prefixChar <= 'z')
prefix.SetValue(PrefixHandle.GetAlphaPrefix(prefixChar - 'a'));
else
prefix.SetValue(prefixOffset, prefixLength);
offset++;
int localNameOffset = offset;
if (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.FirstName) == 0)
anyChar |= 0x80;
anyChar |= ch;
offset++;
while (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.Name) == 0)
break;
anyChar |= ch;
offset++;
}
}
else
{
anyChar |= 0x80;
ch = 0;
}
localName.SetValue(localNameOffset, offset - localNameOffset);
if (anyChar >= 0x80)
{
VerifyNCName(prefix.GetString());
VerifyNCName(localName.GetString());
}
}
else
{
prefix.SetValue(PrefixHandleType.Empty);
localName.SetValue(prefixOffset, offset - prefixOffset);
if (anyChar >= 0x80)
{
VerifyNCName(localName.GetString());
}
}
BufferReader.Advance(offset - prefixOffset);
}
private int ReadAttributeText(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.AttributeText) != 0)
offset++;
return offset - textOffset;
}
private void ReadAttributes()
{
int startOffset = 0;
if (_buffered)
startOffset = BufferReader.Offset;
while (true)
{
byte ch;
ReadQualifiedName(_prefix, _localName);
if (BufferReader.GetByte() != '=')
{
SkipWhitespace();
if (BufferReader.GetByte() != '=')
XmlExceptionHelper.ThrowTokenExpected(this, "=", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
byte quoteChar = BufferReader.GetByte();
if (quoteChar != '"' && quoteChar != '\'')
{
SkipWhitespace();
quoteChar = BufferReader.GetByte();
if (quoteChar != '"' && quoteChar != '\'')
XmlExceptionHelper.ThrowTokenExpected(this, "\"", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
bool escaped = false;
int valueOffset = BufferReader.Offset;
while (true)
{
int offset, offsetMax;
byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax);
int length = ReadAttributeText(buffer, offset, offsetMax);
BufferReader.Advance(length);
ch = BufferReader.GetByte();
if (ch == quoteChar)
break;
if (ch == '&')
{
ReadCharRef();
escaped = true;
}
else if (ch == '\'' || ch == '"')
{
BufferReader.SkipByte();
}
else if (ch == '\n' || ch == '\r' || ch == '\t')
{
BufferReader.SkipByte();
escaped = true;
}
else if (ch == 0xEF)
{
ReadNonFFFE();
}
else
{
XmlExceptionHelper.ThrowTokenExpected(this, ((char)quoteChar).ToString(), (char)ch);
}
}
int valueLength = BufferReader.Offset - valueOffset;
XmlAttributeNode attributeNode;
if (_prefix.IsXmlns)
{
Namespace ns = AddNamespace();
_localName.ToPrefixHandle(ns.Prefix);
ns.Uri.SetValue(valueOffset, valueLength, escaped);
attributeNode = AddXmlnsAttribute(ns);
}
else if (_prefix.IsEmpty && _localName.IsXmlns)
{
Namespace ns = AddNamespace();
ns.Prefix.SetValue(PrefixHandleType.Empty);
ns.Uri.SetValue(valueOffset, valueLength, escaped);
attributeNode = AddXmlnsAttribute(ns);
}
else if (_prefix.IsXml)
{
attributeNode = AddXmlAttribute();
attributeNode.Prefix.SetValue(_prefix);
attributeNode.LocalName.SetValue(_localName);
attributeNode.Value.SetValue((escaped ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8), valueOffset, valueLength);
FixXmlAttribute(attributeNode);
}
else
{
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(_prefix);
attributeNode.LocalName.SetValue(_localName);
attributeNode.Value.SetValue((escaped ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8), valueOffset, valueLength);
}
attributeNode.QuoteChar = (char)quoteChar;
BufferReader.SkipByte();
ch = BufferReader.GetByte();
bool space = false;
while ((s_charType[ch] & CharType.Whitespace) != 0)
{
space = true;
BufferReader.SkipByte();
ch = BufferReader.GetByte();
}
if (ch == '>' || ch == '/' || ch == '?')
break;
if (!space)
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlSpaceBetweenAttributes));
}
if (_buffered && (BufferReader.Offset - startOffset) > _maxBytesPerRead)
XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(this, _maxBytesPerRead);
ProcessAttributes();
}
// NOTE: Call only if 0xEF has been seen in the stream AND there are three valid bytes to check (buffer[offset], buffer[offset + 1], buffer[offset + 2]).
// 0xFFFE and 0xFFFF are not valid characters per Unicode specification. The first byte in the UTF8 representation is 0xEF.
private bool IsNextCharacterNonFFFE(byte[] buffer, int offset)
{
Fx.Assert(buffer[offset] == 0xEF, "buffer[offset] MUST be 0xEF.");
if (buffer[offset + 1] == 0xBF && (buffer[offset + 2] == 0xBE || buffer[offset + 2] == 0xBF))
{
// 0xFFFE : 0xEF 0xBF 0xBE
// 0xFFFF : 0xEF 0xBF 0xBF
// we know that buffer[offset] is already 0xEF, don't bother checking it.
return false;
}
// no bad characters
return true;
}
private void ReadNonFFFE()
{
int off;
byte[] buff = BufferReader.GetBuffer(3, out off);
if (buff[off + 1] == 0xBF && (buff[off + 2] == 0xBE || buff[off + 2] == 0xBF))
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlInvalidFFFE));
}
BufferReader.Advance(3);
}
private void BufferElement()
{
int elementOffset = BufferReader.Offset;
const int byteCount = 128;
bool done = false;
byte quoteChar = 0;
while (!done)
{
int offset;
int offsetMax;
byte[] buffer = BufferReader.GetBuffer(byteCount, out offset, out offsetMax);
if (offset + byteCount != offsetMax)
break;
for (int i = offset; i < offsetMax && !done; i++)
{
byte b = buffer[i];
if (quoteChar == 0)
{
if (b == '\'' || b == '"')
quoteChar = b;
if (b == '>')
done = true;
}
else
{
if (b == quoteChar)
{
quoteChar = 0;
}
}
}
BufferReader.Advance(byteCount);
}
BufferReader.Offset = elementOffset;
}
private new void ReadStartElement()
{
if (!_buffered)
BufferElement();
XmlElementNode elementNode = EnterScope();
elementNode.NameOffset = BufferReader.Offset;
ReadQualifiedName(elementNode.Prefix, elementNode.LocalName);
elementNode.NameLength = BufferReader.Offset - elementNode.NameOffset;
byte ch = BufferReader.GetByte();
while ((s_charType[ch] & CharType.Whitespace) != 0)
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
}
if (ch != '>' && ch != '/')
{
ReadAttributes();
ch = BufferReader.GetByte();
}
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
bool isEmptyElement = false;
if (ch == '/')
{
isEmptyElement = true;
BufferReader.SkipByte();
}
elementNode.IsEmptyElement = isEmptyElement;
elementNode.ExitScope = isEmptyElement;
if (BufferReader.GetByte() != '>')
XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)BufferReader.GetByte());
BufferReader.SkipByte();
elementNode.BufferOffset = BufferReader.Offset;
}
private new void ReadEndElement()
{
BufferReader.SkipByte();
XmlElementNode elementNode = this.ElementNode;
int nameOffset = elementNode.NameOffset;
int nameLength = elementNode.NameLength;
int offset;
byte[] buffer = BufferReader.GetBuffer(nameLength, out offset);
for (int i = 0; i < nameLength; i++)
{
if (buffer[offset + i] != buffer[nameOffset + i])
{
ReadQualifiedName(_prefix, _localName);
XmlExceptionHelper.ThrowTagMismatch(this, elementNode.Prefix.GetString(), elementNode.LocalName.GetString(), _prefix.GetString(), _localName.GetString());
}
}
BufferReader.Advance(nameLength);
if (BufferReader.GetByte() != '>')
{
SkipWhitespace();
if (BufferReader.GetByte() != '>')
XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
MoveToEndElement();
}
private void ReadComment()
{
BufferReader.SkipByte();
if (BufferReader.GetByte() != '-')
XmlExceptionHelper.ThrowTokenExpected(this, "--", (char)BufferReader.GetByte());
BufferReader.SkipByte();
int commentOffset = BufferReader.Offset;
while (true)
{
while (true)
{
byte b = BufferReader.GetByte();
if (b == '-')
break;
if ((s_charType[b] & CharType.Comment) == 0)
{
if (b == 0xEF)
ReadNonFFFE();
else
XmlExceptionHelper.ThrowInvalidXml(this, b);
}
else
{
BufferReader.SkipByte();
}
}
int offset;
byte[] buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)'-' &&
buffer[offset + 1] == (byte)'-')
{
if (buffer[offset + 2] == (byte)'>')
break;
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlInvalidCommentChars));
}
BufferReader.SkipByte();
}
int commentLength = BufferReader.Offset - commentOffset;
MoveToComment().Value.SetValue(ValueHandleType.UTF8, commentOffset, commentLength);
BufferReader.Advance(3);
}
private void ReadCData()
{
int offset;
byte[] buffer = BufferReader.GetBuffer(7, out offset);
if (buffer[offset + 0] != (byte)'[' ||
buffer[offset + 1] != (byte)'C' ||
buffer[offset + 2] != (byte)'D' ||
buffer[offset + 3] != (byte)'A' ||
buffer[offset + 4] != (byte)'T' ||
buffer[offset + 5] != (byte)'A' ||
buffer[offset + 6] != (byte)'[')
{
XmlExceptionHelper.ThrowTokenExpected(this, "[CDATA[", Encoding.UTF8.GetString(buffer, offset, 7));
}
BufferReader.Advance(7);
int cdataOffset = BufferReader.Offset;
while (true)
{
byte b;
while (true)
{
b = BufferReader.GetByte();
if (b == ']')
break;
if (b == 0xEF)
ReadNonFFFE();
else
BufferReader.SkipByte();
}
buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)']' &&
buffer[offset + 1] == (byte)']' &&
buffer[offset + 2] == (byte)'>')
break;
BufferReader.SkipByte();
}
int cdataLength = BufferReader.Offset - cdataOffset;
MoveToCData().Value.SetValue(ValueHandleType.UTF8, cdataOffset, cdataLength);
BufferReader.Advance(3);
}
private int ReadCharRef()
{
DiagnosticUtility.DebugAssert(BufferReader.GetByte() == '&', "");
int charEntityOffset = BufferReader.Offset;
BufferReader.SkipByte();
while (BufferReader.GetByte() != ';')
BufferReader.SkipByte();
BufferReader.SkipByte();
int charEntityLength = BufferReader.Offset - charEntityOffset;
BufferReader.Offset = charEntityOffset;
int ch = BufferReader.GetCharEntity(charEntityOffset, charEntityLength);
BufferReader.Advance(charEntityLength);
return ch;
}
private void ReadWhitespace()
{
byte[] buffer;
int offset;
int offsetMax;
int length;
if (_buffered)
{
buffer = BufferReader.GetBuffer(out offset, out offsetMax);
length = ReadWhitespace(buffer, offset, offsetMax);
}
else
{
buffer = BufferReader.GetBuffer(MaxTextChunk, out offset, out offsetMax);
length = ReadWhitespace(buffer, offset, offsetMax);
length = BreakText(buffer, offset, length);
}
BufferReader.Advance(length);
MoveToWhitespaceText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
private int ReadWhitespace(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int wsOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.SpecialWhitespace) != 0)
offset++;
return offset - wsOffset;
}
private int ReadText(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.Text) != 0)
offset++;
return offset - textOffset;
}
// Read Unicode codepoints 0xFvvv
private int ReadTextAndWatchForInvalidCharacters(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && ((charType[buffer[offset]] & CharType.Text) != 0 || buffer[offset] == 0xEF))
{
if (buffer[offset] != 0xEF)
{
offset++;
}
else
{
// Ensure that we have three bytes (buffer[offset], buffer[offset + 1], buffer[offset + 2])
// available for IsNextCharacterNonFFFE to check.
if (offset + 2 < offsetMax)
{
if (IsNextCharacterNonFFFE(buffer, offset))
{
// if first byte is 0xEF, UTF8 mandates a 3-byte character representation of this Unicode code point
offset += 3;
}
else
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlInvalidFFFE));
}
}
else
{
if (BufferReader.Offset < offset)
{
// We have read some characters already
// Let the outer ReadText advance the bufferReader and return text node to caller
break;
}
else
{
// Get enough bytes for us to process next character, then go back to top of while loop
int dummy;
BufferReader.GetBuffer(3, out dummy);
}
}
}
}
return offset - textOffset;
}
// bytes bits UTF-8 representation
// ----- ---- -----------------------------------
// 1 7 0vvvvvvv
// 2 11 110vvvvv 10vvvvvv
// 3 16 1110vvvv 10vvvvvv 10vvvvvv
// 4 21 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv
// ----- ---- -----------------------------------
private int BreakText(byte[] buffer, int offset, int length)
{
// See if we might be breaking a utf8 sequence
if (length > 0 && (buffer[offset + length - 1] & 0x80) == 0x80)
{
// Find the lead char of the utf8 sequence (0x11xxxxxx)
int originalLength = length;
do
{
length--;
}
while (length > 0 && (buffer[offset + length] & 0xC0) != 0xC0);
// Couldn't find the lead char
if (length == 0)
return originalLength; // Invalid utf8 sequence - can't break
// Count how many bytes follow the lead char
byte b = unchecked((byte)(buffer[offset + length] << 2));
int byteCount = 2;
while ((b & 0x80) == 0x80)
{
b = unchecked((byte)(b << 1));
byteCount++;
// There shouldn't be more than 3 bytes following the lead char
if (byteCount > 4)
return originalLength; // Invalid utf8 sequence - can't break
}
if (length + byteCount == originalLength)
return originalLength; // sequence fits exactly
}
return length;
}
private void ReadText(bool hasLeadingByteOf0xEF)
{
byte[] buffer;
int offset;
int offsetMax;
int length;
if (_buffered)
{
buffer = BufferReader.GetBuffer(out offset, out offsetMax);
if (hasLeadingByteOf0xEF)
{
length = ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax);
}
else
{
length = ReadText(buffer, offset, offsetMax);
}
}
else
{
buffer = BufferReader.GetBuffer(MaxTextChunk, out offset, out offsetMax);
if (hasLeadingByteOf0xEF)
{
length = ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax);
}
else
{
length = ReadText(buffer, offset, offsetMax);
}
length = BreakText(buffer, offset, length);
}
BufferReader.Advance(length);
if (offset < offsetMax - 1 - length && (buffer[offset + length] == (byte)'<' && buffer[offset + length + 1] != (byte)'!'))
{
MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
else
{
MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
}
private void ReadEscapedText()
{
int ch = ReadCharRef();
if (ch < 256 && (s_charType[ch] & CharType.Whitespace) != 0)
MoveToWhitespaceText().Value.SetCharValue(ch);
else
MoveToComplexText().Value.SetCharValue(ch);
}
public override bool Read()
{
if (this.Node.ReadState == ReadState.Closed)
return false;
if (this.Node.CanMoveToElement)
{
// If we're positioned on an attribute or attribute text on an empty element, we need to move back
// to the element in order to get the correct setting of ExitScope
MoveToElement();
}
SignNode();
if (this.Node.ExitScope)
{
ExitScope();
}
if (!_buffered)
BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead);
if (BufferReader.EndOfFile)
{
MoveToEndOfFile();
return false;
}
byte ch = BufferReader.GetByte();
if (ch == (byte)'<')
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
if (ch == (byte)'/')
ReadEndElement();
else if (ch == (byte)'!')
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
if (ch == '-')
{
ReadComment();
}
else
{
if (OutsideRootElement)
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlCDATAInvalidAtTopLevel));
ReadCData();
}
}
else if (ch == (byte)'?')
ReadDeclaration();
else
ReadStartElement();
}
else if ((s_charType[ch] & CharType.SpecialWhitespace) != 0)
{
ReadWhitespace();
}
else if (OutsideRootElement && ch != '\r')
{
XmlExceptionHelper.ThrowInvalidRootData(this);
}
else if ((s_charType[ch] & CharType.Text) != 0)
{
ReadText(false);
}
else if (ch == '&')
{
ReadEscapedText();
}
else if (ch == '\r')
{
BufferReader.SkipByte();
if (!BufferReader.EndOfFile && BufferReader.GetByte() == '\n')
ReadWhitespace();
else
MoveToComplexText().Value.SetCharValue('\n');
}
else if (ch == ']')
{
int offset;
byte[] buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)']' &&
buffer[offset + 1] == (byte)']' &&
buffer[offset + 2] == (byte)'>')
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlCloseCData));
}
BufferReader.SkipByte();
MoveToComplexText().Value.SetCharValue(']'); // Need to get past the ']' and keep going.
}
else if (ch == 0xEF) // Watch for invalid characters 0xfffe and 0xffff
{
ReadText(true);
}
else
{
XmlExceptionHelper.ThrowInvalidXml(this, ch);
}
return true;
}
protected override XmlSigningNodeWriter CreateSigningNodeWriter()
{
return new XmlSigningNodeWriter(true);
}
public bool HasLineInfo()
{
return true;
}
public int LineNumber
{
get
{
int row, column;
GetPosition(out row, out column);
return row;
}
}
public int LinePosition
{
get
{
int row, column;
GetPosition(out row, out column);
return column;
}
}
private void GetPosition(out int row, out int column)
{
if (_rowOffsets == null)
{
_rowOffsets = BufferReader.GetRows();
}
int offset = BufferReader.Offset;
int j = 0;
while (j < _rowOffsets.Length - 1 && _rowOffsets[j + 1] < offset)
j++;
row = j + 1;
column = offset - _rowOffsets[j] + 1;
}
private static class CharType
{
public const byte None = 0x00;
public const byte FirstName = 0x01;
public const byte Name = 0x02;
public const byte Whitespace = 0x04;
public const byte Text = 0x08;
public const byte AttributeText = 0x10;
public const byte SpecialWhitespace = 0x20;
public const byte Comment = 0x40;
}
}
}
| |
using Firehose.Web.Extensions;
using Microsoft.Extensions.Caching.Memory;
using Polly;
using Polly.Caching;
using Polly.Caching.Memory;
using Polly.Retry;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.ServiceModel.Syndication;
using System.Threading.Tasks;
using System.Xml;
namespace Firehose.Web.Infrastructure
{
public class NewCombinedFeedSource
{
private static HttpClient httpClient;
private static AsyncRetryPolicy retryPolicy;
private static AsyncCachePolicy cachePolicy;
public IEnumerable<IAmACommunityMember> Tamarins { get; }
public NewCombinedFeedSource(IEnumerable<IAmACommunityMember> tamarins)
{
EnsureHttpClient();
Tamarins = tamarins;
if (retryPolicy == null)
{
// cache in memory for an hour
var memoryCache = new MemoryCache(new MemoryCacheOptions());
var memoryCacheProvider = new MemoryCacheProvider(memoryCache);
cachePolicy = Policy.CacheAsync(memoryCacheProvider, TimeSpan.FromHours(1), OnCacheError);
// retry policy with max 2 retries, delay by x*x^1.2 where x is retry attempt
// this will ensure we don't retry too quickly
retryPolicy = Policy.Handle<FeedReadFailedException>()
.WaitAndRetryAsync(2, retry => TimeSpan.FromSeconds(retry * Math.Pow(1.2, retry)));
}
}
private void OnCacheError(Context arg1, string arg2, Exception arg3)
{
Logger.Error(arg3, $"Failed caching item: {arg1} - {arg2}");
}
private void EnsureHttpClient()
{
if (httpClient == null)
{
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.UserAgent.Add(
new ProductInfoHeaderValue("PlanetXamarin", $"{GetType().Assembly.GetName().Version}"));
httpClient.Timeout = TimeSpan.FromSeconds(15);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
}
}
private async Task<SyndicationFeed> LoadFeedInternal(int? numberOfItems, string languageCode = "mixed")
{
IEnumerable<IAmACommunityMember> tamarins;
if (languageCode == null || languageCode == "mixed") // use all tamarins
{
tamarins = Tamarins;
}
else
{
tamarins = Tamarins.Where(t => CultureInfo.CreateSpecificCulture(t.FeedLanguageCode).Name == languageCode);
}
var feedTasks = tamarins.SelectMany(t => TryReadFeeds(t, GetFilterFunction(t)));
var syndicationItems = await Task.WhenAll(feedTasks).ConfigureAwait(false);
var combinedFeed = GetCombinedFeed(syndicationItems.SelectMany(f => f), languageCode, tamarins, numberOfItems);
return combinedFeed;
}
public Task<SyndicationFeed> LoadFeed(int? numberOfItems, string languageCode = "mixed")
{
return cachePolicy.ExecuteAsync(context => LoadFeedInternal(numberOfItems, languageCode), new Context($"feed{numberOfItems}{languageCode}"));
}
private IEnumerable<Task<IEnumerable<SyndicationItem>>> TryReadFeeds(IAmACommunityMember tamarin, Func<SyndicationItem, bool> filter)
{
return tamarin.FeedUris.Select(uri => TryReadFeed(tamarin, uri.AbsoluteUri, filter));
}
private async Task<IEnumerable<SyndicationItem>> TryReadFeed(IAmACommunityMember tamarin, string feedUri, Func<SyndicationItem, bool> filter)
{
try
{
return await retryPolicy.ExecuteAsync(context => ReadFeed(feedUri, filter), new Context(feedUri)).ConfigureAwait(false);
}
catch (FeedReadFailedException ex)
{
Logger.Error(ex, $"{tamarin.FirstName} {tamarin.LastName}'s feed of {ex.Data["FeedUri"]} failed to load.");
}
return new SyndicationItem[0];
}
private async Task<IEnumerable<SyndicationItem>> ReadFeed(string feedUri, Func<SyndicationItem, bool> filter)
{
HttpResponseMessage response;
try
{
response = await httpClient.GetAsync(feedUri).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
using (var feedStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var reader = XmlReader.Create(feedStream))
{
var feed = SyndicationFeed.Load(reader);
var filteredItems = feed.Items
.Where(item => TryFilter(item, filter));
return filteredItems;
}
}
}
catch (HttpRequestException hex)
{
throw new FeedReadFailedException("Loading remote syndication feed failed", hex)
.WithData("FeedUri", feedUri);
}
catch (WebException ex)
{
throw new FeedReadFailedException("Loading remote syndication feed timed out", ex)
.WithData("FeedUri", feedUri);
}
catch (XmlException ex)
{
throw new FeedReadFailedException("Failed parsing remote syndication feed", ex)
.WithData("FeedUri", feedUri);
}
catch (TaskCanceledException ex)
{
throw new FeedReadFailedException("Reading feed timed out", ex)
.WithData("FeedUri", feedUri);
}
catch (OperationCanceledException opcex)
{
throw new FeedReadFailedException("Reading feed timed out", opcex)
.WithData("FeedUri", feedUri);
}
throw new FeedReadFailedException("Loading remote syndication feed failed.")
.WithData("FeedUri", feedUri)
.WithData("HttpStatusCode", (int)response.StatusCode);
}
private SyndicationFeed GetCombinedFeed(IEnumerable<SyndicationItem> items, string languageCode,
IEnumerable<IAmACommunityMember> tamarins, int? numberOfItems)
{
DateTimeOffset GetMaxTime(SyndicationItem item)
{
return new[] { item.PublishDate.UtcDateTime, item.LastUpdatedTime.UtcDateTime }.Max();
}
var orderedItems = items
.Where(item =>
GetMaxTime(item) <= DateTimeOffset.UtcNow)
.OrderByDescending(item => GetMaxTime(item));
var feed = new SyndicationFeed(
ConfigurationManager.AppSettings["RssFeedTitle"],
ConfigurationManager.AppSettings["RssFeedDescription"],
new Uri(ConfigurationManager.AppSettings["BaseUrl"] ?? "https://planetxamarin.com"),
numberOfItems.HasValue ? orderedItems.Take(numberOfItems.Value) : orderedItems)
{
ImageUrl = new Uri(ConfigurationManager.AppSettings["RssFeedImageUrl"] ?? "https://planetxamarin.com/Content/Logo.png"),
Copyright = new TextSyndicationContent("The copyright for each post is retained by its author."),
Language = languageCode,
LastUpdatedTime = DateTimeOffset.UtcNow
};
foreach(var tamarin in tamarins)
{
feed.Contributors.Add(new SyndicationPerson(
tamarin.EmailAddress, $"{tamarin.FirstName} {tamarin.LastName}", tamarin.WebSite.ToString()));
}
return feed;
}
private static Func<SyndicationItem, bool> GetFilterFunction(IAmACommunityMember tamarin)
{
if (tamarin is IFilterMyBlogPosts filterMyBlogPosts)
{
return filterMyBlogPosts.Filter;
}
return null;
}
private static bool TryFilter(SyndicationItem item, Func<SyndicationItem, bool> filterFunc)
{
try
{
if (filterFunc != null)
return filterFunc(item);
}
catch (Exception)
{
}
// the authors' filter is derped or has no filter
// try some sane defaults
return item.ApplyDefaultFilter();
}
}
public class FeedReadFailedException : Exception
{
public FeedReadFailedException(string message)
: base(message)
{
}
public FeedReadFailedException(string message, Exception inner)
: base(message, inner)
{
}
}
internal static class ExceptionExtensions
{
public static TException WithData<TException>(this TException exception, string key, object value) where TException : Exception
{
exception.Data[key] = value;
return exception;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
/// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
/// a remote call so in general you should reuse a single channel for as many calls as possible.
/// </summary>
public class Channel
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
readonly object myLock = new object();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource();
readonly string target;
readonly GrpcEnvironment environment;
readonly CompletionQueueSafeHandle completionQueue;
readonly ChannelSafeHandle handle;
readonly Dictionary<string, ChannelOption> options;
readonly Task connectivityWatcherTask;
bool shutdownRequested;
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
public Channel(string target, ChannelCredentials credentials) :
this(target, credentials, null)
{
}
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options)
{
this.target = GrpcPreconditions.CheckNotNull(target, "target");
this.options = CreateOptionsDictionary(options);
EnsureUserAgentChannelOption(this.options);
this.environment = GrpcEnvironment.AddRef();
this.completionQueue = this.environment.PickCompletionQueue();
using (var nativeCredentials = credentials.ToNativeCredentials())
using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
{
if (nativeCredentials != null)
{
this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
}
else
{
this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
}
}
// TODO(jtattermusch): Workaround for https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822.
// Remove once retries are supported in C core
this.connectivityWatcherTask = RunConnectivityWatcherAsync();
GrpcEnvironment.RegisterChannel(this);
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
public Channel(string host, int port, ChannelCredentials credentials) :
this(host, port, credentials, null)
{
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options) :
this(string.Format("{0}:{1}", host, port), credentials, options)
{
}
/// <summary>
/// Gets current connectivity state of this channel.
/// After channel is has been shutdown, <c>ChannelState.Shutdown</c> will be returned.
/// </summary>
public ChannelState State
{
get
{
return GetConnectivityState(false);
}
}
// cached handler for watch connectivity state
static readonly BatchCompletionDelegate WatchConnectivityStateHandler = (success, ctx, state) =>
{
var tcs = (TaskCompletionSource<object>) state;
if (success)
{
tcs.SetResult(null);
}
else
{
tcs.SetCanceled();
}
};
/// <summary>
/// Returned tasks completes once channel state has become different from
/// given lastObservedState.
/// If deadline is reached or and error occurs, returned task is cancelled.
/// </summary>
public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
{
GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
"Shutdown is a terminal state. No further state changes can occur.");
var tcs = new TaskCompletionSource<object>();
var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
// pass "tcs" as "state" for WatchConnectivityStateHandler.
handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs);
return tcs.Task;
}
/// <summary>Resolved address of the remote endpoint in URI format.</summary>
public string ResolvedTarget
{
get
{
return handle.GetTarget();
}
}
/// <summary>The original target used to create the channel.</summary>
public string Target
{
get
{
return this.target;
}
}
/// <summary>
/// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
/// </summary>
public CancellationToken ShutdownToken
{
get
{
return this.shutdownTokenSource.Token;
}
}
/// <summary>
/// Allows explicitly requesting channel to connect without starting an RPC.
/// Returned task completes once state Ready was seen. If the deadline is reached,
/// or channel enters the Shutdown state, the task is cancelled.
/// There is no need to call this explicitly unless your use case requires that.
/// Starting an RPC on a new channel will request connection implicitly.
/// </summary>
/// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
public async Task ConnectAsync(DateTime? deadline = null)
{
var currentState = GetConnectivityState(true);
while (currentState != ChannelState.Ready)
{
if (currentState == ChannelState.Shutdown)
{
throw new OperationCanceledException("Channel has reached Shutdown state.");
}
await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
currentState = GetConnectivityState(false);
}
}
/// <summary>
/// Shuts down the channel cleanly. It is strongly recommended to shutdown
/// all previously created channels before exiting from the process.
/// </summary>
/// <remarks>
/// This method doesn't wait for all calls on this channel to finish (nor does
/// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
/// all the calls on this channel have finished (successfully or with an error)
/// before shutting down the channel to ensure channel shutdown won't impact
/// the outcome of those remote calls.
/// </remarks>
public async Task ShutdownAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
GrpcEnvironment.UnregisterChannel(this);
shutdownTokenSource.Cancel();
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
}
handle.Dispose();
await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false);
}
internal ChannelSafeHandle Handle
{
get
{
return this.handle;
}
}
internal GrpcEnvironment Environment
{
get
{
return this.environment;
}
}
internal CompletionQueueSafeHandle CompletionQueue
{
get
{
return this.completionQueue;
}
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
GrpcPreconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
private ChannelState GetConnectivityState(bool tryToConnect)
{
try
{
return handle.CheckConnectivityState(tryToConnect);
}
catch (ObjectDisposedException)
{
return ChannelState.Shutdown;
}
}
/// <summary>
/// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822
/// </summary>
private async Task RunConnectivityWatcherAsync()
{
try
{
var lastState = State;
while (lastState != ChannelState.Shutdown)
{
lock (myLock)
{
if (shutdownRequested)
{
break;
}
}
try
{
await WaitForStateChangedAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false);
}
catch (TaskCanceledException)
{
// ignore timeout
}
lastState = State;
}
}
catch (ObjectDisposedException) {
// during shutdown, channel is going to be disposed.
}
}
private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
{
var key = ChannelOptions.PrimaryUserAgentString;
var userAgentString = "";
ChannelOption option;
if (options.TryGetValue(key, out option))
{
// user-provided userAgentString needs to be at the beginning
userAgentString = option.StringValue + " ";
};
// TODO(jtattermusch): it would be useful to also provide .NET/mono version.
userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
}
private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
{
var dict = new Dictionary<string, ChannelOption>();
if (options == null)
{
return dict;
}
foreach (var option in options)
{
dict.Add(option.Name, option);
}
return dict;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using System.Xml.XPath;
using Examine;
using Examine.LuceneEngine.SearchCriteria;
using Examine.Providers;
using Lucene.Net.Documents;
using Lucene.Net.Store;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Xml;
using Umbraco.Web.Models;
using UmbracoExamine;
using umbraco;
using Umbraco.Core.Cache;
using Umbraco.Core.Sync;
using Umbraco.Web.Cache;
namespace Umbraco.Web.PublishedCache.XmlPublishedCache
{
/// <summary>
/// An IPublishedMediaStore that first checks for the media in Examine, and then reverts to the database
/// </summary>
/// <remarks>
/// NOTE: In the future if we want to properly cache all media this class can be extended or replaced when these classes/interfaces are exposed publicly.
/// </remarks>
internal class PublishedMediaCache : IPublishedMediaCache
{
public PublishedMediaCache(ApplicationContext applicationContext)
{
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
_applicationContext = applicationContext;
}
/// <summary>
/// Generally used for unit testing to use an explicit examine searcher
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="searchProvider"></param>
/// <param name="indexProvider"></param>
internal PublishedMediaCache(ApplicationContext applicationContext, BaseSearchProvider searchProvider, BaseIndexProvider indexProvider)
{
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
if (searchProvider == null) throw new ArgumentNullException("searchProvider");
if (indexProvider == null) throw new ArgumentNullException("indexProvider");
_applicationContext = applicationContext;
_searchProvider = searchProvider;
_indexProvider = indexProvider;
}
static PublishedMediaCache()
{
InitializeCacheConfig();
}
private readonly ApplicationContext _applicationContext;
private readonly BaseSearchProvider _searchProvider;
private readonly BaseIndexProvider _indexProvider;
public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId)
{
return GetUmbracoMedia(nodeId);
}
public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview)
{
var searchProvider = GetSearchProviderSafe();
if (searchProvider != null)
{
try
{
// first check in Examine for the cache values
// +(+parentID:-1) +__IndexType:media
var criteria = searchProvider.CreateSearchCriteria("media");
var filter = criteria.ParentId(-1).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard());
var result = searchProvider.Search(filter.Compile());
if (result != null)
return result.Select(x => CreateFromCacheValues(ConvertFromSearchResult(x)));
}
catch (Exception ex)
{
if (ex is FileNotFoundException)
{
//Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco
//See this thread: http://examine.cdodeplex.com/discussions/264341
//Catch the exception here for the time being, and just fallback to GetMedia
//TODO: Need to fix examine in LB scenarios!
LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media", ex);
}
else if (ex is AlreadyClosedException)
{
//If the app domain is shutting down and the site is under heavy load the index reader will be closed and it really cannot
//be re-opened since the app domain is shutting down. In this case we have no option but to try to load the data from the db.
LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media, the app domain is most likely in a shutdown state", ex);
}
else throw;
}
}
//something went wrong, fetch from the db
var rootMedia = _applicationContext.Services.MediaService.GetRootMedia();
return rootMedia.Select(m => CreateFromCacheValues(ConvertFromIMedia(m)));
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public bool XPathNavigatorIsNavigable { get { return false; } }
public virtual bool HasContent(UmbracoContext context, bool preview) { throw new NotImplementedException(); }
private ExamineManager GetExamineManagerSafe()
{
try
{
return ExamineManager.Instance;
}
catch (TypeInitializationException)
{
return null;
}
}
private BaseIndexProvider GetIndexProviderSafe()
{
if (_indexProvider != null)
return _indexProvider;
var eMgr = GetExamineManagerSafe();
if (eMgr != null)
{
try
{
//by default use the InternalSearcher
var indexer = eMgr.IndexProviderCollection[Constants.Examine.InternalIndexer];
if (indexer.IndexerData.IncludeNodeTypes.Any() || indexer.IndexerData.ExcludeNodeTypes.Any())
{
LogHelper.Warn<PublishedMediaCache>("The InternalIndexer for examine is configured incorrectly, it should not list any include/exclude node types or field names, it should simply be configured as: " + "<IndexSet SetName=\"InternalIndexSet\" IndexPath=\"~/App_Data/TEMP/ExamineIndexes/Internal/\" />");
}
return indexer;
}
catch (Exception ex)
{
LogHelper.Error<PublishedMediaCache>("Could not retrieve the InternalIndexer", ex);
//something didn't work, continue returning null.
}
}
return null;
}
private BaseSearchProvider GetSearchProviderSafe()
{
if (_searchProvider != null)
return _searchProvider;
var eMgr = GetExamineManagerSafe();
if (eMgr != null)
{
try
{
//by default use the InternalSearcher
return eMgr.SearchProviderCollection[Constants.Examine.InternalSearcher];
}
catch (FileNotFoundException)
{
//Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco
//See this thread: http://examine.cdodeplex.com/discussions/264341
//Catch the exception here for the time being, and just fallback to GetMedia
//TODO: Need to fix examine in LB scenarios!
}
catch (NullReferenceException)
{
//This will occur when the search provider cannot be initialized. In newer examine versions the initialization is lazy and therefore
// the manager will return the singleton without throwing initialization errors, however if examine isn't configured correctly a null
// reference error will occur because the examine settings are null.
}
catch (AlreadyClosedException)
{
//If the app domain is shutting down and the site is under heavy load the index reader will be closed and it really cannot
//be re-opened since the app domain is shutting down. In this case we have no option but to try to load the data from the db.
}
}
return null;
}
private IPublishedContent GetUmbracoMedia(int id)
{
// this recreates an IPublishedContent and model each time
// it is called, but at least it should NOT hit the database
// nor Lucene each time, relying on the memory cache instead
if (id <= 0) return null; // fail fast
var cacheValues = GetCacheValues(id, GetUmbracoMediaCacheValues);
return cacheValues == null ? null : CreateFromCacheValues(cacheValues);
}
private CacheValues GetUmbracoMediaCacheValues(int id)
{
var searchProvider = GetSearchProviderSafe();
if (searchProvider != null)
{
try
{
// first check in Examine as this is WAY faster
//
// the filter will create a query like this:
// +(+__NodeId:3113 -__Path:-1,-21,*) +__IndexType:media
//
// note that since the use of the wildcard, it automatically escapes it in Lucene.
var criteria = searchProvider.CreateSearchCriteria("media");
var filter = criteria.Id(id).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard());
var result = searchProvider.Search(filter.Compile()).FirstOrDefault();
if (result != null) return ConvertFromSearchResult(result);
}
catch (Exception ex)
{
if (ex is FileNotFoundException)
{
//Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco
//See this thread: http://examine.cdodeplex.com/discussions/264341
//Catch the exception here for the time being, and just fallback to GetMedia
//TODO: Need to fix examine in LB scenarios!
LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media", ex);
}
else if (ex is AlreadyClosedException)
{
//If the app domain is shutting down and the site is under heavy load the index reader will be closed and it really cannot
//be re-opened since the app domain is shutting down. In this case we have no option but to try to load the data from the db.
LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media, the app domain is most likely in a shutdown state", ex);
}
else throw;
}
}
// don't log a warning here, as it can flood the log in case of eg a media picker referencing a media
// that has been deleted, hence is not in the Examine index anymore (for a good reason). try to get
// the media from the service, first
var media = ApplicationContext.Current.Services.MediaService.GetById(id);
if (media == null || media.Trashed) return null; // not found, ok
// so, the media was not found in Examine's index *yet* it exists, which probably indicates that
// the index is corrupted. Or not up-to-date. Log a warning, but only once, and only if seeing the
// error more that a number of times.
var miss = Interlocked.CompareExchange(ref _examineIndexMiss, 0, 0); // volatile read
if (miss < ExamineIndexMissMax && Interlocked.Increment(ref _examineIndexMiss) == ExamineIndexMissMax)
LogHelper.Warn<PublishedMediaCache>("Failed ({0} times) to retrieve medias from Examine index and had to load"
+ " them from DB. This may indicate that the Examine index is corrupted.",
() => ExamineIndexMissMax);
return ConvertFromIMedia(media);
}
private const int ExamineIndexMissMax = 10;
private int _examineIndexMiss;
internal CacheValues ConvertFromXPathNodeIterator(XPathNodeIterator media, int id)
{
if (media != null && media.Current != null)
{
return media.Current.Name.InvariantEquals("error")
? null
: ConvertFromXPathNavigator(media.Current);
}
LogHelper.Warn<PublishedMediaCache>(
"Could not retrieve media {0} from Examine index or from legacy library.GetMedia method",
() => id);
return null;
}
internal CacheValues ConvertFromSearchResult(SearchResult searchResult)
{
//NOTE: Some fields will not be included if the config section for the internal index has been
//mucked around with. It should index everything and so the index definition should simply be:
// <IndexSet SetName="InternalIndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/Internal/" />
var values = new Dictionary<string, string>(searchResult.Fields);
//we need to ensure some fields exist, because of the above issue
if (!new[] { "template", "templateId" }.Any(values.ContainsKey))
values.Add("template", 0.ToString());
if (!new[] { "sortOrder" }.Any(values.ContainsKey))
values.Add("sortOrder", 0.ToString());
if (!new[] { "urlName" }.Any(values.ContainsKey))
values.Add("urlName", "");
if (!new[] { "nodeType" }.Any(values.ContainsKey))
values.Add("nodeType", 0.ToString());
if (!new[] { "creatorName" }.Any(values.ContainsKey))
values.Add("creatorName", "");
if (!new[] { "writerID" }.Any(values.ContainsKey))
values.Add("writerID", 0.ToString());
if (!new[] { "creatorID" }.Any(values.ContainsKey))
values.Add("creatorID", 0.ToString());
if (!new[] { "createDate" }.Any(values.ContainsKey))
values.Add("createDate", default(DateTime).ToString("yyyy-MM-dd HH:mm:ss"));
if (!new[] { "level" }.Any(values.ContainsKey))
{
values.Add("level", values["__Path"].Split(',').Length.ToString());
}
// because, migration
if (values.ContainsKey("key") == false)
values["key"] = Guid.Empty.ToString();
return new CacheValues
{
Values = values,
FromExamine = true
};
//var content = new DictionaryPublishedContent(values,
// d => d.ParentId != -1 //parent should be null if -1
// ? GetUmbracoMedia(d.ParentId)
// : null,
// //callback to return the children of the current node
// d => GetChildrenMedia(d.Id),
// GetProperty,
// true);
//return content.CreateModel();
}
internal CacheValues ConvertFromXPathNavigator(XPathNavigator xpath, bool forceNav = false)
{
if (xpath == null) throw new ArgumentNullException("xpath");
var values = new Dictionary<string, string> { { "nodeName", xpath.GetAttribute("nodeName", "") } };
if (!UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
values["nodeTypeAlias"] = xpath.Name;
}
var result = xpath.SelectChildren(XPathNodeType.Element);
//add the attributes e.g. id, parentId etc
if (result.Current != null && result.Current.HasAttributes)
{
if (result.Current.MoveToFirstAttribute())
{
//checking for duplicate keys because of the 'nodeTypeAlias' might already be added above.
if (!values.ContainsKey(result.Current.Name))
{
values[result.Current.Name] = result.Current.Value;
}
while (result.Current.MoveToNextAttribute())
{
if (!values.ContainsKey(result.Current.Name))
{
values[result.Current.Name] = result.Current.Value;
}
}
result.Current.MoveToParent();
}
}
// because, migration
if (values.ContainsKey("key") == false)
values["key"] = Guid.Empty.ToString();
//add the user props
while (result.MoveNext())
{
if (result.Current != null && !result.Current.HasAttributes)
{
string value = result.Current.Value;
if (string.IsNullOrEmpty(value))
{
if (result.Current.HasAttributes || result.Current.SelectChildren(XPathNodeType.Element).Count > 0)
{
value = result.Current.OuterXml;
}
}
values[result.Current.Name] = value;
}
}
return new CacheValues
{
Values = values,
XPath = forceNav ? xpath : null // outside of tests we do NOT want to cache the navigator!
};
//var content = new DictionaryPublishedContent(values,
// d => d.ParentId != -1 //parent should be null if -1
// ? GetUmbracoMedia(d.ParentId)
// : null,
// //callback to return the children of the current node based on the xml structure already found
// d => GetChildrenMedia(d.Id, xpath),
// GetProperty,
// false);
//return content.CreateModel();
}
internal CacheValues ConvertFromIMedia(IMedia media)
{
var values = new Dictionary<string, string>();
var creator = _applicationContext.Services.UserService.GetProfileById(media.CreatorId);
var creatorName = creator == null ? "" : creator.Name;
values["id"] = media.Id.ToString();
values["key"] = media.Key.ToString();
values["parentID"] = media.ParentId.ToString();
values["level"] = media.Level.ToString();
values["creatorID"] = media.CreatorId.ToString();
values["creatorName"] = creatorName;
values["writerID"] = media.CreatorId.ToString();
values["writerName"] = creatorName;
values["template"] = "0";
values["urlName"] = "";
values["sortOrder"] = media.SortOrder.ToString();
values["createDate"] = media.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
values["updateDate"] = media.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss");
values["nodeName"] = media.Name;
values["path"] = media.Path;
values["nodeType"] = media.ContentType.Id.ToString();
values["nodeTypeAlias"] = media.ContentType.Alias;
// add the user props
foreach (var prop in media.Properties)
values[prop.Alias] = prop.Value == null ? null : prop.Value.ToString();
return new CacheValues
{
Values = values
};
}
/// <summary>
/// We will need to first check if the document was loaded by Examine, if so we'll need to check if this property exists
/// in the results, if it does not, then we'll have to revert to looking up in the db.
/// </summary>
/// <param name="dd"> </param>
/// <param name="alias"></param>
/// <returns></returns>
private IPublishedProperty GetProperty(DictionaryPublishedContent dd, string alias)
{
//lets check if the alias does not exist on the document.
//NOTE: Examine will not index empty values and we do not output empty XML Elements to the cache - either of these situations
// would mean that the property is missing from the collection whether we are getting the value from Examine or from the library media cache.
if (dd.Properties.All(x => x.PropertyTypeAlias.InvariantEquals(alias) == false))
{
return null;
}
if (dd.LoadedFromExamine)
{
//We are going to check for a special field however, that is because in some cases we store a 'Raw'
//value in the index such as for xml/html.
var rawValue = dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(UmbracoContentIndexer.RawFieldPrefix + alias));
return rawValue
?? dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias));
}
//if its not loaded from examine, then just return the property
return dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias));
}
/// <summary>
/// A Helper methods to return the children for media whther it is based on examine or xml
/// </summary>
/// <param name="parentId"></param>
/// <param name="xpath"></param>
/// <returns></returns>
private IEnumerable<IPublishedContent> GetChildrenMedia(int parentId, XPathNavigator xpath = null)
{
//if there is no navigator, try examine first, then re-look it up
if (xpath == null)
{
var searchProvider = GetSearchProviderSafe();
if (searchProvider != null)
{
try
{
//first check in Examine as this is WAY faster
var criteria = searchProvider.CreateSearchCriteria("media");
var filter = criteria.ParentId(parentId).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard());
//the above filter will create a query like this, NOTE: That since the use of the wildcard, it automatically escapes it in Lucene.
//+(+parentId:3113 -__Path:-1,-21,*) +__IndexType:media
ISearchResults results;
//we want to check if the indexer for this searcher has "sortOrder" flagged as sortable.
//if so, we'll use Lucene to do the sorting, if not we'll have to manually sort it (slower).
var indexer = GetIndexProviderSafe();
var useLuceneSort = indexer != null && indexer.IndexerData.StandardFields.Any(x => x.Name.InvariantEquals("sortOrder") && x.EnableSorting);
if (useLuceneSort)
{
//we have a sortOrder field declared to be sorted, so we'll use Examine
results = searchProvider.Search(
filter.And().OrderBy(new SortableField("sortOrder", SortType.Int)).Compile());
}
else
{
results = searchProvider.Search(filter.Compile());
}
if (results.Any())
{
// var medias = results.Select(ConvertFromSearchResult);
var medias = results.Select(x =>
{
int nid;
if (int.TryParse(x["__NodeId"], out nid) == false && int.TryParse(x["NodeId"], out nid) == false)
throw new Exception("Failed to extract NodeId from search result.");
var cacheValues = GetCacheValues(nid, id => ConvertFromSearchResult(x));
return CreateFromCacheValues(cacheValues);
});
return useLuceneSort ? medias : medias.OrderBy(x => x.SortOrder);
}
else
{
//if there's no result then return null. Previously we defaulted back to library.GetMedia below
//but this will always get called for when we are getting descendents since many items won't have
//children and then we are hitting the database again!
//So instead we're going to rely on Examine to have the correct results like it should.
return Enumerable.Empty<IPublishedContent>();
}
}
catch (FileNotFoundException)
{
//Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco
//See this thread: http://examine.cdodeplex.com/discussions/264341
//Catch the exception here for the time being, and just fallback to GetMedia
}
}
//falling back to get media
var media = library.GetMedia(parentId, true);
if (media != null && media.Current != null)
{
xpath = media.Current;
}
else
{
return Enumerable.Empty<IPublishedContent>();
}
}
var mediaList = new List<IPublishedContent>();
// this is so bad, really
var item = xpath.Select("//*[@id='" + parentId + "']");
if (item.Current == null)
return Enumerable.Empty<IPublishedContent>();
var items = item.Current.SelectChildren(XPathNodeType.Element);
// and this does not work, because... meh
//var q = "//* [@id='" + parentId + "']/* [@id]";
//var items = xpath.Select(q);
foreach (XPathNavigator itemm in items)
{
int id;
if (int.TryParse(itemm.GetAttribute("id", ""), out id) == false)
continue; // wtf?
var captured = itemm;
var cacheValues = GetCacheValues(id, idd => ConvertFromXPathNavigator(captured));
mediaList.Add(CreateFromCacheValues(cacheValues));
}
////The xpath might be the whole xpath including the current ones ancestors so we need to select the current node
//var item = xpath.Select("//*[@id='" + parentId + "']");
//if (item.Current == null)
//{
// return Enumerable.Empty<IPublishedContent>();
//}
//var children = item.Current.SelectChildren(XPathNodeType.Element);
//foreach(XPathNavigator x in children)
//{
// //NOTE: I'm not sure why this is here, it is from legacy code of ExamineBackedMedia, but
// // will leave it here as it must have done something!
// if (x.Name != "contents")
// {
// //make sure it's actually a node, not a property
// if (!string.IsNullOrEmpty(x.GetAttribute("path", "")) &&
// !string.IsNullOrEmpty(x.GetAttribute("id", "")))
// {
// mediaList.Add(ConvertFromXPathNavigator(x));
// }
// }
//}
return mediaList;
}
/// <summary>
/// An IPublishedContent that is represented all by a dictionary.
/// </summary>
/// <remarks>
/// This is a helper class and definitely not intended for public use, it expects that all of the values required
/// to create an IPublishedContent exist in the dictionary by specific aliases.
/// </remarks>
internal class DictionaryPublishedContent : PublishedContentWithKeyBase
{
// note: I'm not sure this class fully complies with IPublishedContent rules especially
// I'm not sure that _properties contains all properties including those without a value,
// neither that GetProperty will return a property without a value vs. null... @zpqrtbnk
// List of properties that will appear in the XML and do not match
// anything in the ContentType, so they must be ignored.
private static readonly string[] IgnoredKeys = { "version", "isDoc" };
public DictionaryPublishedContent(
IDictionary<string, string> valueDictionary,
Func<int, IPublishedContent> getParent,
Func<int, XPathNavigator, IEnumerable<IPublishedContent>> getChildren,
Func<DictionaryPublishedContent, string, IPublishedProperty> getProperty,
XPathNavigator nav,
bool fromExamine)
{
if (valueDictionary == null) throw new ArgumentNullException("valueDictionary");
if (getParent == null) throw new ArgumentNullException("getParent");
if (getProperty == null) throw new ArgumentNullException("getProperty");
_getParent = new Lazy<IPublishedContent>(() => getParent(ParentId));
_getChildren = new Lazy<IEnumerable<IPublishedContent>>(() => getChildren(Id, nav));
_getProperty = getProperty;
LoadedFromExamine = fromExamine;
ValidateAndSetProperty(valueDictionary, val => _id = int.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int!
ValidateAndSetProperty(valueDictionary, val => _key = Guid.Parse(val), "key");
// wtf are we dealing with templates for medias?!
ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId");
ValidateAndSetProperty(valueDictionary, val => _sortOrder = int.Parse(val), "sortOrder");
ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName", "__nodeName");
ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName");
ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", UmbracoContentIndexer.NodeTypeAliasFieldName);
ValidateAndSetProperty(valueDictionary, val => _documentTypeId = int.Parse(val), "nodeType");
ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName");
ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132
ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID");
ValidateAndSetProperty(valueDictionary, val => _creatorId = int.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132
ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path");
ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate");
ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate");
ValidateAndSetProperty(valueDictionary, val => _level = int.Parse(val), "level");
ValidateAndSetProperty(valueDictionary, val =>
{
int pId;
ParentId = -1;
if (int.TryParse(val, out pId))
{
ParentId = pId;
}
}, "parentID");
_contentType = PublishedContentType.Get(PublishedItemType.Media, _documentTypeAlias);
_properties = new Collection<IPublishedProperty>();
//handle content type properties
//make sure we create them even if there's no value
foreach (var propertyType in _contentType.PropertyTypes)
{
var alias = propertyType.PropertyTypeAlias;
_keysAdded.Add(alias);
string value;
const bool isPreviewing = false; // false :: never preview a media
var property = valueDictionary.TryGetValue(alias, out value) == false || value == null
? new XmlPublishedProperty(propertyType, isPreviewing)
: new XmlPublishedProperty(propertyType, isPreviewing, value);
_properties.Add(property);
}
//loop through remaining values that haven't been applied
foreach (var i in valueDictionary.Where(x =>
_keysAdded.Contains(x.Key) == false // not already processed
&& IgnoredKeys.Contains(x.Key) == false)) // not ignorable
{
if (i.Key.InvariantStartsWith("__"))
{
// no type for that one, dunno how to convert
IPublishedProperty property = new PropertyResult(i.Key, i.Value, PropertyResultType.CustomProperty);
_properties.Add(property);
}
else
{
// this is a property that does not correspond to anything, ignore and log
LogHelper.Warn<PublishedMediaCache>("Dropping property \"" + i.Key + "\" because it does not belong to the content type.");
}
}
}
private DateTime ParseDateTimeValue(string val)
{
if (LoadedFromExamine)
{
try
{
//we might need to parse the date time using Lucene converters
return DateTools.StringToDate(val);
}
catch (FormatException)
{
//swallow exception, its not formatted correctly so revert to just trying to parse
}
}
return DateTime.Parse(val);
}
/// <summary>
/// Flag to get/set if this was laoded from examine cache
/// </summary>
internal bool LoadedFromExamine { get; private set; }
//private readonly Func<DictionaryPublishedContent, IPublishedContent> _getParent;
private readonly Lazy<IPublishedContent> _getParent;
//private readonly Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> _getChildren;
private readonly Lazy<IEnumerable<IPublishedContent>> _getChildren;
private readonly Func<DictionaryPublishedContent, string, IPublishedProperty> _getProperty;
/// <summary>
/// Returns 'Media' as the item type
/// </summary>
public override PublishedItemType ItemType
{
get { return PublishedItemType.Media; }
}
public override IPublishedContent Parent
{
get { return _getParent.Value; }
}
public int ParentId { get; private set; }
public override int Id
{
get { return _id; }
}
public override Guid Key { get { return _key; } }
public override int TemplateId
{
get
{
//TODO: should probably throw a not supported exception since media doesn't actually support this.
return _templateId;
}
}
public override int SortOrder
{
get { return _sortOrder; }
}
public override string Name
{
get { return _name; }
}
public override string UrlName
{
get { return _urlName; }
}
public override string DocumentTypeAlias
{
get { return _documentTypeAlias; }
}
public override int DocumentTypeId
{
get { return _documentTypeId; }
}
public override string WriterName
{
get { return _writerName; }
}
public override string CreatorName
{
get { return _creatorName; }
}
public override int WriterId
{
get { return _writerId; }
}
public override int CreatorId
{
get { return _creatorId; }
}
public override string Path
{
get { return _path; }
}
public override DateTime CreateDate
{
get { return _createDate; }
}
public override DateTime UpdateDate
{
get { return _updateDate; }
}
public override Guid Version
{
get { return _version; }
}
public override int Level
{
get { return _level; }
}
public override bool IsDraft
{
get { return false; }
}
public override ICollection<IPublishedProperty> Properties
{
get { return _properties; }
}
public override IEnumerable<IPublishedContent> Children
{
get { return _getChildren.Value; }
}
public override IPublishedProperty GetProperty(string alias)
{
return _getProperty(this, alias);
}
public override PublishedContentType ContentType
{
get { return _contentType; }
}
// override to implement cache
// cache at context level, ie once for the whole request
// but cache is not shared by requests because we wouldn't know how to clear it
public override IPublishedProperty GetProperty(string alias, bool recurse)
{
if (recurse == false) return GetProperty(alias);
IPublishedProperty property;
string key = null;
var cache = UmbracoContextCache.Current;
if (cache != null)
{
key = string.Format("RECURSIVE_PROPERTY::{0}::{1}", Id, alias.ToLowerInvariant());
object o;
if (cache.TryGetValue(key, out o))
{
property = o as IPublishedProperty;
if (property == null)
throw new InvalidOperationException("Corrupted cache.");
return property;
}
}
// else get it for real, no cache
property = base.GetProperty(alias, true);
if (cache != null)
cache[key] = property;
return property;
}
private readonly List<string> _keysAdded = new List<string>();
private int _id;
private Guid _key;
private int _templateId;
private int _sortOrder;
private string _name;
private string _urlName;
private string _documentTypeAlias;
private int _documentTypeId;
private string _writerName;
private string _creatorName;
private int _writerId;
private int _creatorId;
private string _path;
private DateTime _createDate;
private DateTime _updateDate;
private Guid _version;
private int _level;
private readonly ICollection<IPublishedProperty> _properties;
private readonly PublishedContentType _contentType;
private void ValidateAndSetProperty(IDictionary<string, string> valueDictionary, Action<string> setProperty, params string[] potentialKeys)
{
var key = potentialKeys.FirstOrDefault(x => valueDictionary.ContainsKey(x) && valueDictionary[x] != null);
if (key == null)
{
throw new FormatException("The valueDictionary is not formatted correctly and is missing any of the '" + string.Join(",", potentialKeys) + "' elements");
}
setProperty(valueDictionary[key]);
_keysAdded.Add(key);
}
}
// REFACTORING
// caching the basic atomic values - and the parent id
// but NOT caching actual parent nor children and NOT even
// the list of children ids - BUT caching the path
internal class CacheValues
{
public IDictionary<string, string> Values { get; set; }
public XPathNavigator XPath { get; set; }
public bool FromExamine { get; set; }
}
public const string PublishedMediaCacheKey = "MediaCacheMeh.";
private const int PublishedMediaCacheTimespanSeconds = 4 * 60; // 4 mins
private static TimeSpan _publishedMediaCacheTimespan;
private static bool _publishedMediaCacheEnabled;
private static void InitializeCacheConfig()
{
var value = ConfigurationManager.AppSettings["Umbraco.PublishedMediaCache.Seconds"];
int seconds;
if (int.TryParse(value, out seconds) == false)
seconds = PublishedMediaCacheTimespanSeconds;
if (seconds > 0)
{
_publishedMediaCacheEnabled = true;
_publishedMediaCacheTimespan = TimeSpan.FromSeconds(seconds);
}
else
{
_publishedMediaCacheEnabled = false;
}
}
internal IPublishedContent CreateFromCacheValues(CacheValues cacheValues)
{
var content = new DictionaryPublishedContent(
cacheValues.Values,
parentId => parentId < 0 ? null : GetUmbracoMedia(parentId),
GetChildrenMedia,
GetProperty,
cacheValues.XPath, // though, outside of tests, that should be null
cacheValues.FromExamine
);
return content.CreateModel();
}
private static CacheValues GetCacheValues(int id, Func<int, CacheValues> func)
{
if (_publishedMediaCacheEnabled == false)
return func(id);
var cache = ApplicationContext.Current.ApplicationCache.RuntimeCache;
var key = PublishedMediaCacheKey + id;
return (CacheValues)cache.GetCacheItem(key, () => func(id), _publishedMediaCacheTimespan);
}
internal static void ClearCache(int id)
{
var cache = ApplicationContext.Current.ApplicationCache.RuntimeCache;
var sid = id.ToString();
var key = PublishedMediaCacheKey + sid;
// we do clear a lot of things... but the cache refresher is somewhat
// convoluted and it's hard to tell what to clear exactly ;-(
// clear the parent - NOT (why?)
//var exist = (CacheValues) cache.GetCacheItem(key);
//if (exist != null)
// cache.ClearCacheItem(PublishedMediaCacheKey + GetValuesValue(exist.Values, "parentID"));
// clear the item
cache.ClearCacheItem(key);
// clear all children - in case we moved and their path has changed
var fid = "/" + sid + "/";
cache.ClearCacheObjectTypes<CacheValues>((k, v) =>
GetValuesValue(v.Values, "path", "__Path").Contains(fid));
}
private static string GetValuesValue(IDictionary<string, string> d, params string[] keys)
{
string value = null;
var ignored = keys.Any(x => d.TryGetValue(x, out value));
return 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 NPOI.HSSF.UserModel
{
using System;
using System.Text;
using NPOI.HSSF.Record;
using NPOI.HSSF.Model;
using NPOI.SS.Formula.PTG;
/// <summary>
/// High Level Represantion of Named Range
/// </summary>
/// <remarks>@author Libin Roman (Vista Portal LDT. Developer)</remarks>
public class HSSFName:NPOI.SS.UserModel.IName
{
private HSSFWorkbook book;
private NameRecord _definedNameRec;
private NameCommentRecord _commentRec;
/* package */
internal HSSFName(HSSFWorkbook book, NameRecord name):this(book, name, null)
{
}
/// <summary>
/// Creates new HSSFName - called by HSSFWorkbook to Create a sheet from
/// scratch.
/// </summary>
/// <param name="book">lowlevel Workbook object associated with the sheet.</param>
/// <param name="name">the Name Record</param>
/// <param name="comment"></param>
internal HSSFName(HSSFWorkbook book, NameRecord name, NameCommentRecord comment)
{
this.book = book;
this._definedNameRec = name;
_commentRec = comment;
}
/// <summary>
/// Gets or sets the sheets name which this named range is referenced to
/// </summary>
/// <value>sheet name, which this named range refered to</value>
public String SheetName
{
get
{
String result;
int indexToExternSheet = _definedNameRec.ExternSheetNumber;
result = book.Workbook.FindSheetFirstNameFromExternSheet(indexToExternSheet);
return result;
}
//set
//{
// int sheetNumber = book.GetSheetIndex(value);
// int externSheetNumber = book.GetExternalSheetIndex(sheetNumber);
// name.ExternSheetNumber = externSheetNumber;
//}
}
/// <summary>
/// Gets or sets the name of the named range
/// </summary>
/// <value>named range name</value>
public String NameName
{
get
{
String result = _definedNameRec.NameText;
return result;
}
set
{
ValidateName(value);
_definedNameRec.NameText = value;
InternalWorkbook wb = book.Workbook;
int sheetNumber = _definedNameRec.SheetNumber;
//Check to Ensure no other names have the same case-insensitive name
for (int i = wb.NumNames- 1; i >= 0; i--)
{
NameRecord rec = wb.GetNameRecord(i);
if (rec != _definedNameRec)
{
if (rec.NameText.Equals(NameName, StringComparison.OrdinalIgnoreCase) && sheetNumber == rec.SheetNumber)
{
String msg = "The " + (sheetNumber == 0 ? "workbook" : "sheet") + " already contains this name: " + value;
_definedNameRec.NameText = (value + "(2)");
throw new ArgumentException(msg);
}
}
}
// Update our comment, if there is one
if (_commentRec != null)
{
String oldName = _commentRec.NameText;
_commentRec.NameText=value;
book.Workbook.UpdateNameCommentRecordCache(_commentRec);
}
}
}
private void ValidateName(String name)
{
if (name.Length == 0) throw new ArgumentException("Name cannot be blank");
char c = name[0];
if (!(c == '_' || Char.IsLetter(c)) || name.IndexOf(' ') != -1)
{
throw new ArgumentException("Invalid name: '" + name + "'; Names must begin with a letter or underscore and not contain spaces");
}
}
public String RefersToFormula
{
get
{
if (_definedNameRec.IsFunctionName)
{
throw new InvalidOperationException("Only applicable to named ranges");
}
Ptg[] ptgs = _definedNameRec.NameDefinition;
if (ptgs.Length < 1)
{
// 'refersToFormula' has not been set yet
return null;
}
return HSSFFormulaParser.ToFormulaString(book, ptgs);
}
set
{
Ptg[] ptgs = HSSFFormulaParser.Parse(value, book, NPOI.SS.Formula.FormulaType.NamedRange, SheetIndex);
_definedNameRec.NameDefinition = ptgs;
}
}
/**
* Returns the sheet index this name applies to.
*
* @return the sheet index this name applies to, -1 if this name applies to the entire workbook
*/
public int SheetIndex
{
get
{
return _definedNameRec.SheetNumber - 1;
}
set
{
int lastSheetIx = book.NumberOfSheets - 1;
if (value < -1 || value > lastSheetIx)
{
throw new ArgumentException("Sheet index (" + value + ") is out of range" +
(lastSheetIx == -1 ? "" : (" (0.." + lastSheetIx + ")")));
}
_definedNameRec.SheetNumber = (value + 1);
}
}
public string Comment
{
get
{
if (_commentRec != null)
{
// Prefer the comment record if it has text in it
if (_commentRec.CommentText != null &&
_commentRec.CommentText.Length > 0)
{
return _commentRec.CommentText;
}
}
return _definedNameRec.DescriptionText;
}
set { _definedNameRec.DescriptionText = value; }
}
//
/// <summary>
/// Sets the NameParsedFormula structure that specifies the formula for the defined name.
/// </summary>
/// <param name="ptgs">the sequence of {@link Ptg}s for the formula.</param>
public void SetNameDefinition(Ptg[] ptgs)
{
_definedNameRec.NameDefinition = (ptgs);
}
/// <summary>
/// Tests if this name points to a cell that no longer exists
/// </summary>
/// <value>
/// <c>true</c> if the name refers to a deleted cell; otherwise, <c>false</c>.
/// </value>
public bool IsDeleted
{
get
{
Ptg[] ptgs = _definedNameRec.NameDefinition;
return Ptg.DoesFormulaReferToDeletedCell(ptgs);
}
}
/// <summary>
/// Gets a value indicating whether this instance is function name.
/// </summary>
/// <value>
/// <c>true</c> if this instance is function name; otherwise, <c>false</c>.
/// </value>
public bool IsFunctionName
{
get
{
return _definedNameRec.IsFunctionName;
}
}
/**
* Indicates that the defined name refers to a user-defined function.
* This attribute is used when there is an add-in or other code project associated with the file.
*
* @param value <c>true</c> indicates the name refers to a function.
*/
public void SetFunction(bool value)
{
_definedNameRec.SetFunction(value);
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
sb.Append(_definedNameRec.NameText);
sb.Append("]");
return sb.ToString();
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
public partial class MainWindow
{
private global::Gtk.VBox vbox1;
private global::Gtk.EventBox eventboxHeader;
private global::Gtk.Label labelHeader;
private global::Gtk.HSeparator hseparator2;
private global::Gtk.Notebook notebook1;
private global::Gtk.Fixed fixed1;
private global::Gtk.Label labelPage1;
private global::Gtk.Label label12;
private global::Gtk.Label labelTab1;
private global::Gtk.Fixed fixed2;
private global::Gtk.Label labelPage2;
private global::Gtk.Label labelTab2;
private global::Gtk.Fixed fixed3;
private global::Gtk.Label labelPage3;
private global::Gtk.Label labelTab3;
private global::Gtk.Fixed fixed4;
private global::Gtk.Label labelPage4;
private global::Gtk.Label labelTab4;
private global::Gtk.Fixed fixed5;
private global::Gtk.Label labelPage5;
private global::Gtk.Label labelTab5;
private global::Gtk.HSeparator hseparator1;
private global::Gtk.HButtonBox hbuttonbox1;
private global::Gtk.Button buttonBack;
private global::Gtk.Button buttonNext;
private global::Gtk.Button buttonSkip;
private global::Gtk.Button buttonFinish;
private global::Gtk.Button buttonCancel;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget MainWindow
this.WidthRequest = 500;
this.HeightRequest = 400;
this.Name = "MainWindow";
this.Title = global::Mono.Unix.Catalog.GetString ("MainWindow");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child MainWindow.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
// Container child vbox1.Gtk.Box+BoxChild
this.eventboxHeader = new global::Gtk.EventBox ();
this.eventboxHeader.Name = "eventboxHeader";
// Container child eventboxHeader.Gtk.Container+ContainerChild
this.labelHeader = new global::Gtk.Label ();
this.labelHeader.Name = "labelHeader";
this.labelHeader.Xpad = 12;
this.labelHeader.Ypad = 12;
this.labelHeader.Xalign = 0F;
this.labelHeader.LabelProp = global::Mono.Unix.Catalog.GetString ("<span weight=\"bold\" size=\"xx-large\">Wizard Sample</span>");
this.labelHeader.UseMarkup = true;
this.eventboxHeader.Add (this.labelHeader);
this.vbox1.Add (this.eventboxHeader);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.eventboxHeader]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hseparator2 = new global::Gtk.HSeparator ();
this.hseparator2.Name = "hseparator2";
this.vbox1.Add (this.hseparator2);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hseparator2]));
w3.Position = 1;
w3.Expand = false;
w3.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.notebook1 = new global::Gtk.Notebook ();
this.notebook1.CanFocus = true;
this.notebook1.Name = "notebook1";
this.notebook1.CurrentPage = 0;
this.notebook1.ShowBorder = false;
this.notebook1.ShowTabs = false;
// Container child notebook1.Gtk.Notebook+NotebookChild
this.fixed1 = new global::Gtk.Fixed ();
this.fixed1.Name = "fixed1";
this.fixed1.HasWindow = false;
// Container child fixed1.Gtk.Fixed+FixedChild
this.labelPage1 = new global::Gtk.Label ();
this.labelPage1.Name = "labelPage1";
this.labelPage1.Xalign = 0F;
this.labelPage1.LabelProp = global::Mono.Unix.Catalog.GetString ("Page1");
this.fixed1.Add (this.labelPage1);
global::Gtk.Fixed.FixedChild w4 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.labelPage1]));
w4.X = 12;
w4.Y = 12;
// Container child fixed1.Gtk.Fixed+FixedChild
this.label12 = new global::Gtk.Label ();
this.label12.Name = "label12";
this.label12.LabelProp = global::Mono.Unix.Catalog.GetString ("Use Gtk.Notebook.ShowTabs to control tab display.");
this.fixed1.Add (this.label12);
global::Gtk.Fixed.FixedChild w5 = ((global::Gtk.Fixed.FixedChild)(this.fixed1 [this.label12]));
w5.X = 12;
w5.Y = 36;
this.notebook1.Add (this.fixed1);
// Notebook tab
this.labelTab1 = new global::Gtk.Label ();
this.labelTab1.Name = "labelTab1";
this.labelTab1.LabelProp = global::Mono.Unix.Catalog.GetString ("page1");
this.notebook1.SetTabLabel (this.fixed1, this.labelTab1);
this.labelTab1.ShowAll ();
// Container child notebook1.Gtk.Notebook+NotebookChild
this.fixed2 = new global::Gtk.Fixed ();
this.fixed2.Name = "fixed2";
this.fixed2.HasWindow = false;
// Container child fixed2.Gtk.Fixed+FixedChild
this.labelPage2 = new global::Gtk.Label ();
this.labelPage2.Name = "labelPage2";
this.labelPage2.LabelProp = global::Mono.Unix.Catalog.GetString ("Page2");
this.fixed2.Add (this.labelPage2);
global::Gtk.Fixed.FixedChild w7 = ((global::Gtk.Fixed.FixedChild)(this.fixed2 [this.labelPage2]));
w7.X = 12;
w7.Y = 12;
this.notebook1.Add (this.fixed2);
global::Gtk.Notebook.NotebookChild w8 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1 [this.fixed2]));
w8.Position = 1;
// Notebook tab
this.labelTab2 = new global::Gtk.Label ();
this.labelTab2.Name = "labelTab2";
this.labelTab2.LabelProp = global::Mono.Unix.Catalog.GetString ("page2");
this.notebook1.SetTabLabel (this.fixed2, this.labelTab2);
this.labelTab2.ShowAll ();
// Container child notebook1.Gtk.Notebook+NotebookChild
this.fixed3 = new global::Gtk.Fixed ();
this.fixed3.Name = "fixed3";
this.fixed3.HasWindow = false;
// Container child fixed3.Gtk.Fixed+FixedChild
this.labelPage3 = new global::Gtk.Label ();
this.labelPage3.Name = "labelPage3";
this.labelPage3.LabelProp = global::Mono.Unix.Catalog.GetString ("Page3");
this.fixed3.Add (this.labelPage3);
global::Gtk.Fixed.FixedChild w9 = ((global::Gtk.Fixed.FixedChild)(this.fixed3 [this.labelPage3]));
w9.X = 12;
w9.Y = 12;
this.notebook1.Add (this.fixed3);
global::Gtk.Notebook.NotebookChild w10 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1 [this.fixed3]));
w10.Position = 2;
// Notebook tab
this.labelTab3 = new global::Gtk.Label ();
this.labelTab3.Name = "labelTab3";
this.labelTab3.LabelProp = global::Mono.Unix.Catalog.GetString ("page3");
this.notebook1.SetTabLabel (this.fixed3, this.labelTab3);
this.labelTab3.ShowAll ();
// Container child notebook1.Gtk.Notebook+NotebookChild
this.fixed4 = new global::Gtk.Fixed ();
this.fixed4.Name = "fixed4";
this.fixed4.HasWindow = false;
// Container child fixed4.Gtk.Fixed+FixedChild
this.labelPage4 = new global::Gtk.Label ();
this.labelPage4.Name = "labelPage4";
this.labelPage4.LabelProp = global::Mono.Unix.Catalog.GetString ("Page4");
this.fixed4.Add (this.labelPage4);
global::Gtk.Fixed.FixedChild w11 = ((global::Gtk.Fixed.FixedChild)(this.fixed4 [this.labelPage4]));
w11.X = 12;
w11.Y = 12;
this.notebook1.Add (this.fixed4);
global::Gtk.Notebook.NotebookChild w12 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1 [this.fixed4]));
w12.Position = 3;
// Notebook tab
this.labelTab4 = new global::Gtk.Label ();
this.labelTab4.Name = "labelTab4";
this.labelTab4.LabelProp = global::Mono.Unix.Catalog.GetString ("page4");
this.notebook1.SetTabLabel (this.fixed4, this.labelTab4);
this.labelTab4.ShowAll ();
// Container child notebook1.Gtk.Notebook+NotebookChild
this.fixed5 = new global::Gtk.Fixed ();
this.fixed5.Name = "fixed5";
this.fixed5.HasWindow = false;
// Container child fixed5.Gtk.Fixed+FixedChild
this.labelPage5 = new global::Gtk.Label ();
this.labelPage5.Name = "labelPage5";
this.labelPage5.LabelProp = global::Mono.Unix.Catalog.GetString ("Page5");
this.fixed5.Add (this.labelPage5);
global::Gtk.Fixed.FixedChild w13 = ((global::Gtk.Fixed.FixedChild)(this.fixed5 [this.labelPage5]));
w13.X = 12;
w13.Y = 12;
this.notebook1.Add (this.fixed5);
global::Gtk.Notebook.NotebookChild w14 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1 [this.fixed5]));
w14.Position = 4;
// Notebook tab
this.labelTab5 = new global::Gtk.Label ();
this.labelTab5.Name = "labelTab5";
this.labelTab5.LabelProp = global::Mono.Unix.Catalog.GetString ("page5");
this.notebook1.SetTabLabel (this.fixed5, this.labelTab5);
this.labelTab5.ShowAll ();
this.vbox1.Add (this.notebook1);
global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.notebook1]));
w15.Position = 2;
// Container child vbox1.Gtk.Box+BoxChild
this.hseparator1 = new global::Gtk.HSeparator ();
this.hseparator1.Name = "hseparator1";
this.vbox1.Add (this.hseparator1);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hseparator1]));
w16.Position = 3;
w16.Expand = false;
w16.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbuttonbox1 = new global::Gtk.HButtonBox ();
this.hbuttonbox1.Name = "hbuttonbox1";
this.hbuttonbox1.Spacing = 5;
this.hbuttonbox1.BorderWidth = ((uint)(6));
this.hbuttonbox1.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4));
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.buttonBack = new global::Gtk.Button ();
this.buttonBack.CanFocus = true;
this.buttonBack.Name = "buttonBack";
this.buttonBack.UseUnderline = true;
this.buttonBack.Label = global::Mono.Unix.Catalog.GetString ("< Back");
this.hbuttonbox1.Add (this.buttonBack);
global::Gtk.ButtonBox.ButtonBoxChild w17 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.buttonBack]));
w17.Expand = false;
w17.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.buttonNext = new global::Gtk.Button ();
this.buttonNext.CanFocus = true;
this.buttonNext.Name = "buttonNext";
this.buttonNext.UseUnderline = true;
this.buttonNext.Label = global::Mono.Unix.Catalog.GetString ("Next >");
this.hbuttonbox1.Add (this.buttonNext);
global::Gtk.ButtonBox.ButtonBoxChild w18 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.buttonNext]));
w18.Position = 1;
w18.Expand = false;
w18.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.buttonSkip = new global::Gtk.Button ();
this.buttonSkip.CanFocus = true;
this.buttonSkip.Name = "buttonSkip";
this.buttonSkip.UseUnderline = true;
this.buttonSkip.Label = global::Mono.Unix.Catalog.GetString ("Skip >|");
this.hbuttonbox1.Add (this.buttonSkip);
global::Gtk.ButtonBox.ButtonBoxChild w19 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.buttonSkip]));
w19.Position = 2;
w19.Expand = false;
w19.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.buttonFinish = new global::Gtk.Button ();
this.buttonFinish.CanFocus = true;
this.buttonFinish.Name = "buttonFinish";
this.buttonFinish.UseUnderline = true;
this.buttonFinish.Label = global::Mono.Unix.Catalog.GetString ("Finish");
this.hbuttonbox1.Add (this.buttonFinish);
global::Gtk.ButtonBox.ButtonBoxChild w20 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.buttonFinish]));
w20.Position = 3;
w20.Expand = false;
w20.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.buttonCancel = new global::Gtk.Button ();
this.buttonCancel.CanFocus = true;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseUnderline = true;
this.buttonCancel.Label = global::Mono.Unix.Catalog.GetString ("Cancel");
this.hbuttonbox1.Add (this.buttonCancel);
global::Gtk.ButtonBox.ButtonBoxChild w21 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1 [this.buttonCancel]));
w21.Position = 4;
w21.Expand = false;
w21.Fill = false;
this.vbox1.Add (this.hbuttonbox1);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbuttonbox1]));
w22.Position = 4;
w22.Expand = false;
w22.Fill = false;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 500;
this.DefaultHeight = 400;
this.Show ();
this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent);
this.notebook1.SwitchPage += new global::Gtk.SwitchPageHandler (this.OnNotebook1SwitchPage);
this.buttonBack.Clicked += new global::System.EventHandler (this.OnButtonBackClicked);
this.buttonNext.Clicked += new global::System.EventHandler (this.OnButtonNextClicked);
this.buttonSkip.Clicked += new global::System.EventHandler (this.OnButtonSkipClicked);
this.buttonFinish.Clicked += new global::System.EventHandler (this.OnButtonFinishClicked);
this.buttonCancel.Clicked += new global::System.EventHandler (this.OnButtonCancelClicked);
}
}
| |
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
namespace Rhino.Etl.Core
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Reflection;
/// <summary>
/// Represent a virtual row
/// </summary>
[DebuggerDisplay("Count = {items.Count}")]
[DebuggerTypeProxy(typeof(QuackingDictionaryDebugView))]
[Serializable]
public class Row : QuackingDictionary, IEquatable<Row>
{
static readonly Dictionary<Type, List<PropertyInfo>> propertiesCache = new Dictionary<Type, List<PropertyInfo>>();
static readonly Dictionary<Type, List<FieldInfo>> fieldsCache = new Dictionary<Type, List<FieldInfo>>();
/// <summary>
/// Initializes a new instance of the <see cref="Row"/> class.
/// </summary>
/// <param name="comparer">Defines key equality</param>
public Row(StringComparer comparer)
: base(new Hashtable(), comparer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Row"/> class.
/// </summary>
public Row()
: base(new Hashtable())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Row"/> class.
/// </summary>
/// <param name="itemsToClone">The items to clone.</param>
/// <param name="comparer">Defines key equality</param>
protected Row(IDictionary itemsToClone, StringComparer comparer)
: base(itemsToClone, comparer)
{
}
/// <summary>
/// Creates a copy of the given source, erasing whatever is in the row currently.
/// </summary>
/// <param name="source">The source row.</param>
public void Copy(IDictionary source)
{
items = new Hashtable(source, Comparer);
}
/// <summary>
/// Gets the columns in this row.
/// </summary>
/// <value>The columns.</value>
public IEnumerable<string> Columns
{
get
{
//We likely would want to change the row when iterating on the columns, so we
//want to make sure that we send a copy, to avoid enumeration modified exception
foreach (string column in new ArrayList(items.Keys))
{
yield return column;
}
}
}
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public Row Clone()
{
Row row = new Row(this, Comparer);
return row;
}
/// <summary>
/// Indicates whether the current <see cref="Row" /> is equal to another <see cref="Row" />.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(Row other)
{
if (!Comparer.Equals(other.Comparer))
return false;
if(Columns.SequenceEqual(other.Columns, Comparer) == false)
return false;
foreach (var key in items.Keys)
{
var item = items[key];
var otherItem = other.items[key];
if (item == null | otherItem == null)
return item == null & otherItem == null;
var equalityComparer = CreateComparer(item.GetType(), otherItem.GetType());
if(equalityComparer(item, otherItem) == false)
return false;
}
return true;
}
private static Func<object, object, bool> CreateComparer(Type firstType, Type secondType)
{
if (firstType == secondType)
return Equals;
var firstParameter = Expression.Parameter(typeof (object), "first");
var secondParameter = Expression.Parameter(typeof (object), "second");
var equalExpression = Expression.Equal(Expression.Convert(firstParameter, firstType),
Expression.Convert(Expression.Convert(secondParameter, secondType), firstType));
return Expression.Lambda<Func<object, object, bool>>(equalExpression, firstParameter, secondParameter).Compile();
}
/// <summary>
/// Creates a key from the current row, suitable for use in hashtables
/// </summary>
public ObjectArrayKeys CreateKey()
{
return CreateKey(Columns.ToArray());
}
/// <summary>
/// Creates a key that allow to do full or partial indexing on a row
/// </summary>
/// <param name="columns">The columns.</param>
/// <returns></returns>
public ObjectArrayKeys CreateKey(params string[] columns)
{
object[] array = new object[columns.Length];
for (int i = 0; i < columns.Length; i++)
{
array[i] = items[columns[i]];
}
return new ObjectArrayKeys(array);
}
/// <summary>
/// Copy all the public properties and fields of an object to the row
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static Row FromObject(object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
Row row = new Row();
foreach (PropertyInfo property in GetProperties(obj))
{
row[property.Name] = property.GetValue(obj, new object[0]);
}
foreach (FieldInfo field in GetFields(obj))
{
row[field.Name] = field.GetValue(obj);
}
return row;
}
private static List<PropertyInfo> GetProperties(object obj)
{
List<PropertyInfo> properties;
if (propertiesCache.TryGetValue(obj.GetType(), out properties))
return properties;
properties = new List<PropertyInfo>();
foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
if (property.CanRead == false || property.GetIndexParameters().Length > 0)
continue;
properties.Add(property);
}
propertiesCache[obj.GetType()] = properties;
return properties;
}
private static List<FieldInfo> GetFields(object obj)
{
List<FieldInfo> fields;
if (fieldsCache.TryGetValue(obj.GetType(), out fields))
return fields;
fields = new List<FieldInfo>();
foreach (FieldInfo fieldInfo in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
if (Attribute.IsDefined(fieldInfo, typeof(CompilerGeneratedAttribute)) == false)
{
fields.Add(fieldInfo);
}
}
fieldsCache[obj.GetType()] = fields;
return fields;
}
/// <summary>
/// Generate a row from the reader
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns></returns>
public static Row FromReader(IDataReader reader)
{
Row row = new Row();
for (int i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = reader.GetValue(i);
}
return row;
}
/// <summary>
/// Create a new object of <typeparamref name="T"/> and set all
/// the matching fields/properties on it.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T ToObject<T>()
{
return (T)ToObject(typeof(T));
}
/// <summary>
/// Create a new object of <param name="type"/> and set all
/// the matching fields/properties on it.
/// </summary>
public object ToObject(Type type)
{
object instance = Activator.CreateInstance(type);
foreach (PropertyInfo info in GetProperties(instance))
{
if(items.Contains(info.Name) && info.CanWrite)
info.SetValue(instance, items[info.Name],null);
}
foreach (FieldInfo info in GetFields(instance))
{
if(items.Contains(info.Name))
info.SetValue(instance,items[info.Name]);
}
return instance;
}
}
}
| |
using System;
using System.Text;
using AzureFtpServer.Ftp;
using AzureFtpServer.Ftp.FileSystem;
using AzureFtpServer.Ftp.General;
using AzureFtpServer.General;
namespace AzureFtpServer.FtpCommands
{
/// <summary>
/// Base class for LIST/NLST command handlers
/// </summary>
internal abstract class ListCommandHandlerBase : FtpCommandHandler
{
public ListCommandHandlerBase(string sCommand, FtpConnectionObject connectionObject)
: base(sCommand, connectionObject)
{
}
protected override string OnProcess(string sMessage)
{
sMessage = sMessage.Trim();
string[] asFiles = null;
string[] asDirectories = null;
// Get the file/dir to list
string targetToList = GetPath(sMessage);
// checks the file/dir name
if (!FileNameHelpers.IsValid(targetToList))
{
return GetMessage(501, string.Format("\"{0}\" is not a valid file/directory name", sMessage));
}
// two vars indicating different list results
bool targetIsFile = false;
bool targetIsDir = false;
// targetToList ends with '/', must be a directory
if (targetToList.EndsWith(@"/"))
{
targetIsFile = false;
if (ConnectionObject.FileSystemObject.DirectoryExists(targetToList))
targetIsDir = true;
}
else
{
// check whether the target to list is a directory
if (ConnectionObject.FileSystemObject.DirectoryExists(FileNameHelpers.AppendDirTag(targetToList)))
targetIsDir = true;
// check whether the target to list is a file
if (ConnectionObject.FileSystemObject.FileExists(targetToList))
targetIsFile = true;
}
if (targetIsFile)
{
asFiles = new string[1] { targetToList };
if (targetIsDir)
asDirectories = new string[1] { FileNameHelpers.AppendDirTag(targetToList) };
}
// list a directory
else if (targetIsDir)
{
targetToList = FileNameHelpers.AppendDirTag(targetToList);
asFiles = ConnectionObject.FileSystemObject.GetFiles(targetToList);
asDirectories = ConnectionObject.FileSystemObject.GetDirectories(targetToList);
}
else
{
return GetMessage(550, string.Format("\"{0}\" not exists", sMessage));
}
var socketData = new FtpDataSocket(ConnectionObject);
if (!socketData.Loaded)
{
return GetMessage(425, "Unable to establish the data connection");
}
// prepare to write response to data channel
SocketHelpers.Send(ConnectionObject.Socket, string.Format("150 Opening data connection for {0}\r\n", Command), ConnectionObject.Encoding);
// generate the response
string sFileList = BuildReply(asFiles, asDirectories);
// ToDo, send response according to ConnectionObject.DataType, i.e., Ascii or Binary
socketData.Send(sFileList, Encoding.UTF8);
socketData.Close();
return GetMessage(226, string.Format("{0} successful.", Command));
}
protected abstract string BuildReply(string[] asFiles, string[] asDirectories);
// build short list reply, only list the file names
protected string BuildShortReply(string[] asFiles, string[] asDirectories)
{
var stringBuilder = new StringBuilder();
if (asFiles != null)
{
foreach (string filePath in asFiles)
{
stringBuilder.Append(string.Format("{0}\r\n", FileNameHelpers.GetFileName(filePath)));
}
}
if (asDirectories != null)
{
foreach (string dirPath in asDirectories)
{
stringBuilder.Append(string.Format("{0}\r\n", FileNameHelpers.GetDirectoryName(dirPath)));
}
}
return stringBuilder.ToString();
}
// build detailed list reply
protected string BuildLongReply(string[] asFiles, string[] asDirectories)
{
var stringBuilder = new StringBuilder();
if (asFiles != null)
{
foreach (string filePath in asFiles)
{
IFileInfo fileInfo = ConnectionObject.FileSystemObject.GetFileInfo(filePath);
stringBuilder.Append(GetLongProperty(fileInfo));
}
}
if (asDirectories != null)
{
foreach (string dirPath in asDirectories)
{
IFileInfo dirInfo = ConnectionObject.FileSystemObject.GetDirectoryInfo(dirPath);
stringBuilder.Append(GetLongProperty(dirInfo));
}
}
return stringBuilder.ToString();
}
private string GetLongProperty(IFileInfo info)
{
if (info == null)
return null;
var stringBuilder = new StringBuilder();
// permissions
string sAttributes = info.GetAttributeString();
stringBuilder.Append(sAttributes);
stringBuilder.Append(" 1 owner group");
// check whether info is directory
bool isDirectory = info.IsDirectory();
// size
string sFileSize = info.GetSize().ToString(); // if info is directory, the size will be 1
stringBuilder.Append(TextHelpers.RightAlignString(sFileSize, 13, ' '));
stringBuilder.Append(" ");
// modify time
DateTimeOffset fileDate = info.GetModifiedTime(); //if info is directory, the modify time will be the current time
// month
stringBuilder.Append(TextHelpers.Month(fileDate.Month));
stringBuilder.Append(" ");
// day
string sDay = fileDate.Day.ToString();
if (sDay.Length == 1)
stringBuilder.Append(" ");
stringBuilder.Append(sDay);
stringBuilder.Append(" ");
// year or hour:min
if (fileDate.Year < DateTime.Now.Year)
{
stringBuilder.Append(" " + fileDate.Year);
}
else
{
stringBuilder.Append(string.Format("{0:hh}:{1:mm}", fileDate, fileDate));
}
stringBuilder.Append(" ");
// filename
string path = info.Path();
if (isDirectory)
stringBuilder.Append(FileNameHelpers.GetDirectoryName(path));
else
stringBuilder.Append(FileNameHelpers.GetFileName(path));
// end
stringBuilder.Append("\r\n");
return stringBuilder.ToString();
}
}
}
| |
namespace Nancy.Tests.Unit.ModelBinding
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using FakeItEasy;
using Nancy.Configuration;
using Nancy.IO;
using Nancy.Json;
using Nancy.ModelBinding;
using Nancy.ModelBinding.DefaultBodyDeserializers;
using Nancy.ModelBinding.DefaultConverters;
using Nancy.Responses.Negotiation;
using Nancy.Tests.Fakes;
using Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers;
using Xunit;
public class DefaultBinderFixture
{
private readonly IFieldNameConverter passthroughNameConverter;
private readonly BindingDefaults emptyDefaults;
private readonly JavaScriptSerializer serializer;
private readonly BindingDefaults bindingDefaults;
public DefaultBinderFixture()
{
var environment = new DefaultNancyEnvironment();
environment.AddValue(JsonConfiguration.Default);
this.passthroughNameConverter = A.Fake<IFieldNameConverter>();
A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments()
.ReturnsLazily(f => (string)f.Arguments[0]);
this.serializer = new JavaScriptSerializer();
this.serializer.RegisterConverters(JsonConfiguration.Default.Converters);
this.bindingDefaults = new BindingDefaults(environment);
this.emptyDefaults = A.Fake<BindingDefaults>(options => options.WithArgumentsForConstructor(new[] { environment }));
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(ArrayCache.Empty<IBodyDeserializer>());
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(ArrayCache.Empty<ITypeConverter>());
}
[Fact]
public void Should_throw_if_type_converters_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(null, ArrayCache.Empty<IBodyDeserializer>(), A.Fake<IFieldNameConverter>(), this.bindingDefaults));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_body_deserializers_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), null, A.Fake<IFieldNameConverter>(), this.bindingDefaults));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_body_deserializer_fails_and_IgnoreErrors_is_false()
{
// Given
var deserializer = new ThrowingBodyDeserializer<FormatException>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
var config = new BindingConfig { IgnoreErrors = false };
// When
var result = Record.Exception(() => binder.Bind(context, this.GetType(), null, config));
// Then
result.ShouldBeOfType<ModelBindingException>();
result.InnerException.ShouldBeOfType<FormatException>();
}
[Fact]
public void Should_not_throw_if_body_deserializer_fails_and_IgnoreErrors_is_true()
{
// Given
var deserializer = new ThrowingBodyDeserializer<FormatException>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
var config = new BindingConfig { IgnoreErrors = true };
// When, Then
binder.Bind(context, this.GetType(), null, config);
}
[Fact]
public void Should_throw_if_field_name_converter_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), ArrayCache.Empty<IBodyDeserializer>(), null, this.bindingDefaults));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_defaults_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), ArrayCache.Empty<IBodyDeserializer>(), A.Fake<IFieldNameConverter>(), null));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_call_body_deserializer_if_one_matches()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_not_call_body_deserializer_if_doesnt_match()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(false);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void Should_pass_request_content_type_to_can_deserialize()
{
// Then
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>._))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_pass_binding_context_to_can_deserialize()
{
// Then
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>.That.Not.IsNull()))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned()
{
// Given
var modelObject = new TestModel { StringProperty = "Hello!" };
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringProperty.ShouldEqual("Hello!");
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned_and_overwrite_when_allowed()
{
// Given
var modelObject = new TestModel { StringPropertyWithDefaultValue = "Hello!" };
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Hello!");
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned_and_not_overwrite_when_not_allowed()
{
// Given
var modelObject =
new TestModel()
{
StringPropertyWithDefaultValue = "Hello!",
StringFieldWithDefaultValue = "World!",
};
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.NoOverwrite);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Default Property Value");
((TestModel)result).StringFieldWithDefaultValue.ShouldEqual("Default Field Value");
}
[Fact]
public void Should_see_if_a_type_converter_is_available_for_each_property_on_the_model_where_incoming_value_exists()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments().Returns(false);
var binder = this.GetBinder(typeConverters: new[] { typeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Times(2));
}
[Fact]
public void Should_call_convert_on_type_converter_if_available()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
var binder = this.GetBinder(typeConverters: new[] { typeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_ignore_properties_that_cannot_be_converted()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
context.Request.Form["DateProperty"] = "Broken";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
result.DateProperty.ShouldEqual(default(DateTime));
}
[Fact]
public void Should_throw_ModelBindingException_if_convertion_of_a_property_fails()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = "morebad";
// Then
Type modelType = typeof(TestModel);
Assert.Throws<ModelBindingException>(() => binder.Bind(context, modelType, null, BindingConfig.Default))
.ShouldMatch(exception =>
exception.BoundType == modelType
&& exception.PropertyBindingExceptions.Any(pe =>
pe.PropertyName == "IntProperty"
&& pe.AttemptedValue == "badint")
&& exception.PropertyBindingExceptions.Any(pe =>
pe.PropertyName == "AnotherIntProperty"
&& pe.AttemptedValue == "morebad")
&& exception.PropertyBindingExceptions.All(pe =>
pe.InnerException.Message.Contains(pe.AttemptedValue)
&& pe.InnerException.Message.Contains(modelType.GetProperty(pe.PropertyName).PropertyType.Name)));
}
[Fact]
public void Should_not_throw_ModelBindingException_if_convertion_of_property_fails_and_ignore_error_is_true()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = "morebad";
var config = new BindingConfig {IgnoreErrors = true};
// When
// Then
Record.Exception(() => binder.Bind(context, typeof(TestModel), null, config)).ShouldBeNull();
}
[Fact]
public void Should_set_remaining_properties_when_one_fails_and_ignore_error_is_enabled()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = 10;
var config = new BindingConfig { IgnoreErrors = true };
// When
var model = binder.Bind(context, typeof(TestModel), null, config) as TestModel;
// Then
model.AnotherIntProperty.ShouldEqual(10);
}
[Fact]
public void Should_ignore_indexer_properties()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
var validProperties = 0;
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>._, A<BindingContext>._)).Returns(true);
A.CallTo(() => deserializer.Deserialize(A<MediaRange>._, A<Stream>.Ignored, A<BindingContext>.Ignored))
.Invokes(f =>
{
validProperties = f.Arguments.Get<BindingContext>(2).ValidModelBindingMembers.Count();
})
.Returns(new TestModel());
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
validProperties.ShouldEqual(22);
}
[Fact]
public void Should_pass_binding_context_to_default_deserializer()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches("application/xml")), A<BindingContext>.That.Not.IsNull()))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_field_name_converter_for_each_field()
{
// Given
var binder = this.GetBinder();
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Times(2));
}
[Fact]
public void Should_not_bind_anything_on_blacklist()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default, "IntProperty");
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_not_bind_anything_on_blacklist_when_the_blacklist_is_specified_by_expressions()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
var fakeModule = A.Fake<INancyModule>();
var fakeModelBinderLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeModule.Context).Returns(context);
A.CallTo(() => fakeModule.ModelBinderLocator).Returns(fakeModelBinderLocator);
A.CallTo(() => fakeModelBinderLocator.GetBinderForType(typeof (TestModel), context)).Returns(binder);
// When
var result = fakeModule.Bind<TestModel>(tm => tm.IntProperty);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_use_default_body_deserializer_if_one_found()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_default_type_converter_if_one_found()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { typeConverter });
var binder = this.GetBinder(ArrayCache.Empty<ITypeConverter>());
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void User_body_serializer_should_take_precedence_over_default_one()
{
// Given
var userDeserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => userDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
var defaultDeserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => defaultDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { defaultDeserializer });
var binder = this.GetBinder(bodyDeserializers: new[] { userDeserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => userDeserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => defaultDeserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void User_type_converter_should_take_precedence_over_default_one()
{
// Given
var userTypeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => userTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
var defaultTypeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => defaultTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { defaultTypeConverter });
var binder = this.GetBinder(new[] { userTypeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void Should_bind_model_from_request()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "3";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Should_bind_inherited_model_from_request()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "3";
context.Request.Query["AnotherProperty"] = "Hello";
// When
var result = (InheritedTestModel)binder.Bind(context, typeof(InheritedTestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
result.AnotherProperty.ShouldEqual("Hello");
}
[Fact]
public void Should_bind_model_from_context_parameters()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test";
context.Parameters["IntProperty"] = "3";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Form_properties_should_take_precendence_over_request_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Query["StringProperty"] = "Test2";
context.Request.Query["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Should_bind_multiple_Form_properties_to_list()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["StringProperty_0"] = "Test";
context.Request.Form["IntProperty_0"] = "1";
context.Request.Form["StringProperty_1"] = "Test2";
context.Request.Form["IntProperty_1"] = "2";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.First().IntProperty.ShouldEqual(1);
result.Last().StringProperty.ShouldEqual("Test2");
result.Last().IntProperty.ShouldEqual(2);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_0"] = "1";
context.Request.Form["IntProperty_01"] = "2";
context.Request.Form["IntProperty_02"] = "3";
context.Request.Form["IntProperty_03"] = "4";
context.Request.Form["IntProperty_04"] = "5";
context.Request.Form["IntProperty_05"] = "6";
context.Request.Form["IntProperty_06"] = "7";
context.Request.Form["IntProperty_07"] = "8";
context.Request.Form["IntProperty_08"] = "9";
context.Request.Form["IntProperty_09"] = "10";
context.Request.Form["IntProperty_10"] = "11";
context.Request.Form["IntProperty_11"] = "12";
context.Request.Form["IntProperty_12"] = "13";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.ElementAt(1).IntProperty.ShouldEqual(2);
result.Last().IntProperty.ShouldEqual(13);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_should_work_with_padded_zeros()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_00"] = "1";
context.Request.Form["IntProperty_01"] = "2";
context.Request.Form["IntProperty_02"] = "3";
context.Request.Form["IntProperty_03"] = "4";
context.Request.Form["IntProperty_04"] = "5";
context.Request.Form["IntProperty_05"] = "6";
context.Request.Form["IntProperty_06"] = "7";
context.Request.Form["IntProperty_07"] = "8";
context.Request.Form["IntProperty_08"] = "9";
context.Request.Form["IntProperty_09"] = "10";
context.Request.Form["IntProperty_10"] = "11";
context.Request.Form["IntProperty_11"] = "12";
context.Request.Form["IntProperty_12"] = "13";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(13);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_counting_from_1()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_01"] = "1";
context.Request.Form["IntProperty_02"] = "2";
context.Request.Form["IntProperty_03"] = "3";
context.Request.Form["IntProperty_04"] = "4";
context.Request.Form["IntProperty_05"] = "5";
context.Request.Form["IntProperty_06"] = "6";
context.Request.Form["IntProperty_07"] = "7";
context.Request.Form["IntProperty_08"] = "8";
context.Request.Form["IntProperty_09"] = "9";
context.Request.Form["IntProperty_10"] = "10";
context.Request.Form["IntProperty_11"] = "11";
context.Request.Form["IntProperty_12"] = "12";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_be_able_to_bind_more_than_once_should_ignore_non_list_properties_when_binding_to_a_list()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Form["NestedIntProperty[0]"] = "1";
context.Request.Form["NestedIntField[0]"] = "2";
context.Request.Form["NestedStringProperty[0]"] = "one";
context.Request.Form["NestedStringField[0]"] = "two";
context.Request.Form["NestedIntProperty[1]"] = "3";
context.Request.Form["NestedIntField[1]"] = "4";
context.Request.Form["NestedStringProperty[1]"] = "three";
context.Request.Form["NestedStringField[1]"] = "four";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
var result2 = (List<AnotherTestModel>)binder.Bind(context, typeof(List<AnotherTestModel>), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
result2.ShouldHaveCount(2);
result2.First().NestedIntProperty.ShouldEqual(1);
result2.First().NestedIntField.ShouldEqual(2);
result2.First().NestedStringProperty.ShouldEqual("one");
result2.First().NestedStringField.ShouldEqual("two");
result2.Last().NestedIntProperty.ShouldEqual(3);
result2.Last().NestedIntField.ShouldEqual(4);
result2.Last().NestedStringProperty.ShouldEqual("three");
result2.Last().NestedStringField.ShouldEqual("four");
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_with_jagged_ids()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_01"] = "1";
context.Request.Form["IntProperty_04"] = "2";
context.Request.Form["IntProperty_05"] = "3";
context.Request.Form["IntProperty_06"] = "4";
context.Request.Form["IntProperty_09"] = "5";
context.Request.Form["IntProperty_11"] = "6";
context.Request.Form["IntProperty_57"] = "7";
context.Request.Form["IntProperty_199"] = "8";
context.Request.Form["IntProperty_1599"] = "9";
context.Request.Form["StringProperty_1599"] = "nine";
context.Request.Form["IntProperty_233"] = "10";
context.Request.Form["IntProperty_14"] = "11";
context.Request.Form["IntProperty_12"] = "12";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(9);
result.Last().StringProperty.ShouldEqual("nine");
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValuesProperty"] = "1,2,3,4";
context.Request.Form["IntValuesField"] = "5,6,7,8";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.IntValuesProperty.ShouldHaveCount(4);
result.IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.IntValuesField.ShouldHaveCount(4);
result.IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValuesProperty_0"] = "1,2,3,4";
context.Request.Form["IntValuesField_0"] = "5,6,7,8";
context.Request.Form["IntValuesProperty_1"] = "9,10,11,12";
context.Request.Form["IntValuesField_1"] = "13,14,15,16";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.ShouldHaveCount(2);
result.First().IntValuesProperty.ShouldHaveCount(4);
result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.First().IntValuesField.ShouldHaveCount(4);
result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
result.Last().IntValuesProperty.ShouldHaveCount(4);
result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });
result.Last().IntValuesField.ShouldHaveCount(4);
result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets_and_specifying_an_instance()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValuesProperty[0]"] = "1,2,3,4";
context.Request.Form["IntValuesField[0]"] = "5,6,7,8";
context.Request.Form["IntValuesProperty[1]"] = "9,10,11,12";
context.Request.Form["IntValuesField[1]"] = "13,14,15,16";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), new List<TestModel> { new TestModel {AnotherStringProperty = "Test"} }, new BindingConfig { Overwrite = false});
// Then
result.ShouldHaveCount(2);
result.First().AnotherStringProperty.ShouldEqual("Test");
result.First().IntValuesProperty.ShouldHaveCount(4);
result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.First().IntValuesField.ShouldHaveCount(4);
result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
result.Last().AnotherStringProperty.ShouldBeNull();
result.Last().IntValuesProperty.ShouldHaveCount(4);
result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });
result.Last().IntValuesField.ShouldHaveCount(4);
result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValuesProperty[0]"] = "1,2,3,4";
context.Request.Form["IntValuesField[0]"] = "5,6,7,8";
context.Request.Form["IntValuesProperty[1]"] = "9,10,11,12";
context.Request.Form["IntValuesField[1]"] = "13,14,15,16";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.ShouldHaveCount(2);
result.First().IntValuesProperty.ShouldHaveCount(4);
result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.First().IntValuesField.ShouldHaveCount(4);
result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
result.Last().IntValuesProperty.ShouldHaveCount(4);
result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });
result.Last().IntValuesField.ShouldHaveCount(4);
result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });
}
[Fact]
public void Should_bind_collections_regardless_of_case()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["lowercaseintproperty[0]"] = "1";
context.Request.Form["lowercaseintproperty[1]"] = "2";
context.Request.Form["lowercaseIntproperty[2]"] = "3";
context.Request.Form["lowercaseIntproperty[3]"] = "4";
context.Request.Form["Lowercaseintproperty[4]"] = "5";
context.Request.Form["Lowercaseintproperty[5]"] = "6";
context.Request.Form["LowercaseIntproperty[6]"] = "7";
context.Request.Form["LowercaseIntproperty[7]"] = "8";
context.Request.Form["lowercaseintfield[0]"] = "9";
context.Request.Form["lowercaseintfield[1]"] = "10";
context.Request.Form["lowercaseIntfield[2]"] = "11";
context.Request.Form["lowercaseIntfield[3]"] = "12";
context.Request.Form["Lowercaseintfield[4]"] = "13";
context.Request.Form["Lowercaseintfield[5]"] = "14";
context.Request.Form["LowercaseIntfield[6]"] = "15";
context.Request.Form["LowercaseIntfield[7]"] = "16";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.ShouldHaveCount(8);
result.First().lowercaseintproperty.ShouldEqual(1);
result.Last().lowercaseintproperty.ShouldEqual(8);
result.First().lowercaseintfield.ShouldEqual(9);
result.Last().lowercaseintfield.ShouldEqual(16);
}
[Fact]
public void Form_properties_should_take_precendence_over_request_properties_and_context_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Query["StringProperty"] = "Test2";
context.Request.Query["IntProperty"] = "1";
context.Parameters["StringProperty"] = "Test3";
context.Parameters["IntProperty"] = "2";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Request_properties_should_take_precendence_over_context_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "13";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_be_able_to_bind_from_form_and_request_simultaneously()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Theory]
[InlineData("de-DE", 4.50)]
[InlineData("en-GB", 450)]
[InlineData("en-US", 450)]
[InlineData("sv-SE", 4.50)]
[InlineData("ru-RU", 4.50)]
[InlineData("zh-TW", 450)]
public void Should_be_able_to_bind_culturally_aware_form_properties_if_numeric(string culture, double expected)
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Culture = new CultureInfo(culture);
context.Request.Form["DoubleProperty"] = "4,50";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.DoubleProperty.ShouldEqual(expected);
}
[Theory]
[InlineData("12/25/2012", 12, 25, 2012, "en-US")]
[InlineData("12/12/2012", 12, 12, 2012, "en-US")]
[InlineData("25/12/2012", 12, 25, 2012, "en-GB")]
[InlineData("12/12/2012", 12, 12, 2012, "en-GB")]
[InlineData("12/12/2012", 12, 12, 2012, "ru-RU")]
[InlineData("25/12/2012", 12, 25, 2012, "ru-RU")]
[InlineData("2012-12-25", 12, 25, 2012, "zh-TW")]
[InlineData("2012-12-12", 12, 12, 2012, "zh-TW")]
public void Should_be_able_to_bind_culturally_aware_form_properties_if_datetime(string date, int month, int day, int year, string culture)
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Culture = new CultureInfo(culture);
context.Request.Form["DateProperty"] = date;
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.DateProperty.Date.Month.ShouldEqual(month);
result.DateProperty.Date.Day.ShouldEqual(day);
result.DateProperty.Date.Year.ShouldEqual(year);
}
[Fact]
public void Should_be_able_to_bind_from_request_and_context_simultaneously()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Parameters["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_not_overwrite_nullable_property_if_already_set_and_overwriting_is_not_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { StringProperty = "Existing Value" };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite);
// Then
result.StringProperty.ShouldEqual("Existing Value");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_not_overwrite_non_nullable_property_if_already_set_and_overwriting_is_not_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { IntProperty = 27 };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(27);
}
[Fact]
public void Should_overwrite_nullable_property_if_already_set_and_overwriting_is_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { StringProperty = "Existing Value" };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test2");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Should_overwrite_non_nullable_property_if_already_set_and_overwriting_is_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { IntProperty = 27 };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test2");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Should_bind_list_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_array_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
// When
var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_string_array_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });
var body = serializer.Serialize(new[] { "Test","AnotherTest"});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (string[])binder.Bind(context, typeof(string[]), null, BindingConfig.Default);
// Then
result.First().ShouldEqual("Test");
result.Last().ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_ienumerable_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });
var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_ienumerable_model_with_instance_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });
var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
var then = DateTime.Now;
var instance = new List<TestModel> { new TestModel{ DateProperty = then }, new TestModel { IntProperty = 9, AnotherStringProperty = "Bananas" } };
// When
var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), instance, new BindingConfig{Overwrite = false});
// Then
result.First().StringProperty.ShouldEqual("Test");
result.First().DateProperty.ShouldEqual(then);
result.Last().StringProperty.ShouldEqual("AnotherTest");
result.Last().IntProperty.ShouldEqual(9);
result.Last().AnotherStringProperty.ShouldEqual("Bananas");
}
[Fact]
public void Should_bind_model_with_instance_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { StringProperty = "Test" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
var then = DateTime.Now;
var instance = new TestModel { DateProperty = then, IntProperty = 6, AnotherStringProperty = "Beers" };
// Wham
var result = (TestModel)binder.Bind(context, typeof(TestModel), instance, new BindingConfig { Overwrite = false });
// Then
result.StringProperty.ShouldEqual("Test");
result.DateProperty.ShouldEqual(then);
result.IntProperty.ShouldEqual(6);
result.AnotherStringProperty.ShouldEqual("Beers");
}
[Fact]
public void Should_bind_model_from_body_that_contains_an_array()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });
var body = serializer.Serialize(
new TestModel
{
StringProperty = "Test",
SomeStringsProperty = new[] { "E", "A", "D", "G", "B", "E" },
SomeStringsField = new[] { "G", "D", "A", "E" },
});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.SomeStringsProperty.ShouldHaveCount(6);
result.SomeStringsProperty.ShouldEqualSequence(new[] { "E", "A", "D", "G", "B", "E" });
result.SomeStringsField.ShouldHaveCount(4);
result.SomeStringsField.ShouldEqualSequence(new[] { "G", "D", "A", "E" });
}
[Fact]
public void Should_bind_array_model_from_body_that_contains_an_array()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });
var body =
serializer.Serialize(new[]
{
new TestModel()
{
StringProperty = "Test",
SomeStringsProperty = new[] {"E", "A", "D", "G", "B", "E"},
SomeStringsField = new[] { "G", "D", "A", "E" },
},
new TestModel()
{
StringProperty = "AnotherTest",
SomeStringsProperty = new[] {"E", "A", "D", "G", "B", "E"},
SomeStringsField = new[] { "G", "D", "A", "E" },
}
});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default, "SomeStringsProperty", "SomeStringsField");
// Then
result.ShouldHaveCount(2);
result.First().SomeStringsProperty.ShouldBeNull();
result.First().SomeStringsField.ShouldBeNull();
result.Last().SomeStringsProperty.ShouldBeNull();
result.Last().SomeStringsField.ShouldBeNull();
}
[Fact]
public void Form_request_and_context_properties_should_take_precedence_over_body_properties()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() };
var binder = this.GetBinder(typeConverters, bodyDeserializers);
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 0, StringProperty = "From body" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProperty"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("From form");
result.AnotherStringProperty.ShouldEqual("From context");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Form_request_and_context_properties_should_be_ignored_in_body_only_mode_when_there_is_a_body()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() };
var binder = GetBinder(typeConverters, bodyDeserializers);
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 2, StringProperty = "From body" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProperty"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true });
// Then
result.StringProperty.ShouldEqual("From body");
result.AnotherStringProperty.ShouldBeNull(); // not in body, so default value
result.IntProperty.ShouldEqual(2);
}
[Fact]
public void Form_request_and_context_properties_should_NOT_be_used_in_body_only_mode_if_there_is_no_body()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProperty"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true });
// Then
result.StringProperty.ShouldEqual(null);
result.AnotherStringProperty.ShouldEqual(null);
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_be_able_to_bind_body_request_form_and_context_properties()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { DateProperty = new DateTime(2012, 8, 16) });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["IntProperty"] = "0";
context.Request.Query["StringProperty"] = "From Query";
context.Parameters["AnotherStringProperty"] = "From Context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("From Query");
result.IntProperty.ShouldEqual(0);
result.DateProperty.ShouldEqual(new DateTime(2012, 8, 16));
result.AnotherStringProperty.ShouldEqual("From Context");
}
[Fact]
public void Should_ignore_existing_instance_if_type_doesnt_match()
{
//Given
var binder = this.GetBinder();
var existing = new object();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.ShouldNotBeSameAs(existing);
}
[Fact]
public void Should_bind_to_valuetype_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });
var body = serializer.Serialize(1);
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (int)binder.Bind(context, typeof(int), null, BindingConfig.Default);
// Then
result.ShouldEqual(1);
}
[Fact]
public void Should_bind_ienumerable_model__of_valuetype_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });
var body = serializer.Serialize(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (IEnumerable<int>)binder.Bind(context, typeof(IEnumerable<int>), null, BindingConfig.Default);
// Then
result.ShouldEqualSequence(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });
}
[Fact]
public void Should_bind_to_model_with_non_public_default_constructor()
{
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/json" });
context.Request.Form["IntProperty"] = "10";
var result = (TestModelWithHiddenDefaultConstructor)binder.Bind(context, typeof (TestModelWithHiddenDefaultConstructor), null, BindingConfig.Default);
result.ShouldNotBeNull();
result.IntProperty.ShouldEqual(10);
}
private IBinder GetBinder(IEnumerable<ITypeConverter> typeConverters = null, IEnumerable<IBodyDeserializer> bodyDeserializers = null, IFieldNameConverter nameConverter = null, BindingDefaults bindingDefaults = null)
{
var converters = typeConverters ?? new ITypeConverter[] { new DateTimeConverter(), new NumericConverter(), new FallbackConverter() };
var deserializers = bodyDeserializers ?? ArrayCache.Empty<IBodyDeserializer>();
var converter = nameConverter ?? this.passthroughNameConverter;
var defaults = bindingDefaults ?? this.emptyDefaults;
return new DefaultBinder(converters, deserializers, converter, defaults);
}
private static NancyContext CreateContextWithHeader(string name, IEnumerable<string> values)
{
var header = new Dictionary<string, IEnumerable<string>>
{
{ name, values }
};
return new NancyContext
{
Request = new FakeRequest("GET", "/", header),
Parameters = DynamicDictionary.Empty
};
}
private static NancyContext CreateContextWithHeaderAndBody(string name, IEnumerable<string> values, string body)
{
var header = new Dictionary<string, IEnumerable<string>>
{
{ name, values }
};
byte[] byteArray = Encoding.UTF8.GetBytes(body);
var bodyStream = RequestStream.FromStream(new MemoryStream(byteArray));
return new NancyContext
{
Request = new FakeRequest("GET", "/", header, bodyStream, "http", string.Empty),
Parameters = DynamicDictionary.Empty
};
}
private static INancyEnvironment GetTestingEnvironment()
{
var envionment =
new DefaultNancyEnvironment();
envionment.AddValue(JsonConfiguration.Default);
return envionment;
}
public class TestModel
{
public TestModel()
{
this.StringPropertyWithDefaultValue = "Default Property Value";
this.StringFieldWithDefaultValue = "Default Field Value";
}
public string StringProperty { get; set; }
public string AnotherStringProperty { get; set; }
public string StringField;
public string AnotherStringField;
public int IntProperty { get; set; }
public int AnotherIntProperty { get; set; }
public int IntField;
public int AnotherIntField;
public int lowercaseintproperty { get; set; }
public int lowercaseintfield;
public DateTime DateProperty { get; set; }
public DateTime DateField;
public string StringPropertyWithDefaultValue { get; set; }
public string StringFieldWithDefaultValue;
public double DoubleProperty { get; set; }
public double DoubleField;
[XmlIgnore]
public IEnumerable<int> IntValuesProperty { get; set; }
[XmlIgnore]
public IEnumerable<int> IntValuesField;
public string[] SomeStringsProperty { get; set; }
public string[] SomeStringsField;
public int this[int index]
{
get { return 0; }
set { }
}
public List<AnotherTestModel> ModelsProperty { get; set; }
public List<AnotherTestModel> ModelsField;
}
public class InheritedTestModel : TestModel
{
public string AnotherProperty { get; set; }
}
public class AnotherTestModel
{
public string NestedStringProperty { get; set; }
public int NestedIntProperty { get; set; }
public double NestedDoubleProperty { get; set; }
public string NestedStringField;
public int NestedIntField;
public double NestedDoubleField;
}
private class ThrowingBodyDeserializer<T> : IBodyDeserializer where T : Exception, new()
{
public bool CanDeserialize(MediaRange mediaRange, BindingContext context)
{
return true;
}
public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context)
{
throw new T();
}
}
public class TestModelWithHiddenDefaultConstructor
{
public int IntProperty { get; private set; }
private TestModelWithHiddenDefaultConstructor() { }
}
}
public class BindingConfigFixture
{
[Fact]
public void Should_allow_overwrite_on_new_instance()
{
// Given
// When
var instance = new BindingConfig();
// Then
instance.Overwrite.ShouldBeTrue();
}
}
}
| |
// 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 is used internally to create best fit behavior as per the original windows best fit behavior.
//
using System.Diagnostics;
using System.Threading;
namespace System.Text
{
internal sealed class InternalDecoderBestFitFallback : DecoderFallback
{
// Our variables
internal Encoding _encoding;
internal char[]? _arrayBestFit = null;
internal char _cReplacement = '?';
internal InternalDecoderBestFitFallback(Encoding encoding)
{
// Need to load our replacement characters table.
_encoding = encoding;
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new InternalDecoderBestFitFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 1;
}
}
public override bool Equals(object? value)
{
if (value is InternalDecoderBestFitFallback that)
{
return _encoding.CodePage == that._encoding.CodePage;
}
return false;
}
public override int GetHashCode()
{
return _encoding.CodePage;
}
}
internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer
{
// Our variables
private char _cBestFit = '\0';
private int _iCount = -1;
private int _iSize;
private InternalDecoderBestFitFallback _oFallback;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static object? s_InternalSyncObject;
private static object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange<object?>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback)
{
_oFallback = fallback;
if (_oFallback._arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// Double check before we do it again.
if (_oFallback._arrayBestFit == null)
_oFallback._arrayBestFit = fallback._encoding.GetBestFitBytesToUnicodeData();
}
}
}
// Fallback methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
Debug.Assert(_iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
_cBestFit = TryBestFit(bytesUnknown);
if (_cBestFit == '\0')
_cBestFit = _oFallback._cReplacement;
_iCount = _iSize = 1;
return true;
}
// Default version is overridden in DecoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_iCount == int.MaxValue)
{
_iCount = -1;
return '\0';
}
// Return the best fit character
return _cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (_iCount >= 0)
_iCount++;
// Return true if we could do it.
return (_iCount >= 0 && _iCount <= _iSize);
}
// How many characters left to output?
public override int Remaining
{
get
{
return (_iCount > 0) ? _iCount : 0;
}
}
// Clear the buffer
public override unsafe void Reset()
{
_iCount = -1;
byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// return our replacement string Length (always 1 for InternalDecoderBestFitFallback, either
// a best fit char or ?
return 1;
}
// private helper methods
private char TryBestFit(byte[] bytesCheck)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
Debug.Assert(_oFallback._arrayBestFit != null);
int highBound = _oFallback._arrayBestFit.Length;
int index;
char cCheck;
// Check trivial case first (no best fit)
if (highBound == 0)
return '\0';
// If our array is too small or too big we can't check
if (bytesCheck.Length == 0 || bytesCheck.Length > 2)
return '\0';
if (bytesCheck.Length == 1)
cCheck = unchecked((char)bytesCheck[0]);
else
cCheck = unchecked((char)((bytesCheck[0] << 8) + bytesCheck[1]));
// Check trivial out of range case
if (cCheck < _oFallback._arrayBestFit[0] || cCheck > _oFallback._arrayBestFit[highBound - 2])
return '\0';
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because it must be word aligned.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = _oFallback._arrayBestFit[index];
if (cTest == cCheck)
{
// We found it
Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback._arrayBestFit[index + 1];
}
else if (cTest < cCheck)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (_oFallback._arrayBestFit[index] == cCheck)
{
// We found it
Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback._arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// The superclass for all PDUs. This incorporates the PduHeader record, section 5.2.29.
/// </summary>
[Serializable]
[XmlRoot]
public partial class Pdu : PduBase, IPdu
{
/// <summary>
/// The version of the protocol. 5=DIS-1995, 6=DIS-1998.
/// </summary>
private byte _protocolVersion = 6;
/// <summary>
/// Exercise ID
/// </summary>
private byte _exerciseID;
/// <summary>
/// Type of pdu, unique for each PDU class
/// </summary>
private byte _pduType;
/// <summary>
/// value that refers to the protocol family, eg SimulationManagement, et
/// </summary>
private byte _protocolFamily;
/// <summary>
/// Timestamp value
/// </summary>
private uint _timestamp;
/// <summary>
/// Length, in bytes, of the PDU
/// </summary>
private ushort _length;
/// <summary>
/// zero-filled array of padding
/// </summary>
private short _padding;
/// <summary>
/// Initializes a new instance of the <see cref="Pdu"/> class.
/// </summary>
public Pdu()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(Pdu left, Pdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(Pdu left, Pdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 1; // this._protocolVersion
marshalSize += 1; // this._exerciseID
marshalSize += 1; // this._pduType
marshalSize += 1; // this._protocolFamily
marshalSize += 4; // this._timestamp
marshalSize += 2; // this._length
marshalSize += 2; // this._padding
return marshalSize;
}
/// <summary>
/// Gets or sets the The version of the protocol. 5=DIS-1995, 6=DIS-1998.
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "protocolVersion")]
public byte ProtocolVersion
{
get
{
return this._protocolVersion;
}
set
{
this._protocolVersion = value;
}
}
/// <summary>
/// Gets or sets the Exercise ID
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "exerciseID")]
public byte ExerciseID
{
get
{
return this._exerciseID;
}
set
{
this._exerciseID = value;
}
}
/// <summary>
/// Gets or sets the Type of pdu, unique for each PDU class
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "pduType")]
public byte PduType
{
get
{
return this._pduType;
}
set
{
this._pduType = value;
}
}
/// <summary>
/// Gets or sets the value that refers to the protocol family, eg SimulationManagement, et
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "protocolFamily")]
public byte ProtocolFamily
{
get
{
return this._protocolFamily;
}
set
{
this._protocolFamily = value;
}
}
/// <summary>
/// Gets or sets the Timestamp value
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "timestamp")]
public uint Timestamp
{
get
{
return this._timestamp;
}
set
{
this._timestamp = value;
}
}
/// <summary>
/// Gets or sets the Length, in bytes, of the PDU
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "length")]
public ushort Length
{
get
{
return this._length;
}
set
{
this._length = value;
}
}
/// <summary>
/// Gets or sets the zero-filled array of padding
/// </summary>
[XmlElement(Type = typeof(short), ElementName = "padding")]
public short Padding
{
get
{
return this._padding;
}
set
{
this._padding = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteUnsignedByte((byte)this._protocolVersion);
dos.WriteUnsignedByte((byte)this._exerciseID);
dos.WriteUnsignedByte((byte)this._pduType);
dos.WriteUnsignedByte((byte)this._protocolFamily);
dos.WriteUnsignedInt((uint)this._timestamp);
dos.WriteUnsignedShort((ushort)this._length);
dos.WriteShort((short)this._padding);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._protocolVersion = dis.ReadUnsignedByte();
this._exerciseID = dis.ReadUnsignedByte();
this._pduType = dis.ReadUnsignedByte();
this._protocolFamily = dis.ReadUnsignedByte();
this._timestamp = dis.ReadUnsignedInt();
this._length = dis.ReadUnsignedShort();
this._padding = dis.ReadShort();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<Pdu>");
try
{
sb.AppendLine("<protocolVersion type=\"byte\">" + this._protocolVersion.ToString(CultureInfo.InvariantCulture) + "</protocolVersion>");
sb.AppendLine("<exerciseID type=\"byte\">" + this._exerciseID.ToString(CultureInfo.InvariantCulture) + "</exerciseID>");
sb.AppendLine("<pduType type=\"byte\">" + this._pduType.ToString(CultureInfo.InvariantCulture) + "</pduType>");
sb.AppendLine("<protocolFamily type=\"byte\">" + this._protocolFamily.ToString(CultureInfo.InvariantCulture) + "</protocolFamily>");
sb.AppendLine("<timestamp type=\"uint\">" + this._timestamp.ToString(CultureInfo.InvariantCulture) + "</timestamp>");
sb.AppendLine("<length type=\"ushort\">" + this._length.ToString(CultureInfo.InvariantCulture) + "</length>");
sb.AppendLine("<padding type=\"short\">" + this._padding.ToString(CultureInfo.InvariantCulture) + "</padding>");
sb.AppendLine("</Pdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as Pdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Pdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._protocolVersion != obj._protocolVersion)
{
ivarsEqual = false;
}
if (this._exerciseID != obj._exerciseID)
{
ivarsEqual = false;
}
if (this._pduType != obj._pduType)
{
ivarsEqual = false;
}
if (this._protocolFamily != obj._protocolFamily)
{
ivarsEqual = false;
}
if (this._timestamp != obj._timestamp)
{
ivarsEqual = false;
}
if (this._length != obj._length)
{
ivarsEqual = false;
}
if (this._padding != obj._padding)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._protocolVersion.GetHashCode();
result = GenerateHash(result) ^ this._exerciseID.GetHashCode();
result = GenerateHash(result) ^ this._pduType.GetHashCode();
result = GenerateHash(result) ^ this._protocolFamily.GetHashCode();
result = GenerateHash(result) ^ this._timestamp.GetHashCode();
result = GenerateHash(result) ^ this._length.GetHashCode();
result = GenerateHash(result) ^ this._padding.GetHashCode();
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
[Serializable]
internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
{
#region FCalls
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags);
#endregion
#region Private Data Members
// agressive caching
private IntPtr m_fieldHandle;
private FieldAttributes m_fieldAttributes;
// lazy caching
private string m_name;
private RuntimeType m_fieldType;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
Type declaringType = DeclaringType;
bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType);
INVOCATION_FLAGS invocationFlags = 0;
// first take care of all the NO_INVOKE cases
if (
(declaringType != null && declaringType.ContainsGenericParameters) ||
(declaringType == null && Module.Assembly.ReflectionOnly) ||
(fIsReflectionOnlyType)
)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
// If the invocationFlags are still 0, then
// this should be an usable field, determine the other flags
if (invocationFlags == 0)
{
if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
// A public field is inaccesible to Transparent code if the field is Critical.
bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical;
bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck);
if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
// find out if the field type is one of the following: Primitive, Enum or Pointer
Type fieldType = FieldType;
if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST;
}
// must be last to avoid threading problems
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
#region Constructor
internal RtFieldInfo(
RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringType, bindingFlags)
{
m_fieldHandle = handle.Value;
m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle);
}
#endregion
#region Private Members
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
get
{
return new RuntimeFieldHandleInternal(m_fieldHandle);
}
}
#endregion
#region Internal Members
internal void CheckConsistency(Object target)
{
// only test instance fields
if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
{
throw new TargetException(SR.RFLCT_Targ_StatFldReqTarg);
}
else
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, SR.Arg_FieldDeclTarget,
Name, m_declaringType, target.GetType()));
}
}
}
}
internal override bool CacheEquals(object o)
{
RtFieldInfo m = o as RtFieldInfo;
if ((object)m == null)
return false;
return m.m_fieldHandle == m_fieldHandle;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && declaringType.ContainsGenericParameters)
throw new InvalidOperationException(SR.Arg_UnboundGenField);
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.Arg_ReflectionOnlyField);
throw new FieldAccessException();
}
CheckConsistency(obj);
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
#region Security Check
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags);
#endregion
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
// UnsafeSetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalSetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && DeclaringType.ContainsGenericParameters)
throw new InvalidOperationException(SR.Arg_UnboundGenField);
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.Arg_ReflectionOnlyField);
throw new FieldAccessException();
}
CheckConsistency(obj);
RuntimeType fieldType = (RuntimeType)FieldType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD));
return UnsafeGetValue(obj);
}
// UnsafeGetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalGetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object UnsafeGetValue(Object obj)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
bool domainInitialized = false;
if (declaringType == null)
{
return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
return retVal;
}
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
if (m_name == null)
m_name = RuntimeFieldHandle.GetName(this);
return m_name;
}
}
internal String FullName
{
get
{
return String.Format("{0}.{1}", DeclaringType.FullName, Name);
}
}
public override int MetadataToken
{
get { return RuntimeFieldHandle.GetToken(this); }
}
internal override RuntimeModule GetRuntimeModule()
{
return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
}
#endregion
#region FieldInfo Overrides
public override Object GetValue(Object obj)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetValue(obj, ref stackMark);
}
public override object GetRawConstantValue() { throw new InvalidOperationException(); }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
if (obj.IsNull)
throw new ArgumentException(SR.Arg_TypedReference_Null);
Contract.EndContractBlock();
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj, Object value)
{
if (obj.IsNull)
throw new ArgumentException(SR.Arg_TypedReference_Null);
Contract.EndContractBlock();
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
}
}
public override RuntimeFieldHandle FieldHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
return new RuntimeFieldHandle(this);
}
}
internal IntPtr GetFieldHandle()
{
return m_fieldHandle;
}
public override FieldAttributes Attributes
{
get
{
return m_fieldAttributes;
}
}
public override Type FieldType
{
get
{
if (m_fieldType == null)
m_fieldType = new Signature(this, m_declaringType).FieldType;
return m_fieldType;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using ccl.ShaderNodes.Sockets;
using Rhino.Geometry.Collections;
namespace RhinoCyclesCore.ExtensionMethods
{
public static class NumericExtensions
{
public static bool FuzzyEquals(this double orig, double test)
{
var rc = false;
rc = Math.Abs(orig - test) < 0.000001;
return rc;
}
public static bool FuzzyEquals(this float orig, float test)
{
var rc = false;
rc = Math.Abs(orig - test) < 0.000001;
return rc;
}
}
public static class SizeExtensions
{
public static void Deconstruct(this Size size, out int x, out int y)
{
x = size.Width;
y = size.Height;
}
}
public static class MeshVertexColorListExtensions
{
/// <summary>
/// Copies all vertex colors to a linear array of float in rgb order
/// </summary>
/// <returns>The float array.</returns>
public static float[] ToFloatArray(this MeshVertexColorList cl)
{
int count = cl.Count;
var rc = new float[count * 3];
int index = 0;
foreach (var c in cl)
{
Rhino.Display.Color4f c4f = new Rhino.Display.Color4f(c);
rc[index++] = c4f.R;
rc[index++] = c4f.G;
rc[index++] = c4f.B;
}
return rc;
}
/// <summary>
/// Copies all vertex colors to a linear array of float in rgb order
/// if cl.Count==count
/// </summary>
/// <returns>The float array, or null if cl.Count!=count</returns>
public static float[] ToFloatArray(this MeshVertexColorList cl, int count)
{
if (count != cl.Count) return null;
return cl.ToFloatArray();
}
}
public static class ISocketExtenions
{
public static List<ISocket> ToList(this ISocket sock)
{
List<ISocket> lst = new List<ISocket> {
sock
};
return lst;
}
}
public static class DisplayColor4fExtensions
{
public static void ToArray(this Rhino.Display.Color4f cl, ref byte[] conv)
{
conv[0] = (byte)(Math.Min(cl.R, 1.0f) * 255.0f);
conv[1] = (byte)(Math.Min(cl.G, 1.0f) * 255.0f);
conv[2] = (byte)(Math.Min(cl.B, 1.0f) * 255.0f);
conv[3] = (byte)(Math.Min(cl.A, 1.0f) * 255.0f);
}
public static void ToArray(this Rhino.Display.Color4f cl, ref float[] conv)
{
conv[0] = cl.R;
conv[1] = cl.G;
conv[2] = cl.B;
conv[3] = cl.A;
}
public static T[] ToArray<T>(this Rhino.Display.Color4f cl)
{
var conv = new T[4];
if (typeof(T) == typeof(float))
{
conv[0] = (T)((object)(cl.R));
conv[1] = (T)((object)(cl.G));
conv[2] = (T)((object)(cl.B));
conv[3] = (T)((object)(cl.A));
}
else
{
conv[0] = (T)Convert.ChangeType((byte)(Math.Min(cl.R, 1.0f) * 255.0f), typeof(T));
conv[1] = (T)Convert.ChangeType((byte)(Math.Min(cl.G, 1.0f) * 255.0f), typeof(T));
conv[2] = (T)Convert.ChangeType((byte)(Math.Min(cl.B, 1.0f) * 255.0f), typeof(T));
conv[3] = (T)Convert.ChangeType((byte)(Math.Min(cl.A, 1.0f) * 255.0f), typeof(T));
//conv[0] = (T)((object)((byte)Math.Min(cl.R, 1.0f) * 255.0f));
//conv[1] = (T)((object)((byte)Math.Min(cl.G, 1.0f) * 255.0f));
//conv[2] = (T)((object)((byte)Math.Min(cl.B, 1.0f) * 255.0f));
//conv[3] = (T)((object)((byte)Math.Min(cl.A, 1.0f) * 255.0f));
}
return conv;
}
public static float LargestComponent(this Rhino.Display.Color4f cl)
{
if (cl.R > cl.G && cl.R > cl.B) return cl.R;
if (cl.G > cl.R && cl.G > cl.B) return cl.G;
return cl.B;
}
public static ccl.float4 ToFloat4(this Rhino.Display.Color4f cl)
{
return RenderEngine.CreateFloat4(cl.R, cl.G, cl.B);
}
public static Rhino.Display.Color4f ToColor4f(this ccl.float4 cl)
{
return new Rhino.Display.Color4f(cl.x, cl.y, cl.z, cl.w);
}
/// <summary>
/// Apply gamma
/// </summary>
/// <param name="cl">Color whose components to raise to the power of</param>
/// <param name="gamma">power to raise to</param>
/// <returns>Color with components raised to the power of gamma</returns>
public static Rhino.Display.Color4f ApplyGamma(this Rhino.Display.Color4f cl, float gamma) {
if (Math.Abs(1.0f - gamma) > float.Epsilon)
{
return new Rhino.Display.Color4f((float) Math.Pow(cl.R, gamma), (float) Math.Pow(cl.G, gamma), (float) Math.Pow(cl.B, gamma), cl.A);
}
return cl;
}
}
public static class Point3dExtensions
{
/// <summary>
/// Get a ccl.float4 representation from a Point3d. The w property will
/// be set to 0
/// </summary>
/// <param name="point">The Point3d to cast</param>
/// <returns>ccl.float4</returns>
public static ccl.float4 ToFloat4(this Rhino.Geometry.Point3d point)
{
var f = new ccl.float4((float)point.X, (float)point.Y, (float)point.Z);
return f;
}
}
public static class Vector3dExtensions
{
/// <summary>
/// Get a ccl.float4 representation from a Vector3d. The w property will
/// be set to 0
/// </summary>
/// <param name="vector">The Vector3d to cast</param>
/// <returns>ccl.float4</returns>
public static ccl.float4 ToFloat4(this Rhino.Geometry.Vector3d vector)
{
var f = new ccl.float4((float)vector.X, (float)vector.Y, (float)vector.Z);
return f;
}
}
public static class CclTransformExtensions
{
public static float[] ToFloatArray(this ccl.Transform t)
{
var f = new float[12];
f[0] = t.x.x;
f[1] = t.x.y;
f[2] = t.x.z;
f[3] = t.x.w;
f[4] = t.y.x;
f[5] = t.y.y;
f[6] = t.y.z;
f[7] = t.y.w;
f[8] = t.z.x;
f[9] = t.z.y;
f[10] = t.z.z;
f[11] = t.z.w;
return f;
}
public static Rhino.Geometry.Transform ToRhinoTransform(this ccl.Transform t)
{
Rhino.Geometry.Transform rt = new Rhino.Geometry.Transform();
rt.M00 = t.x.x;
rt.M01 = t.x.y;
rt.M02 = t.x.z;
rt.M03 = t.x.w;
rt.M10 = t.y.x;
rt.M11 = t.y.y;
rt.M12 = t.y.z;
rt.M13 = t.y.w;
rt.M20 = t.z.x;
rt.M21 = t.z.y;
rt.M22 = t.z.z;
rt.M23 = t.z.w;
rt.M30 = 0.0f;
rt.M31 = 0.0f;
rt.M32 = 0.0f;
rt.M33 = 0.0f;
return rt;
}
/// <summary>
/// Convert a Rhino.Geometry.Transform to ccl.Transform
/// </summary>
/// <param name="rt">Rhino.Geometry.Transform</param>
/// <returns>ccl.Transform</returns>
public static ccl.Transform ToCyclesTransform(this Rhino.Geometry.Transform rt)
{
var t = new ccl.Transform(
(float) rt.M00, (float) rt.M01, (float) rt.M02, (float) rt.M03,
(float) rt.M10, (float) rt.M11, (float) rt.M12, (float) rt.M13,
(float) rt.M20, (float) rt.M21, (float) rt.M22, (float) rt.M23
);
return t;
}
/// <summary>
/// Calculate the CRC for the transform using the given remainder.
/// </summary>
public static uint TransformCrc(this Rhino.Geometry.Transform rt, uint remainder)
{
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M00);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M01);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M02);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M03);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M10);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M11);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M12);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M13);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M20);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M21);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M22);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M23);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M30);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M31);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M32);
remainder = Rhino.RhinoMath.CRC32(remainder, rt.M33);
return remainder;
}
/// <summary>
/// Extract scale vector from ccl.Transform
/// </summary>
/// <param name="t">ccl.Transform to extract scale vector from</param>
/// <returns>ccl.float4 that is the scale vector for this transform</returns>
public static ccl.float4 ScaleVector(this ccl.Transform t)
{
ccl.float4 sx = new ccl.float4(t.x.x,t.y.x,t.z.x);
ccl.float4 sy = new ccl.float4(t.x.y,t.y.y,t.z.y);
ccl.float4 sz = new ccl.float4(t.x.z,t.y.z,t.z.z);
return new ccl.float4(sx.Length(), sy.Length(), sz.Length());
}
/// <summary>
/// Extract translate vector from ccl.Transform
/// </summary>
/// <param name="t">ccl.Transform to extract translate vector from</param>
/// <returns>ccl.float4 that is the translate vector for this transform</returns>
public static ccl.float4 TranslateVector(this ccl.Transform t)
{
return new ccl.float4(t.x.w, t.y.w, t.z.w);
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Registrasi_RIList : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRegistrasiRI";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["RegistrasiRI"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
else
{
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + "Pasien Rujukan";
btnOld.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + "Pasien Rawat Jalan";
}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
GetListKelas();
UpdateDataView(true);
}
}
public void GetListKelas()
{
string KelasId = "";
if (Request.QueryString["KelasId"] != null)
KelasId = Request.QueryString["KelasId"].ToString();
SIMRS.DataAccess.RS_Kelas myObj = new SIMRS.DataAccess.RS_Kelas();
DataTable dt = myObj.GetList();
cmbKelas.Items.Clear();
int i = 0;
cmbKelas.Items.Add("");
cmbKelas.Items[i].Text = "";
cmbKelas.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelas.Items.Add("");
cmbKelas.Items[i].Text = dr["Nama"].ToString();
cmbKelas.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == KelasId)
{
cmbKelas.SelectedIndex = i;
}
i++;
}
GetListRuang();
}
public void GetListRuang()
{
string RuangId = "";
if (Request.QueryString["RuangId"] != null)
RuangId = Request.QueryString["RuangId"].ToString();
int kelasId = 0;
if (cmbKelas.SelectedIndex > 0)
kelasId = int.Parse(cmbKelas.SelectedItem.Value);
SIMRS.DataAccess.RS_Ruang myObj = new SIMRS.DataAccess.RS_Ruang();
DataTable dt = myObj.GetListByKelasId(kelasId);
cmbRuang.Items.Clear();
int i = 0;
cmbRuang.Items.Add("");
cmbRuang.Items[i].Text = "";
cmbRuang.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbRuang.Items.Add("");
cmbRuang.Items[i].Text = dr["Nama"].ToString();
cmbRuang.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == RuangId)
{
cmbRuang.SelectedIndex = i;
}
i++;
}
GetListNomorRuang();
}
public void GetListNomorRuang()
{
string NomorRuang = "";
if (Request.QueryString["NomorRuang"] != null)
NomorRuang = Request.QueryString["NomorRuang"].ToString();
SIMRS.DataAccess.RS_RuangRawat myObj = new SIMRS.DataAccess.RS_RuangRawat();
if (cmbKelas.SelectedIndex > 0)
myObj.KelasId = int.Parse(cmbKelas.SelectedItem.Value);
if (cmbRuang.SelectedIndex > 0)
myObj.RuangId = int.Parse(cmbRuang.SelectedItem.Value);
DataTable dt = myObj.GetListNomorRuang();
cmbNoRuang.Items.Clear();
int i = 0;
cmbNoRuang.Items.Add("");
cmbNoRuang.Items[i].Text = "";
cmbNoRuang.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbNoRuang.Items.Add("");
cmbNoRuang.Items[i].Text = dr["NomorRuang"].ToString();
cmbNoRuang.Items[i].Value = dr["NomorRuang"].ToString();
if (dr["NomorRuang"].ToString() == NomorRuang)
{
cmbNoRuang.SelectedIndex = i;
}
i++;
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
DataTable myData = new DataTable();
SIMRS.DataAccess.RS_RawatInap myObj = new SIMRS.DataAccess.RS_RawatInap();
int KelasId = 0;
if (cmbKelas.SelectedIndex > 0 )
{
KelasId = int.Parse(cmbKelas.SelectedItem.Value);
}
int RuangId = 0;
if (cmbRuang.SelectedIndex > 0)
{
RuangId = int.Parse(cmbRuang.SelectedItem.Value);
}
string NomorRuang = "";
if (cmbNoRuang.Items.Count > 0 )
{
NomorRuang = cmbNoRuang.SelectedItem.Value;
}
myData = myObj.SelectAllFilter(KelasId, RuangId, NomorRuang);
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("RIAddRujukan.aspx?CurrentPage=" + CurrentPage);
}
public void OnOldRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("RIAddRJ.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama")
dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRegistrasi")
dv.RowFilter = " NoRegistrasi LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRM")
dv.RowFilter = " NoRM LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NRP")
dv.RowFilter = " NRP LIKE '%" + txtSearch.Text + "%'";
else
dv.RowFilter = "";
BindData(dv);
}
#endregion
#region .Update Link Item Butom
/// <summary>
/// The function is responsible for get link button form.
/// </summary>
/// <param name="szId"></param>
/// <param name="CurrentPage"></param>
/// <returns></returns>
public string GetLinkButton(string RawatInapId, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["RegistrasiRI"] != null)
{
szResult += "<a class=\"toolbar\" href=\"RIView.aspx?CurrentPage=" + CurrentPage + "&RawatInapId=" + RawatInapId + "\" ";
szResult += ">" + Resources.GetString("", "View") + "</a>";
}
return szResult;
}
public bool GetLinkDelete(string StatusRawatInap)
{
bool szResult = false;
if (Session["RegistrasiRI"] != null && StatusRawatInap == "0")
{
szResult = true;
}
return szResult;
}
#endregion
protected void cmbKelas_SelectedIndexChanged(object sender, EventArgs e)
{
GetListRuang();
UpdateDataView(true);
}
protected void cmbRuang_SelectedIndexChanged(object sender, EventArgs e)
{
GetListNomorRuang();
UpdateDataView(true);
}
protected void cmbNoRuang_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateDataView(true);
}
protected void DataGridList_DeleteCommand(object source, DataGridCommandEventArgs e)
{
string RawatInapId = DataGridList.DataKeys[e.Item.ItemIndex].ToString();
SIMRS.DataAccess.RS_RawatInap myObj = new SIMRS.DataAccess.RS_RawatInap();
myObj.RawatInapId = int.Parse(RawatInapId);
myObj.Delete();
DataGridList.SelectedIndex = -1;
UpdateDataView(true);
}
}
| |
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Web;
namespace RedditSharp
{
public class WebAgent : IWebAgent
{
/// <summary>
/// Additional values to append to the default RedditSharp user agent.
/// </summary>
public static string UserAgent { get; set; }
/// <summary>
/// It is strongly advised that you leave this enabled. Reddit bans excessive
/// requests with extreme predjudice.
/// </summary>
public static bool EnableRateLimit { get; set; }
public static string Protocol { get; set; }
/// <summary>
/// It is strongly advised that you leave this set to Burst or Pace. Reddit bans excessive
/// requests with extreme predjudice.
/// </summary>
public static RateLimitMode RateLimit { get; set; }
/// <summary>
/// The method by which the WebAgent will limit request rate
/// </summary>
public enum RateLimitMode
{
/// <summary>
/// Limits requests to one every two seconds (one if OAuth)
/// </summary>
Pace,
/// <summary>
/// Restricts requests to five per ten seconds (ten if OAuth)
/// </summary>
SmallBurst,
/// <summary>
/// Restricts requests to thirty per minute (sixty if OAuth)
/// </summary>
Burst,
/// <summary>
/// Does not restrict request rate. ***NOT RECOMMENDED***
/// </summary>
None
}
/// <summary>
/// The root domain RedditSharp uses to address Reddit.
/// www.reddit.com by default
/// </summary>
public static string RootDomain { get; set; }
/// <summary>
/// Used to make calls against Reddit's API using OAuth2
/// </summary>
public string AccessToken { get; set; }
public CookieContainer Cookies { get; set; }
public string AuthCookie { get; set; }
private static DateTime _lastRequest;
private static DateTime _burstStart;
private static int _requestsThisBurst;
/// <summary>
/// UTC DateTime of last request made to Reddit API
/// </summary>
public DateTime LastRequest
{
get { return _lastRequest; }
}
/// <summary>
/// UTC DateTime of when the last burst started
/// </summary>
public DateTime BurstStart
{
get { return _burstStart; }
}
/// <summary>
/// Number of requests made during the current burst
/// </summary>
public int RequestsThisBurst
{
get { return _requestsThisBurst; }
}
static WebAgent()
{
UserAgent = "";
RateLimit = RateLimitMode.Pace;
Protocol = "https";
RootDomain = "www.reddit.com";
}
public virtual JToken CreateAndExecuteRequest(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
{
if (!Uri.TryCreate(string.Format("{0}://{1}{2}", Protocol, RootDomain, url), UriKind.Absolute, out uri))
throw new Exception("Could not parse Uri");
}
var request = CreateGet(uri);
try { return ExecuteRequest(request); }
catch (Exception)
{
var tempProtocol = Protocol;
var tempRootDomain = RootDomain;
Protocol = "http";
RootDomain = "www.reddit.com";
var retval = CreateAndExecuteRequest(url);
Protocol = tempProtocol;
RootDomain = tempRootDomain;
return retval;
}
}
/// <summary>
/// Executes the web request and handles errors in the response
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual JToken ExecuteRequest(HttpWebRequest request)
{
EnforceRateLimit();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var result = GetResponseString(response.GetResponseStream());
JToken json;
if (!string.IsNullOrEmpty(result))
{
json = JToken.Parse(result);
try
{
if (json["json"] != null)
{
json = json["json"]; //get json object if there is a root node
}
if (json["error"] != null)
{
switch (json["error"].ToString())
{
case "404":
throw new Exception("File Not Found");
case "403":
throw new Exception("Restricted");
case "invalid_grant":
//Refresh authtoken
//AccessToken = authProvider.GetRefreshToken();
//ExecuteRequest(request);
break;
}
}
}
catch
{
}
}
else
{
json = JToken.Parse("{'method':'" + response.Method + "','uri':'" + response.ResponseUri.AbsoluteUri + "','status':'" + response.StatusCode.ToString() + "'}");
}
return json;
}
[MethodImpl(MethodImplOptions.Synchronized)]
protected virtual void EnforceRateLimit()
{
var limitRequestsPerMinute = IsOAuth() ? 60.0 : 30.0;
switch (RateLimit)
{
case RateLimitMode.Pace:
while ((DateTime.UtcNow - _lastRequest).TotalSeconds < 60.0 / limitRequestsPerMinute)// Rate limiting
Thread.Sleep(250);
_lastRequest = DateTime.UtcNow;
break;
case RateLimitMode.SmallBurst:
if (_requestsThisBurst == 0 || (DateTime.UtcNow - _burstStart).TotalSeconds >= 10) //this is first request OR the burst expired
{
_burstStart = DateTime.UtcNow;
_requestsThisBurst = 0;
}
if (_requestsThisBurst >= limitRequestsPerMinute / 6.0) //limit has been reached
{
while ((DateTime.UtcNow - _burstStart).TotalSeconds < 10)
Thread.Sleep(250);
_burstStart = DateTime.UtcNow;
_requestsThisBurst = 0;
}
_lastRequest = DateTime.UtcNow;
_requestsThisBurst++;
break;
case RateLimitMode.Burst:
if (_requestsThisBurst == 0 || (DateTime.UtcNow - _burstStart).TotalSeconds >= 60) //this is first request OR the burst expired
{
_burstStart = DateTime.UtcNow;
_requestsThisBurst = 0;
}
if (_requestsThisBurst >= limitRequestsPerMinute) //limit has been reached
{
while ((DateTime.UtcNow - _burstStart).TotalSeconds < 60)
Thread.Sleep(250);
_burstStart = DateTime.UtcNow;
_requestsThisBurst = 0;
}
_lastRequest = DateTime.UtcNow;
_requestsThisBurst++;
break;
}
}
public virtual HttpWebRequest CreateRequest(string url, string method)
{
EnforceRateLimit();
bool prependDomain = !Uri.IsWellFormedUriString(url, UriKind.Absolute);
HttpWebRequest request;
if (prependDomain)
request = (HttpWebRequest)WebRequest.Create(string.Format("{0}://{1}{2}", Protocol, RootDomain, url));
else
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = Cookies;
if (IsOAuth())// use OAuth
{
request.Headers.Set("Authorization", "bearer " + AccessToken);//Must be included in OAuth calls
}
request.Method = method;
request.UserAgent = UserAgent + " - with RedditSharp by /u/meepster23";
return request;
}
protected virtual HttpWebRequest CreateRequest(Uri uri, string method)
{
EnforceRateLimit();
var request = (HttpWebRequest)WebRequest.Create(uri);
request.CookieContainer = Cookies;
if (Type.GetType("Mono.Runtime") != null)
{
var cookieHeader = Cookies.GetCookieHeader(new Uri("http://reddit.com"));
request.Headers.Set("Cookie", cookieHeader);
}
if (IsOAuth())// use OAuth
{
request.Headers.Set("Authorization", "bearer " + AccessToken);//Must be included in OAuth calls
}
request.Method = method;
request.UserAgent = UserAgent + " - with RedditSharp by /u/meepster23";
return request;
}
public virtual HttpWebRequest CreateGet(string url)
{
return CreateRequest(url, "GET");
}
private HttpWebRequest CreateGet(Uri url)
{
return CreateRequest(url, "GET");
}
public virtual HttpWebRequest CreatePost(string url)
{
var request = CreateRequest(url, "POST");
request.ContentType = "application/x-www-form-urlencoded";
return request;
}
public virtual string GetResponseString(Stream stream)
{
var data = new StreamReader(stream).ReadToEnd();
stream.Close();
return data;
}
public virtual void WritePostBody(Stream stream, object data, params string[] additionalFields)
{
var type = data.GetType();
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
string value = "";
foreach (var property in properties)
{
var attr = property.GetCustomAttributes(typeof(RedditAPINameAttribute), false).FirstOrDefault() as RedditAPINameAttribute;
string name = attr == null ? property.Name : attr.Name;
var entry = Convert.ToString(property.GetValue(data, null));
value += name + "=" + HttpUtility.UrlEncode(entry).Replace(";", "%3B").Replace("&", "%26") + "&";
}
for (int i = 0; i < additionalFields.Length; i += 2)
{
var entry = Convert.ToString(additionalFields[i + 1]) ?? string.Empty;
value += additionalFields[i] + "=" + HttpUtility.UrlEncode(entry).Replace(";", "%3B").Replace("&", "%26") + "&";
}
value = value.Remove(value.Length - 1); // Remove trailing &
var raw = Encoding.UTF8.GetBytes(value);
stream.Write(raw, 0, raw.Length);
stream.Close();
}
private static bool IsOAuth()
{
return RootDomain == "oauth.reddit.com";
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
#if !NETMF
using System.Configuration;
#endif
using System.Diagnostics;
#if NETMF
using Microsoft.SPOT;
#endif
namespace log4net.Util
{
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
public delegate void LogReceivedEventHandler(object source, LogReceivedEventArgs e);
/// <summary>
/// Outputs log statements from within the log4net assembly.
/// </summary>
/// <remarks>
/// <para>
/// Log4net components cannot make log4net logging calls. However, it is
/// sometimes useful for the user to learn about what log4net is
/// doing.
/// </para>
/// <para>
/// All log4net internal debug calls go to the standard output stream
/// whereas internal error messages are sent to the standard error output
/// stream.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class LogLog
{
/// <summary>
/// The event raised when an internal message has been received.
/// </summary>
public static event LogReceivedEventHandler LogReceived;
private readonly Type source;
private readonly DateTime timeStamp;
private readonly string prefix;
private readonly string message;
private readonly Exception exception;
/// <summary>
/// The Type that generated the internal message.
/// </summary>
public Type Source
{
get { return source; }
}
/// <summary>
/// The DateTime stamp of when the internal message was received.
/// </summary>
public DateTime TimeStamp
{
get { return timeStamp; }
}
/// <summary>
/// A string indicating the severity of the internal message.
/// </summary>
/// <remarks>
/// "log4net: ",
/// "log4net:ERROR ",
/// "log4net:WARN "
/// </remarks>
public string Prefix
{
get { return prefix; }
}
/// <summary>
/// The internal log message.
/// </summary>
public string Message
{
get { return message; }
}
/// <summary>
/// The Exception related to the message.
/// </summary>
/// <remarks>
/// Optional. Will be null if no Exception was passed.
/// </remarks>
public Exception Exception
{
get { return exception; }
}
/// <summary>
/// Formats Prefix, Source, and Message in the same format as the value
/// sent to Console.Out and Trace.Write.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Prefix + Source.Name + ": " + Message;
}
#region Private Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LogLog" /> class.
/// </summary>
/// <param name="source"></param>
/// <param name="prefix"></param>
/// <param name="message"></param>
/// <param name="exception"></param>
public LogLog(Type source, string prefix, string message, Exception exception)
{
timeStamp = DateTime.Now;
this.source = source;
this.prefix = prefix;
this.message = message;
this.exception = exception;
}
#endregion Private Instance Constructors
#region Static Constructor
/// <summary>
/// Static constructor that initializes logging by reading
/// settings from the application configuration file.
/// </summary>
/// <remarks>
/// <para>
/// The <c>log4net.Internal.Debug</c> application setting
/// controls internal debugging. This setting should be set
/// to <c>true</c> to enable debugging.
/// </para>
/// <para>
/// The <c>log4net.Internal.Quiet</c> application setting
/// suppresses all internal logging including error messages.
/// This setting should be set to <c>true</c> to enable message
/// suppression.
/// </para>
/// </remarks>
static LogLog()
{
#if !NETCF
try
{
InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Debug"), false);
QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Quiet"), false);
EmitInternalMessages = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Emit"), true);
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not
// parse correctly.
//
// We will leave debug OFF and print an Error message
Error(typeof(LogLog), "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
#endif
}
#endregion Static Constructor
#region Public Static Properties
/// <summary>
/// Gets or sets a value indicating whether log4net internal logging
/// is enabled or disabled.
/// </summary>
/// <value>
/// <c>true</c> if log4net internal logging is enabled, otherwise
/// <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c>, internal debug level logging will be
/// displayed.
/// </para>
/// <para>
/// This value can be set by setting the application setting
/// <c>log4net.Internal.Debug</c> in the application configuration
/// file.
/// </para>
/// <para>
/// The default value is <c>false</c>, i.e. debugging is
/// disabled.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// The following example enables internal debugging using the
/// application configuration file :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net.Internal.Debug" value="true" />
/// </appSettings>
/// </configuration>
/// </code>
/// </example>
public static bool InternalDebugging
{
get { return s_debugEnabled; }
set { s_debugEnabled = value; }
}
/// <summary>
/// Gets or sets a value indicating whether log4net should generate no output
/// from internal logging, not even for errors.
/// </summary>
/// <value>
/// <c>true</c> if log4net should generate no output at all from internal
/// logging, otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c> will cause internal logging at all levels to be
/// suppressed. This means that no warning or error reports will be logged.
/// This option overrides the <see cref="InternalDebugging"/> setting and
/// disables all debug also.
/// </para>
/// <para>This value can be set by setting the application setting
/// <c>log4net.Internal.Quiet</c> in the application configuration file.
/// </para>
/// <para>
/// The default value is <c>false</c>, i.e. internal logging is not
/// disabled.
/// </para>
/// </remarks>
/// <example>
/// The following example disables internal logging using the
/// application configuration file :
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net.Internal.Quiet" value="true" />
/// </appSettings>
/// </configuration>
/// </code>
/// </example>
public static bool QuietMode
{
get { return s_quietMode; }
set { s_quietMode = value; }
}
/// <summary>
///
/// </summary>
public static bool EmitInternalMessages
{
get { return s_emitInternalMessages; }
set { s_emitInternalMessages = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Raises the LogReceived event when an internal messages is received.
/// </summary>
/// <param name="source"></param>
/// <param name="prefix"></param>
/// <param name="message"></param>
/// <param name="exception"></param>
public static void OnLogReceived(Type source, string prefix, string message, Exception exception)
{
if (LogReceived != null)
{
LogReceived(null, new LogReceivedEventArgs(new LogLog(source, prefix, message, exception)));
}
}
/// <summary>
/// Test if LogLog.Debug is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Debug is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Debug is enabled for output.
/// </para>
/// </remarks>
public static bool IsDebugEnabled
{
get { return s_debugEnabled && !s_quietMode; }
}
/// <summary>
/// Writes log4net internal debug messages to the
/// standard output stream.
/// </summary>
/// <param name="source"></param>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net: ".
/// </para>
/// </remarks>
public static void Debug(Type source, string message)
{
if (IsDebugEnabled)
{
if (EmitInternalMessages)
{
EmitOutLine(PREFIX + message);
}
OnLogReceived(source, PREFIX, message, null);
}
}
/// <summary>
/// Writes log4net internal debug messages to the
/// standard output stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net: ".
/// </para>
/// </remarks>
public static void Debug(Type source, string message, Exception exception)
{
if (IsDebugEnabled)
{
if (EmitInternalMessages)
{
EmitOutLine(PREFIX + message);
if (exception != null)
{
EmitOutLine(exception.ToString());
}
}
OnLogReceived(source, PREFIX, message, exception);
}
}
/// <summary>
/// Test if LogLog.Warn is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Warn is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Warn is enabled for output.
/// </para>
/// </remarks>
public static bool IsWarnEnabled
{
get { return !s_quietMode; }
}
/// <summary>
/// Writes log4net internal warning messages to the
/// standard error stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal warning messages are prepended with
/// the string "log4net:WARN ".
/// </para>
/// </remarks>
public static void Warn(Type source, string message)
{
if (IsWarnEnabled)
{
if (EmitInternalMessages)
{
EmitErrorLine(WARN_PREFIX + message);
}
OnLogReceived(source, WARN_PREFIX, message, null);
}
}
/// <summary>
/// Writes log4net internal warning messages to the
/// standard error stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal warning messages are prepended with
/// the string "log4net:WARN ".
/// </para>
/// </remarks>
public static void Warn(Type source, string message, Exception exception)
{
if (IsWarnEnabled)
{
if (EmitInternalMessages)
{
EmitErrorLine(WARN_PREFIX + message);
if (exception != null)
{
EmitErrorLine(exception.ToString());
}
}
OnLogReceived(source, WARN_PREFIX, message, exception);
}
}
/// <summary>
/// Test if LogLog.Error is enabled for output.
/// </summary>
/// <value>
/// <c>true</c> if Error is enabled
/// </value>
/// <remarks>
/// <para>
/// Test if LogLog.Error is enabled for output.
/// </para>
/// </remarks>
public static bool IsErrorEnabled
{
get { return !s_quietMode; }
}
/// <summary>
/// Writes log4net internal error messages to the
/// standard error stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// All internal error messages are prepended with
/// the string "log4net:ERROR ".
/// </para>
/// </remarks>
public static void Error(Type source, string message)
{
if (IsErrorEnabled)
{
if (EmitInternalMessages)
{
EmitErrorLine(ERR_PREFIX + message);
}
OnLogReceived(source, ERR_PREFIX, message, null);
}
}
/// <summary>
/// Writes log4net internal error messages to the
/// standard error stream.
/// </summary>
/// <param name="source">The Type that generated this message.</param>
/// <param name="message">The message to log.</param>
/// <param name="exception">An exception to log.</param>
/// <remarks>
/// <para>
/// All internal debug messages are prepended with
/// the string "log4net:ERROR ".
/// </para>
/// </remarks>
public static void Error(Type source, string message, Exception exception)
{
if (IsErrorEnabled)
{
if (EmitInternalMessages)
{
EmitErrorLine(ERR_PREFIX + message);
if (exception != null)
{
EmitErrorLine(exception.ToString());
}
}
OnLogReceived(source, ERR_PREFIX, message, exception);
}
}
#endregion Public Static Methods
/// <summary>
/// Writes output to the standard output stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// Writes to both Console.Out and System.Diagnostics.Trace.
/// Note that the System.Diagnostics.Trace is not supported
/// on the Compact Framework.
/// </para>
/// <para>
/// If the AppDomain is not configured with a config file then
/// the call to System.Diagnostics.Trace may fail. This is only
/// an issue if you are programmatically creating your own AppDomains.
/// </para>
/// </remarks>
private static void EmitOutLine(string message)
{
try
{
#if NETCF
Console.WriteLine(message);
//System.Diagnostics.Debug.WriteLine(message);
#elif NETMF
Debug.Print(message);
Trace.Print(message);
#else
Console.Out.WriteLine(message);
Trace.WriteLine(message);
#endif
}
catch
{
// Ignore exception, what else can we do? Not really a good idea to propagate back to the caller
}
}
/// <summary>
/// Writes output to the standard error stream.
/// </summary>
/// <param name="message">The message to log.</param>
/// <remarks>
/// <para>
/// Writes to both Console.Error and System.Diagnostics.Trace.
/// Note that the System.Diagnostics.Trace is not supported
/// on the Compact Framework.
/// </para>
/// <para>
/// If the AppDomain is not configured with a config file then
/// the call to System.Diagnostics.Trace may fail. This is only
/// an issue if you are programmatically creating your own AppDomains.
/// </para>
/// </remarks>
private static void EmitErrorLine(string message)
{
try
{
#if NETCF
Console.WriteLine(message);
//System.Diagnostics.Debug.WriteLine(message);
#elif NETMF
Debug.Print(message);
Trace.Print(message);
#else
Console.Error.WriteLine(message);
Trace.WriteLine(message);
#endif
}
catch
{
// Ignore exception, what else can we do? Not really a good idea to propagate back to the caller
}
}
#region Private Static Fields
/// <summary>
/// Default debug level
/// </summary>
private static bool s_debugEnabled = false;
/// <summary>
/// In quietMode not even errors generate any output.
/// </summary>
private static bool s_quietMode = false;
private static bool s_emitInternalMessages = true;
private const string PREFIX = "log4net: ";
private const string ERR_PREFIX = "log4net:ERROR ";
private const string WARN_PREFIX = "log4net:WARN ";
#endregion Private Static Fields
/// <summary>
/// Subscribes to the LogLog.LogReceived event and stores messages
/// to the supplied IList instance.
/// </summary>
public class LogReceivedAdapter : IDisposable
{
private readonly IList items;
private readonly LogReceivedEventHandler handler;
/// <summary>
///
/// </summary>
/// <param name="items"></param>
public LogReceivedAdapter(IList items)
{
this.items = items;
handler = new LogReceivedEventHandler(LogLog_LogReceived);
LogReceived += handler;
}
void LogLog_LogReceived(object source, LogReceivedEventArgs e)
{
items.Add(e.LogLog);
}
/// <summary>
///
/// </summary>
public IList Items
{
get { return items; }
}
/// <summary>
///
/// </summary>
public void Dispose()
{
LogReceived -= handler;
}
}
}
/// <summary>
///
/// </summary>
public class LogReceivedEventArgs : EventArgs
{
private readonly LogLog loglog;
/// <summary>
///
/// </summary>
/// <param name="loglog"></param>
public LogReceivedEventArgs(LogLog loglog)
{
this.loglog = loglog;
}
/// <summary>
///
/// </summary>
public LogLog LogLog
{
get { return loglog; }
}
}
}
| |
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using Windows.Devices.Geolocation;
namespace Kazyx.WPPMM.Utils
{
public class Downloader
{
private Task task;
private readonly Queue<DownloadRequest> DownloadQueue = new Queue<DownloadRequest>();
internal Action<int> QueueStatusUpdated;
internal void AddDownloadQueue(Uri uri, Geoposition position, Action<Picture> OnCompleted, Action<ImageDLError> OnError)
{
var req = new DownloadRequest { Uri = uri, GeoPosition = position, Completed = OnCompleted, Error = OnError };
DebugUtil.Log("Enqueue " + uri.AbsoluteUri);
DownloadQueue.Enqueue(req);
if (QueueStatusUpdated != null)
{
QueueStatusUpdated(DownloadQueue.Count);
}
ProcessQueueSequentially();
}
private void ProcessQueueSequentially()
{
if (task == null)
{
DebugUtil.Log("Create new task");
task = Task.Factory.StartNew(async () =>
{
while (DownloadQueue.Count != 0)
{
DebugUtil.Log("Dequeue - remaining " + DownloadQueue.Count);
await DownloadImage(DownloadQueue.Dequeue());
if (QueueStatusUpdated != null)
{
QueueStatusUpdated(DownloadQueue.Count);
}
}
DebugUtil.Log("Queue end. Kill task");
task = null;
});
}
}
private async Task DownloadImage(DownloadRequest req)
{
DebugUtil.Log("Run DownloadImage task");
try
{
var strm = await GetResponseStreamAsync(req.Uri);
// geo tagging
var GeoTaggingError = ImageDLError.None;
if (req.GeoPosition != null)
{
try
{
strm = NtImageProcessor.MetaData.MetaDataOperator.AddGeoposition(strm, req.GeoPosition);
}
catch (NtImageProcessor.MetaData.Misc.GpsInformationAlreadyExistsException)
{
DebugUtil.Log("Caught GpsInformationAlreadyExistsException.");
GeoTaggingError = ImageDLError.GeotagAlreadyExists;
}
catch (Exception)
{
DebugUtil.Log("Caught exception during geotagging");
GeoTaggingError = ImageDLError.GeotagAddition;
}
}
var pic = new MediaLibrary().SavePictureToCameraRoll(//
string.Format("CameraRemote{0:yyyyMMdd_HHmmss}.jpg", DateTime.Now), strm);
strm.Dispose();
if (GeoTaggingError == ImageDLError.GeotagAddition)
{
Deployment.Current.Dispatcher.BeginInvoke(() => req.Error.Invoke(ImageDLError.GeotagAddition));
}
else if (GeoTaggingError == ImageDLError.GeotagAlreadyExists)
{
Deployment.Current.Dispatcher.BeginInvoke(() => req.Error.Invoke(ImageDLError.GeotagAlreadyExists));
}
if (pic == null)
{
Deployment.Current.Dispatcher.BeginInvoke(() => req.Error.Invoke(ImageDLError.Saving));
return;
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() => req.Completed.Invoke(pic));
}
}
catch (HttpStatusException e)
{
if (e.StatusCode == HttpStatusCode.Gone)
{
Deployment.Current.Dispatcher.BeginInvoke(() => req.Error.Invoke(ImageDLError.Gone));
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() => req.Error.Invoke(ImageDLError.Network));
}
}
catch (WebException)
{
Deployment.Current.Dispatcher.BeginInvoke(() => req.Error.Invoke(ImageDLError.Network));
}
catch (Exception e)
{
// Some devices throws exception while saving picture to camera roll.
// e.g.) HTC 8S
DebugUtil.Log("Caught exception at saving picture: " + e.Message);
DebugUtil.Log(e.StackTrace);
Deployment.Current.Dispatcher.BeginInvoke(() => req.Error.Invoke(ImageDLError.DeviceInternal));
}
}
public static Task<Stream> GetResponseStreamAsync(Uri uri)
{
var tcs = new TaskCompletionSource<Stream>();
var request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Method = "GET";
var ResponseHandler = new AsyncCallback((res) =>
{
try
{
var result = request.EndGetResponse(res) as HttpWebResponse;
if (result == null)
{
tcs.TrySetException(new WebException("No HttpWebResponse"));
return;
}
var code = result.StatusCode;
if (code == HttpStatusCode.OK)
{
tcs.TrySetResult(result.GetResponseStream());
}
else
{
DebugUtil.Log("Http Status Error: " + code);
tcs.TrySetException(new HttpStatusException(code));
}
}
catch (WebException e)
{
var result = e.Response as HttpWebResponse;
if (result != null)
{
DebugUtil.Log("Http Status Error: " + result.StatusCode);
tcs.TrySetException(new HttpStatusException(result.StatusCode));
}
else
{
DebugUtil.Log("WebException: " + e.Status);
tcs.TrySetException(e);
}
};
});
request.BeginGetResponse(ResponseHandler, null);
return tcs.Task;
}
}
class HttpStatusException : Exception
{
public readonly HttpStatusCode StatusCode;
public HttpStatusException(HttpStatusCode code)
{
this.StatusCode = code;
}
}
class DownloadRequest
{
public Uri Uri;
public Geoposition GeoPosition;
public Action<Picture> Completed;
public Action<ImageDLError> Error;
}
public enum ImageDLError
{
Network,
Saving,
Argument,
DeviceInternal,
GeotagAlreadyExists,
GeotagAddition,
Gone,
Unknown,
None,
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) *
// * *
// * This library is free software; you can redistribute it and/or *
// * modify it under the terms of the GNU Lesser General Public License *
// * as published by the Free Software Foundation; either version 2.1 *
// * of the License, or (at your option) any later version. *
// * *
// * This library is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
// * Lesser General Public License for more details. *
// * *
// * You should have received a copy of the GNU Lesser General Public *
// * License along with this library; if not, write to the Free *
// * Software Foundation, Inc., 59 Temple Place, Suite 330, *
// * Boston, MA 02111-1307 USA *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: Cache.cs
//
// Created: 30-01-2007 SharedCache.com, rschuetz
// Modified: 30-01-2007 SharedCache.com, rschuetz : Creation
// Modified: 16-12-2007 SharedCache.com, rschuetz : added calculated cache size, upon each action ( add || remove ) it updates the value
// Modified: 18-12-2007 SharedCache.com, rschuetz : changed Cache from HybridDictonary into Dictionary<string, byte[]>() upon both constructors
// Modified: 18-12-2007 SharedCache.com, rschuetz : since SharedCache works internally with byte[] instead of objects almoast all needed code has been adapted
// Modified: 18-12-2007 SharedCache.com, rschuetz : added regions
// Modified: 18-12-2007 SharedCache.com, rschuetz : implementation of Cache Size [CalculatedCacheSize], the property is configurable over the App.config file: CacheAmountOfObjects
// Modified: 20-01-2008 SharedCache.com, rschuetz : within Insert method calculated cache size were not be updated.
// Modified: 28-01-2010 SharedCache.com, chrisme : clean up code
// *************************************************************************
using System;
using System.Collections.Generic;
namespace SharedCache.WinServiceCommon
{
/// <summary>
/// Provides generic object cache/pool that based on
/// CLR garbage collector (GC) logic.
/// </summary>
/// <remarks>
/// You can extend Cache behaviour in distributed
/// environment by lifetime services setting
/// of Your classes.
/// </remarks>
[Serializable]
public sealed class Cache
{
#region Properties & private Variables
#region Property: CalculatedCacheSize
private long calculatedCacheSize;
/// <summary>
/// Gets/sets the CalculatedCacheSize
/// </summary>
public long CalculatedCacheSize
{
[System.Diagnostics.DebuggerStepThrough]
get { return this.calculatedCacheSize; }
}
#endregion
#region Singleton: CacheCleanup
private CacheCleanup cacheCleanup;
/// <summary>
/// Singleton for <see cref="CacheCleanup" />
/// </summary>
public CacheCleanup CacheCleanup
{
[System.Diagnostics.DebuggerStepThrough]
get { return this.cacheCleanup ?? (this.cacheCleanup = new CacheCleanup()); }
}
#endregion
/// <summary>
/// The Cache Dictionary which contains all data
/// </summary>
readonly Dictionary<string, byte[]> dict;
#endregion Properties & private Variables
#region Constructors
/// <summary>
/// Creates an empty Cache.
/// </summary>
public Cache()
{
dict = new Dictionary<string, byte[]>();
this.calculatedCacheSize = 0;
}
/// <summary>
/// Creates a Cache with the specified initial size.
/// </summary>
/// <param name="initialSize">The approximate number of objects that the Cache can initially contain.</param>
public Cache(int initialSize) : this()
{
dict = new Dictionary<string, byte[]>(initialSize);
}
#endregion Constructors
#region Methods
#region General Methods [Amount / Size / Clear / GetAllKeys]
/// <summary>
/// returns the amount this instance contains.
/// </summary>
/// <returns></returns>
public long Amount()
{
long result = 0;
lock (dict)
{
result = dict.Count;
}
return result;
}
/// <summary>
/// calculates the actual size of this instance.
/// <remarks>
/// This is a very heavy operation, please consider not to use this to often then
/// it locks the cache exclusivly which is very expensive!!!
/// </remarks>
/// </summary>
/// <returns>a <see cref="long"/> object with the actual Dictionary size</returns>
public long Size()
{
Dictionary<string, byte[]> di = null;
long size = 0;
// consider, this is very expensive!!
lock (dict)
{
di = new Dictionary<string, byte[]>(dict);
}
foreach (KeyValuePair<string, byte[]> de in di)
{
size += de.Value.Length;
}
return size;
}
/// <summary>
/// Retrive all key's
/// </summary>
/// <returns>returns a list with all key's as a <see cref="string"/> objects.</returns>
public List<string> GetAllKeys()
{
Dictionary<string, byte[]> hd = null;
lock (dict)
{
hd = new Dictionary<string, byte[]>(dict);
}
return new List<string>(hd.Keys);
}
#endregion General Methods [Amount / Size / Clear / GetAllKeys]
#region Add / Insert Methods
/// <summary>
/// Adds an object that identified by the provided key to the Cache.
/// if the key is already available it will replace it.
/// </summary>
/// <param name="key">The Object to use as the key of the object to add.</param>
/// <param name="value">The Object to add. </param>
public void Add(string key, byte[] value)
{
try
{
lock (dict)
{
dict[key] = value;
this.calculatedCacheSize += value.Length;
}
}
catch (Exception ex)
{
Handler.LogHandler.Force(@"Add Failed - " + ex.Message);
}
}
/// <summary>
/// Adds the specified KeyValuePair
/// </summary>
/// <param name="kpv">The KPV. A <see cref="T:System.Collections.Generic.KeyValuePair<System.String,System.Object>"/> Object.</param>
public void Add(KeyValuePair<string, byte[]> kpv)
{
this.Add(kpv.Key, kpv.Value);
}
/// <summary>
/// Inserts the specified key.
/// </summary>
/// <param name="key">The key. A <see cref="T:System.String"/> Object.</param>
/// <param name="value">The value. A <see cref="T:System.Object"/> Object.</param>
public void Insert(string key, byte[] value)
{
lock (dict)
{
dict.Add(key, value);
this.calculatedCacheSize += value.Length;
}
}
#endregion Add / Insert Methods
#region Retrive Method
/// <summary>
/// Gets the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>a <see cref="object"/> object.</returns>
public byte[] Get(string key)
{
byte[] o = null;
try
{
lock (dict)
{
if (dict.ContainsKey(key))
{
o = dict[key];
}
else
o = null;
}
}
catch (Exception ex)
{
Handler.LogHandler.Info(@"Get Failed!", ex);
}
return o;
}
#endregion Retrive Methods
#region Remove / Clear Methods
/// <summary>
/// Removes the object that identified by the specified key from the Cache.
/// </summary>
/// <param name="key">The key of the object to remove.</param>
public void Remove(string key)
{
try
{
lock (dict)
{
if (dict.ContainsKey(key))
{
this.calculatedCacheSize -= dict[key].Length;
dict.Remove(key);
}
}
GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
Handler.LogHandler.Info(@"Remove failed!", ex);
}
}
/// <summary>
/// Removes all objects from the Cache.
/// </summary>
public void Clear()
{
lock (dict)
{
dict.Clear();
this.calculatedCacheSize = 0;
}
// ISSUE: Not sure if this has to be here
GC.Collect();
}
#endregion Remove Methods
#endregion Methods
}
}
| |
/*This script has been, partially or completely, generated by the Fungus.GenerateVariableWindow*/
using UnityEngine;
namespace Fungus
{
// <summary>
/// Get or Set a property of a Animator component
/// </summary>
[CommandInfo("Property",
"Animator",
"Get or Set a property of a Animator component")]
[AddComponentMenu("")]
public class AnimatorProperty : BaseVariableProperty
{
//generated property
public enum Property
{
IsOptimizable,
IsHuman,
HasRootMotion,
HumanScale,
IsInitialized,
DeltaPosition,
DeltaRotation,
Velocity,
AngularVelocity,
RootPosition,
RootRotation,
ApplyRootMotion,
HasTransformHierarchy,
GravityWeight,
BodyPosition,
BodyRotation,
StabilizeFeet,
LayerCount,
ParameterCount,
FeetPivotActive,
PivotWeight,
PivotPosition,
IsMatchingTarget,
Speed,
TargetPosition,
TargetRotation,
PlaybackTime,
RecorderStartTime,
RecorderStopTime,
HasBoundPlayables,
LayersAffectMassCenter,
LeftFeetBottomHeight,
RightFeetBottomHeight,
LogWarnings,
FireEvents,
KeepAnimatorControllerStateOnDisable,
}
[SerializeField]
protected Property property;
[SerializeField]
[VariableProperty(typeof(AnimatorVariable))]
protected AnimatorVariable animatorVar;
[SerializeField]
[VariableProperty(typeof(BooleanVariable),
typeof(FloatVariable),
typeof(Vector3Variable),
typeof(QuaternionVariable),
typeof(IntegerVariable))]
protected Variable inOutVar;
public override void OnEnter()
{
var iob = inOutVar as BooleanVariable;
var iof = inOutVar as FloatVariable;
var iov = inOutVar as Vector3Variable;
var ioq = inOutVar as QuaternionVariable;
var ioi = inOutVar as IntegerVariable;
var target = animatorVar.Value;
switch (getOrSet)
{
case GetSet.Get:
switch (property)
{
case Property.IsOptimizable:
iob.Value = target.isOptimizable;
break;
case Property.IsHuman:
iob.Value = target.isHuman;
break;
case Property.HasRootMotion:
iob.Value = target.hasRootMotion;
break;
case Property.HumanScale:
iof.Value = target.humanScale;
break;
case Property.IsInitialized:
iob.Value = target.isInitialized;
break;
case Property.DeltaPosition:
iov.Value = target.deltaPosition;
break;
case Property.DeltaRotation:
ioq.Value = target.deltaRotation;
break;
case Property.Velocity:
iov.Value = target.velocity;
break;
case Property.AngularVelocity:
iov.Value = target.angularVelocity;
break;
case Property.RootPosition:
iov.Value = target.rootPosition;
break;
case Property.RootRotation:
ioq.Value = target.rootRotation;
break;
case Property.ApplyRootMotion:
iob.Value = target.applyRootMotion;
break;
case Property.HasTransformHierarchy:
iob.Value = target.hasTransformHierarchy;
break;
case Property.GravityWeight:
iof.Value = target.gravityWeight;
break;
case Property.BodyPosition:
iov.Value = target.bodyPosition;
break;
case Property.BodyRotation:
ioq.Value = target.bodyRotation;
break;
case Property.StabilizeFeet:
iob.Value = target.stabilizeFeet;
break;
case Property.LayerCount:
ioi.Value = target.layerCount;
break;
case Property.ParameterCount:
ioi.Value = target.parameterCount;
break;
case Property.FeetPivotActive:
iof.Value = target.feetPivotActive;
break;
case Property.PivotWeight:
iof.Value = target.pivotWeight;
break;
case Property.PivotPosition:
iov.Value = target.pivotPosition;
break;
case Property.IsMatchingTarget:
iob.Value = target.isMatchingTarget;
break;
case Property.Speed:
iof.Value = target.speed;
break;
case Property.TargetPosition:
iov.Value = target.targetPosition;
break;
case Property.TargetRotation:
ioq.Value = target.targetRotation;
break;
case Property.PlaybackTime:
iof.Value = target.playbackTime;
break;
case Property.RecorderStartTime:
iof.Value = target.recorderStartTime;
break;
case Property.RecorderStopTime:
iof.Value = target.recorderStopTime;
break;
case Property.HasBoundPlayables:
iob.Value = target.hasBoundPlayables;
break;
case Property.LayersAffectMassCenter:
iob.Value = target.layersAffectMassCenter;
break;
case Property.LeftFeetBottomHeight:
iof.Value = target.leftFeetBottomHeight;
break;
case Property.RightFeetBottomHeight:
iof.Value = target.rightFeetBottomHeight;
break;
case Property.LogWarnings:
iob.Value = target.logWarnings;
break;
case Property.FireEvents:
iob.Value = target.fireEvents;
break;
#if UNITY_2019_2_OR_NEWER
case Property.KeepAnimatorControllerStateOnDisable:
iob.Value = target.keepAnimatorControllerStateOnDisable;
break;
#endif
default:
Debug.Log("Unsupported get or set attempted");
break;
}
break;
case GetSet.Set:
switch (property)
{
case Property.RootPosition:
target.rootPosition = iov.Value;
break;
case Property.RootRotation:
target.rootRotation = ioq.Value;
break;
case Property.ApplyRootMotion:
target.applyRootMotion = iob.Value;
break;
case Property.BodyPosition:
target.bodyPosition = iov.Value;
break;
case Property.BodyRotation:
target.bodyRotation = ioq.Value;
break;
case Property.StabilizeFeet:
target.stabilizeFeet = iob.Value;
break;
case Property.FeetPivotActive:
target.feetPivotActive = iof.Value;
break;
case Property.Speed:
target.speed = iof.Value;
break;
case Property.PlaybackTime:
target.playbackTime = iof.Value;
break;
case Property.RecorderStartTime:
target.recorderStartTime = iof.Value;
break;
case Property.RecorderStopTime:
target.recorderStopTime = iof.Value;
break;
case Property.LayersAffectMassCenter:
target.layersAffectMassCenter = iob.Value;
break;
case Property.LogWarnings:
target.logWarnings = iob.Value;
break;
case Property.FireEvents:
target.fireEvents = iob.Value;
break;
#if UNITY_2019_2_OR_NEWER
case Property.KeepAnimatorControllerStateOnDisable:
target.keepAnimatorControllerStateOnDisable = iob.Value;
break;
#endif
default:
Debug.Log("Unsupported get or set attempted");
break;
}
break;
default:
break;
}
Continue();
}
public override string GetSummary()
{
if (animatorVar == null)
{
return "Error: no animatorVar set";
}
if (inOutVar == null)
{
return "Error: no variable set to push or pull data to or from";
}
return getOrSet.ToString() + " " + property.ToString();
}
public override Color GetButtonColor()
{
return new Color32(235, 191, 217, 255);
}
public override bool HasReference(Variable variable)
{
if (animatorVar == variable || inOutVar == variable)
return true;
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.MirrorRecursiveTypes
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Some cool documentation.
/// </summary>
public partial class RecursiveTypesAPI : ServiceClient<RecursiveTypesAPI>, IRecursiveTypesAPI
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public RecursiveTypesAPI(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public RecursiveTypesAPI(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public RecursiveTypesAPI(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public RecursiveTypesAPI(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("https://management.azure.com/");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// Products
/// </summary>
/// <remarks>
/// The Products endpoint returns information about the Uber products offered
/// at a given location. The response includes the display name and other
/// details about each product, and lists the products in the proper display
/// order.
/// </remarks>
/// <param name='subscriptionId'>
/// Subscription Id.
/// </param>
/// <param name='resourceGroupName'>
/// Resource Group Id.
/// </param>
/// <param name='apiVersion'>
/// API Id.
/// </param>
/// <param name='body'>
/// API body mody.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> PostWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, string apiVersion, Product body = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (apiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "apiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{apiVersion}", System.Uri.EscapeDataString(apiVersion));
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#define PROTOTYPE
#if UNITY_STANDALONE || UNITY_EDITOR
using UnityEngine;
using System.Collections;
using ProBuilder2.Common;
namespace ProBuilder2.Examples
{
/**
* \brief This class allows the user to select a single face at a time and move it forwards or backwards.
* More advanced usage of the ProBuilder API should make use of the pb_Object->SelectedFaces list to keep
* track of the selected faces.
*/
public class RuntimeEdit : MonoBehaviour
{
class pb_Selection
{
public pb_Object pb; ///< This is the currently selected ProBuilder object.
public pb_Face face; ///< Keep a reference to the currently selected face.
public pb_Selection(pb_Object _pb, pb_Face _face)
{
pb = _pb;
face = _face;
}
public bool HasObject()
{
return pb != null;
}
public bool IsValid()
{
return pb != null && face != null;
}
public bool Equals(pb_Selection sel)
{
if(sel != null && sel.IsValid())
return (pb == sel.pb && face == sel.face);
else
return false;
}
public void Destroy()
{
if(pb != null)
GameObject.Destroy(pb.gameObject);
}
public override string ToString()
{
return "pb_Object: " + pb == null ? "Null" : pb.name +
"\npb_Face: " + ( (face == null) ? "Null" : face.ToString() );
}
}
pb_Selection currentSelection;
pb_Selection previousSelection;
private pb_Object preview;
public Material previewMaterial;
/**
* \brief Wake up!
*/
void Awake()
{
SpawnCube();
}
/**
* \brief This is the usual Unity OnGUI method. We only use it to show a 'Reset' button.
*/
void OnGUI()
{
// To reset, nuke the pb_Object and build a new one.
if(GUI.Button(new Rect(5, Screen.height - 25, 80, 20), "Reset"))
{
currentSelection.Destroy();
Destroy(preview.gameObject);
SpawnCube();
}
}
/**
* \brief Creates a new ProBuilder cube and sets it up with a concave MeshCollider.
*/
void SpawnCube()
{
// This creates a basic cube with ProBuilder features enabled. See the ProBuilder.Shape enum to
// see all possible primitive types.
pb_Object pb = pb_ShapeGenerator.CubeGenerator(Vector3.one);
// The runtime component requires that a concave mesh collider be present in order for face selection
// to work.
pb.gameObject.AddComponent<MeshCollider>().convex = false;
// Now set it to the currentSelection
currentSelection = new pb_Selection(pb, null);
}
Vector2 mousePosition_initial = Vector2.zero;
bool dragging = false;
public float rotateSpeed = 100f;
/**
* \brief This is responsible for moving the camera around and not much else.
*/
public void LateUpdate()
{
if(!currentSelection.HasObject())
return;
if(Input.GetMouseButtonDown(1) || (Input.GetMouseButtonDown(0) && Input.GetKey(KeyCode.LeftAlt)))
{
mousePosition_initial = Input.mousePosition;
dragging = true;
}
if(dragging)
{
Vector2 delta = (Vector3)mousePosition_initial - (Vector3)Input.mousePosition;
Vector3 dir = new Vector3(delta.y, delta.x, 0f);
currentSelection.pb.gameObject.transform.RotateAround(Vector3.zero, dir, rotateSpeed * Time.deltaTime);
// If there is a currently selected face, update the preview.
if(currentSelection.IsValid())
RefreshSelectedFacePreview();
}
if(Input.GetMouseButtonUp(1) || Input.GetMouseButtonUp(0))
{
dragging = false;
}
}
/**
* \brief The 'meat' of the operation. This listens for a click event, then checks for a positive
* face selection. If the click has hit a pb_Object, select it.
*/
public void Update()
{
if(Input.GetMouseButtonUp(0) && !Input.GetKey(KeyCode.LeftAlt)) {
if(FaceCheck(Input.mousePosition))
{
if(currentSelection.IsValid())
{
// Check if this face has been previously selected, and if so, move the face.
// Otherwise, just accept this click as a selection.
if(!currentSelection.Equals(previousSelection))
{
previousSelection = new pb_Selection(currentSelection.pb, currentSelection.face);
RefreshSelectedFacePreview();
return;
}
Vector3 localNormal = pb_Math.Normal( pbUtil.ValuesWithIndices(currentSelection.pb.vertices, currentSelection.face.distinctIndices) );// currentSelection.pb.GetVertices(currentSelection.face.distinctIndices));
if(Input.GetKey(KeyCode.LeftShift))
currentSelection.pb.TranslateVertices( currentSelection.face.distinctIndices, localNormal.normalized * -.5f );
else
currentSelection.pb.TranslateVertices( currentSelection.face.distinctIndices, localNormal.normalized * .5f );
currentSelection.pb.Refresh(); // Refresh will update the Collision mesh volume, face UVs as applicatble, and normal information.
// this create the selected face preview
RefreshSelectedFacePreview();
}
}
}
}
/**
* \brief This is how we figure out what face is clicked.
*/
public bool FaceCheck(Vector3 pos)
{
Ray ray = Camera.main.ScreenPointToRay (pos);
RaycastHit hit;
if( Physics.Raycast(ray.origin, ray.direction, out hit))
{
pb_Object hitpb = hit.transform.gameObject.GetComponent<pb_Object>();
if(hitpb == null)
return false;
Mesh m = hitpb.msh;
int[] tri = new int[3] {
m.triangles[hit.triangleIndex * 3 + 0],
m.triangles[hit.triangleIndex * 3 + 1],
m.triangles[hit.triangleIndex * 3 + 2]
};
currentSelection.pb = hitpb;
return hitpb.FaceWithTriangle(tri, out currentSelection.face);
}
return false;
}
void RefreshSelectedFacePreview()
{
pb_Face face = new pb_Face(currentSelection.face); // Copy the currently selected face
face.ShiftIndicesToZero(); // Shift the selected face indices to zero
// Copy the currently selected vertices in world space.
// World space so that we don't have to apply transforms
// to match the current selection.
Vector3[] verts = currentSelection.pb.VerticesInWorldSpace(currentSelection.face.distinctIndices);
// Now go through and move the verts we just grabbed out about .1m from the original face.
Vector3 normal = pb_Math.Normal(verts);
for(int i = 0; i < verts.Length; i++)
verts[i] += normal.normalized * .01f;
if(preview)
Destroy(preview.gameObject);
preview = pb_Object.CreateInstanceWithVerticesFaces(verts, new pb_Face[1]{face});
preview.SetFaceMaterial(preview.faces, previewMaterial);
preview.ToMesh();
preview.Refresh();
}
}
}
#endif
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a JSON property.
/// </summary>
public class JProperty : JContainer
{
private readonly List<JToken> _content = new List<JToken>();
private readonly string _name;
/// <summary>
/// Gets the container's children tokens.
/// </summary>
/// <value>The container's children tokens.</value>
protected override IList<JToken> ChildrenTokens
{
get { return _content; }
}
/// <summary>
/// Gets the property name.
/// </summary>
/// <value>The property name.</value>
public string Name
{
[DebuggerStepThrough]
get { return _name; }
}
/// <summary>
/// Gets or sets the property value.
/// </summary>
/// <value>The property value.</value>
public JToken Value
{
[DebuggerStepThrough]
get { return (ChildrenTokens.Count > 0) ? ChildrenTokens[0] : null; }
set
{
CheckReentrancy();
JToken newValue = value ?? new JValue((object) null);
if (ChildrenTokens.Count == 0)
{
InsertItem(0, newValue);
}
else
{
SetItem(0, newValue);
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JProperty"/> class from another <see cref="JProperty"/> object.
/// </summary>
/// <param name="other">A <see cref="JProperty"/> object to copy from.</param>
public JProperty(JProperty other)
: base(other)
{
_name = other.Name;
}
internal override JToken GetItem(int index)
{
if (index != 0)
throw new ArgumentOutOfRangeException();
return Value;
}
internal override void SetItem(int index, JToken item)
{
if (index != 0)
throw new ArgumentOutOfRangeException();
if (IsTokenUnchanged(Value, item))
return;
if (Parent != null)
((JObject)Parent).InternalPropertyChanging(this);
base.SetItem(0, item);
if (Parent != null)
((JObject)Parent).InternalPropertyChanged(this);
}
internal override bool RemoveItem(JToken item)
{
throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
}
internal override void RemoveItemAt(int index)
{
throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
}
internal override void InsertItem(int index, JToken item)
{
if (Value != null)
throw new Exception("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
base.InsertItem(0, item);
}
internal override bool ContainsItem(JToken item)
{
return (Value == item);
}
internal override void ClearItems()
{
throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
}
internal override bool DeepEquals(JToken node)
{
JProperty t = node as JProperty;
return (t != null && _name == t.Name && ContentsEqual(t));
}
internal override JToken CloneToken()
{
return new JProperty(this);
}
/// <summary>
/// Gets the node type for this <see cref="JToken"/>.
/// </summary>
/// <value>The type.</value>
public override JTokenType Type
{
[DebuggerStepThrough]
get { return JTokenType.Property; }
}
internal JProperty(string name)
{
// called from JTokenWriter
ValidationUtils.ArgumentNotNull(name, "name");
_name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="JProperty"/> class.
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="content">The property content.</param>
public JProperty(string name, params object[] content)
: this(name, (object)content)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JProperty"/> class.
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="content">The property content.</param>
public JProperty(string name, object content)
{
ValidationUtils.ArgumentNotNull(name, "name");
_name = name;
Value = IsMultiContent(content)
? new JArray(content)
: CreateFromContent(content);
}
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
writer.WritePropertyName(_name);
Value.WriteTo(writer, converters);
}
internal override int GetDeepHashCode()
{
return _name.GetHashCode() ^ ((Value != null) ? Value.GetDeepHashCode() : 0);
}
/// <summary>
/// Loads an <see cref="JProperty"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JProperty"/>.</param>
/// <returns>A <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static new JProperty Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JProperty from JsonReader.");
}
if (reader.TokenType != JsonToken.PropertyName)
throw new Exception(
"Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(
CultureInfo.InvariantCulture, reader.TokenType));
JProperty p = new JProperty((string)reader.Value);
p.SetLineInfo(reader as IJsonLineInfo);
p.ReadTokenFrom(reader);
return p;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.CodeAnalysis;
namespace Tmds.DBus.Tool
{
class CodeGenCommand : Command
{
CommandOption _serviceOption;
CommandOption _serviceNameOption;
CommandOption _busOption;
CommandOption _pathOption;
CommandOption _norecurseOption;
CommandOption _namespaceOption;
CommandOption _outputOption;
CommandOption _catOption;
CommandOption _skipOptions;
CommandOption _interfaceOptions;
CommandOption _publicOption;
CommandOption _noInternalsVisibleToOption;
CommandArgument _files;
CommandOption _protocolOption;
public CodeGenCommand(CommandLineApplication parent) :
base("codegen", parent)
{}
public override void Configure()
{
_serviceOption = AddServiceOption();
_serviceNameOption = AddServiceNameOption();
_busOption = AddBusOption();
_pathOption = AddPathOption();
_norecurseOption = AddNoRecurseOption();
_noInternalsVisibleToOption = Configuration.Option("--no-ivt", "Don't add the InternalsVisibleTo Attribute", CommandOptionType.NoValue);
_namespaceOption = Configuration.Option("--namespace", "C# namespace (default: <service>)", CommandOptionType.SingleValue);
_outputOption = Configuration.Option("--output", "File to write (default: <namespace>.cs)", CommandOptionType.SingleValue);
_catOption = Configuration.Option("--cat", "Write to standard out instead of file", CommandOptionType.NoValue);
_skipOptions = Configuration.Option("--skip", "DBus interfaces to skip", CommandOptionType.MultipleValue);
_interfaceOptions = Configuration.Option("--interface", "DBus interfaces to include, optionally specify a name (e.g. 'org.freedesktop.NetworkManager.Device.Wired:WiredDevice')", CommandOptionType.MultipleValue);
_publicOption = Configuration.Option("--public", "The code generated by this tool will have public access modifier (default: internal)", CommandOptionType.NoValue);
_protocolOption = Configuration.Option("--protocol-api", "The code generated by this tool will use target the Tmds.DBus.Protocol API.", CommandOptionType.NoValue);
_files = AddFilesArgument();
}
internal CommandOption AddServiceNameOption()
=> Configuration.Option("--service-name", ".NET name for the service.", CommandOptionType.SingleValue);
public override void Execute()
{
if (!_serviceOption.HasValue() && _files.Values == null)
{
throw new ArgumentException("Service option or files argument must be specified.", "service");
}
IEnumerable<string> skipInterfaces = new [] { "org.freedesktop.DBus.Introspectable", "org.freedesktop.DBus.Peer", "org.freedesktop.DBus.Properties" };
if (_skipOptions.HasValue())
{
skipInterfaces = skipInterfaces.Concat(_skipOptions.Values);
}
Dictionary<string, string> interfaces = null;
if (_interfaceOptions.HasValue())
{
interfaces = new Dictionary<string, string>();
foreach (var interf in _interfaceOptions.Values)
{
if (interf.Contains(':'))
{
var split = interf.Split(new[] { ':' });
interfaces.Add(split[0], split[1]);
}
else
{
interfaces.Add(interf, null);
}
}
}
var address = ParseBusAddress(_busOption);
var service = _serviceOption.Value();
string ns = _namespaceOption.Value();
var serviceName = _serviceNameOption.Value();
if (serviceName == null)
{
if (service != null)
{
var serviceSplit = service.Split(new [] { '.' });
serviceName = serviceSplit[serviceSplit.Length - 1];
}
else
{
serviceName = "MyService";
}
}
ns = ns ?? $"{serviceName}.DBus";
var codeGenArguments = new CodeGenArguments
{
Namespace = ns,
Service = service,
ServiceName = serviceName,
Path = _pathOption.HasValue() ? _pathOption.Value() : "/",
Address = address,
Recurse = !_norecurseOption.HasValue(),
NoInternalsVisibleTo = _noInternalsVisibleToOption.HasValue(),
OutputFileName = _catOption.HasValue() ? null : _outputOption.Value() ?? $"{ns}.cs",
SkipInterfaces = skipInterfaces,
Interfaces = interfaces,
TypesAccessModifier = _publicOption.HasValue() ? Accessibility.Public : Accessibility.NotApplicable,
Files = _files.Values,
ProtocolApi = _protocolOption.HasValue()
};
GenerateCodeAsync(codeGenArguments).Wait();
}
class Visitor
{
private CodeGenArguments _arguments;
private Dictionary<string, InterfaceDescription> _introspections;
private HashSet<string> _names;
public Visitor(CodeGenArguments codeGenArguments)
{
_introspections = new Dictionary<string, InterfaceDescription>();
_names = new HashSet<string>();
_arguments = codeGenArguments;
}
public bool VisitNode(string path, XElement nodeXml)
{
foreach (var interfaceXml in nodeXml.Elements("interface"))
{
string fullName = interfaceXml.Attribute("name").Value;
if (_introspections.ContainsKey(fullName) || _arguments.SkipInterfaces.Contains(fullName))
{
continue;
}
string proposedName = null;
if (_arguments.Interfaces != null)
{
if (!_arguments.Interfaces.TryGetValue(fullName, out proposedName))
{
continue;
}
}
if (proposedName == null)
{
var split = fullName.Split(new[] { '.' });
var name = Generator.Prettify(split[split.Length - 1]);
proposedName = name;
int index = 0;
while (_names.Contains(proposedName))
{
proposedName = $"{name}{index}";
index++;
}
}
_names.Add(proposedName);
_introspections.Add(fullName, new InterfaceDescription { InterfaceXml = interfaceXml, Name = proposedName });
if (_arguments.Interfaces != null)
{
_arguments.Interfaces.Remove(fullName);
return _arguments.Interfaces.Count != 0;
}
}
return true;
}
public List<InterfaceDescription> Descriptions => _introspections.Values.ToList();
}
private async Task GenerateCodeAsync(CodeGenArguments codeGenArguments)
{
var visitor = new Visitor(codeGenArguments);
if (codeGenArguments.Service != null)
{
using (var connection = new Connection(codeGenArguments.Address))
{
await connection.ConnectAsync();
await NodeVisitor.VisitAsync(connection, codeGenArguments.Service, codeGenArguments.Path, codeGenArguments.Recurse, visitor.VisitNode);
}
}
if (codeGenArguments.Files != null)
{
foreach (var file in codeGenArguments.Files)
{
await NodeVisitor.VisitAsync(file, visitor.VisitNode);
}
}
var descriptions = visitor.Descriptions;
var generator = codeGenArguments.ProtocolApi
? (IGenerator)new ProtocolGenerator(
new ProtocolGeneratorSettings {
Namespace = codeGenArguments.Namespace,
TypesAccessModifier = codeGenArguments.TypesAccessModifier,
ServiceName = codeGenArguments.ServiceName
})
: new Generator(
new GeneratorSettings {
Namespace = codeGenArguments.Namespace,
NoInternalsVisibleTo = codeGenArguments.NoInternalsVisibleTo,
TypesAccessModifier = codeGenArguments.TypesAccessModifier
});
var code = generator.Generate(descriptions);
if (codeGenArguments.OutputFileName != null)
{
File.WriteAllText(codeGenArguments.OutputFileName, code);
Console.WriteLine($"Generated: {Path.GetFullPath(codeGenArguments.OutputFileName)}");
}
else
{
System.Console.WriteLine(code);
}
}
class CodeGenArguments
{
public string Namespace { get; set; }
public string Service { get; set; }
public string ServiceName { get; set; }
public string Path { get; set; }
public string Address { get; set; }
public bool Recurse { get; set; }
public string OutputFileName { get; set; }
public IEnumerable<string> SkipInterfaces { get; set; }
public Dictionary<string, string> Interfaces { get; set; }
public List<string> Files { get; set; }
public bool NoInternalsVisibleTo { get; set; }
public Accessibility TypesAccessModifier {get; set;}
public bool ProtocolApi { get; set; }
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
namespace Reporting.Rdl
{
///<summary>
/// Parsing name lookup. Fields, parameters, report items, globals, user, aggregate scopes, grouping,...
///</summary>
internal class NameLookup
{
IDictionary fields;
IDictionary parameters;
IDictionary reportitems;
IDictionary globals;
IDictionary user;
IDictionary aggrScope;
Grouping g; // if expression in a table group or detail group
// used to default aggregates to the right group
Matrix m; // if expression used in a Matrix
// used to default aggregate to the right matrix
Classes instances;
CodeModules cms;
Type codeType;
DataSetsDefn dsets;
ReportLink _PageFooterHeader; // when expression is in page header or footer this is set
string _ExprName; // name of the expression; this isn't always set
internal NameLookup(IDictionary f, IDictionary p, IDictionary r,
IDictionary gbl, IDictionary u, IDictionary ascope,
Grouping ag, Matrix mt, CodeModules cm, Classes i, DataSetsDefn ds, Type ct)
{
fields=f;
parameters=p;
reportitems=r;
globals=gbl;
user=u;
aggrScope = ascope;
g=ag;
m = mt;
cms = cm;
instances = i;
dsets = ds;
codeType = ct;
}
internal ReportLink PageFooterHeader
{
get {return _PageFooterHeader;}
set {_PageFooterHeader = value;}
}
internal bool IsPageScope
{
get {return _PageFooterHeader != null;}
}
internal string ExpressionName
{
get {return _ExprName;}
set {_ExprName = value;}
}
internal IDictionary Fields
{
get { return fields; }
}
internal IDictionary Parameters
{
get { return parameters; }
}
internal IDictionary ReportItems
{
get { return reportitems; }
}
internal IDictionary User
{
get { return user; }
}
internal IDictionary Globals
{
get { return globals; }
}
internal ReportClass LookupInstance(string name)
{
if (instances == null)
return null;
return instances[name];
}
internal Field LookupField(string name)
{
if (fields == null)
return null;
return (Field) fields[name];
}
internal ReportParameter LookupParameter(string name)
{
if (parameters == null)
return null;
return (ReportParameter) parameters[name];
}
internal Textbox LookupReportItem(string name)
{
if (reportitems == null)
return null;
return (Textbox) reportitems[name];
}
internal IExpr LookupGlobal(string name)
{
if (globals == null)
return null;
return (IExpr) globals[name];
}
internal Type LookupType(string clsname)
{
if (cms == null || clsname == string.Empty)
return null;
return cms[clsname];
}
internal CodeModules CMS
{
get{return cms;}
}
internal Type CodeClassType
{
get{return codeType;}
}
internal IExpr LookupUser(string name)
{
if (user == null)
return null;
return (IExpr) user[name];
}
internal Grouping LookupGrouping()
{
return g;
}
internal Matrix LookupMatrix()
{
return m;
}
internal object LookupScope(string name)
{
if (aggrScope == null)
return null;
return aggrScope[name];
}
internal DataSetDefn ScopeDataSet(string name)
{
if (name == null)
{ // Only allowed when there is only one dataset
if (dsets.Items.Count != 1)
return null;
foreach (DataSetDefn ds in dsets.Items.Values) // No easy way to get the item by index
return ds;
return null;
}
return dsets[name];
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using log4net;
using HttpServer;
using HttpListener = HttpServer.HttpListener;
namespace OpenSim.Framework.Servers.HttpServer
{
/// <summary>
/// OSHttpServer provides an HTTP server bound to a specific
/// port. When instantiated with just address and port it uses
/// normal HTTP, when instantiated with address, port, and X509
/// certificate, it uses HTTPS.
/// </summary>
public class OSHttpServer
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private object _syncObject = new object();
// underlying HttpServer.HttpListener
protected HttpListener _listener;
// underlying core/engine thread
protected Thread _engine;
// Queue containing (OS)HttpRequests
protected OSHttpRequestQueue _queue;
// OSHttpRequestPumps "pumping" incoming OSHttpRequests
// upwards
protected OSHttpRequestPump[] _pumps;
// thread identifier
protected string _engineId;
public string EngineID
{
get { return _engineId; }
}
/// <summary>
/// True if this is an HTTPS connection; false otherwise.
/// </summary>
protected bool _isSecure;
public bool IsSecure
{
get { return _isSecure; }
}
public int QueueSize
{
get { return _pumps.Length; }
}
/// <summary>
/// List of registered OSHttpHandlers for this OSHttpServer instance.
/// </summary>
protected List<OSHttpHandler> _httpHandlers = new List<OSHttpHandler>();
public List<OSHttpHandler> OSHttpHandlers
{
get
{
lock (_httpHandlers)
{
return new List<OSHttpHandler>(_httpHandlers);
}
}
}
/// <summary>
/// Instantiate an HTTP server.
/// </summary>
public OSHttpServer(IPAddress address, int port, int poolSize)
{
_engineId = String.Format("OSHttpServer (HTTP:{0})", port);
_isSecure = false;
_log.DebugFormat("[{0}] HTTP server instantiated", EngineID);
_listener = new HttpListener(address, port);
_queue = new OSHttpRequestQueue();
_pumps = OSHttpRequestPump.Pumps(this, _queue, poolSize);
}
/// <summary>
/// Instantiate an HTTPS server.
/// </summary>
public OSHttpServer(IPAddress address, int port, X509Certificate certificate, int poolSize)
{
_engineId = String.Format("OSHttpServer [HTTPS:{0}/ps:{1}]", port, poolSize);
_isSecure = true;
_log.DebugFormat("[{0}] HTTPS server instantiated", EngineID);
_listener = new HttpListener(address, port, certificate);
_queue = new OSHttpRequestQueue();
_pumps = OSHttpRequestPump.Pumps(this, _queue, poolSize);
}
/// <summary>
/// Turn an HttpRequest into an OSHttpRequestItem and place it
/// in the queue. The OSHttpRequestQueue object will pulse the
/// next available idle pump.
/// </summary>
protected void OnHttpRequest(HttpClientContext client, HttpRequest request)
{
// turn request into OSHttpRequest
OSHttpRequest req = new OSHttpRequest(client, request);
// place OSHttpRequest into _httpRequestQueue, will
// trigger Pulse to idle waiting pumps
_queue.Enqueue(req);
}
/// <summary>
/// Start the HTTP server engine.
/// </summary>
public void Start()
{
_engine = new Thread(new ThreadStart(Engine));
_engine.Name = _engineId;
_engine.IsBackground = true;
_engine.Start();
ThreadTracker.Add(_engine);
// start the pumps...
for (int i = 0; i < _pumps.Length; i++)
_pumps[i].Start();
}
public void Stop()
{
lock (_syncObject) Monitor.Pulse(_syncObject);
}
/// <summary>
/// Engine keeps the HTTP server running.
/// </summary>
private void Engine()
{
try {
_listener.RequestHandler += OnHttpRequest;
_listener.Start(QueueSize);
_log.InfoFormat("[{0}] HTTP server started", EngineID);
lock (_syncObject) Monitor.Wait(_syncObject);
}
catch (Exception ex)
{
_log.DebugFormat("[{0}] HTTP server startup failed: {1}", EngineID, ex.ToString());
}
_log.InfoFormat("[{0}] HTTP server terminated", EngineID);
}
/// <summary>
/// Add an HTTP request handler.
/// </summary>
/// <param name="handler">OSHttpHandler delegate</param>
/// <param name="path">regex object for path matching</parm>
/// <param name="headers">dictionary containing header names
/// and regular expressions to match against header values</param>
public void AddHandler(OSHttpHandler handler)
{
lock (_httpHandlers)
{
if (_httpHandlers.Contains(handler))
{
_log.DebugFormat("[OSHttpServer] attempt to add already existing handler ignored");
return;
}
_httpHandlers.Add(handler);
}
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:[email protected])
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.ComponentModel;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
#endif
#if WPF
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
#endif
using PdfSharp;
using PdfSharp.Internal;
using PdfSharp.Fonts.OpenType;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Advanced;
// WPFHACK
#pragma warning disable 162
namespace PdfSharp.Drawing
{
/// <summary>
/// Defines an object used to draw image files (bmp, png, jpeg, gif) and PDF forms.
/// An abstract base class that provides functionality for the Bitmap and Metafile descended classes.
/// </summary>
public class XImage : IDisposable
{
/// <summary>
/// Initializes a new instance of the <see cref="XImage"/> class.
/// </summary>
protected XImage()
{
}
#if GDI
/// <summary>
/// Initializes a new instance of the <see cref="XImage"/> class from a GDI+ image.
/// </summary>
XImage(Image image)
{
this.gdiImage = image;
#if WPF
this.wpfImage = ImageHelper.CreateBitmapSource(image);
#endif
Initialize();
}
#endif
#if WPF && !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="XImage"/> class from a WPF image.
/// </summary>
XImage(BitmapSource image)
{
this.wpfImage = image;
Initialize();
}
#endif
XImage(string path)
{
path = Path.GetFullPath(path);
if (!File.Exists(path))
throw new FileNotFoundException(PSSR.FileNotFound(path), path);
this.path = path;
//FileStream file = new FileStream(filename, FileMode.Open);
//BitsLength = (int)file.Length;
//Bits = new byte[BitsLength];
//file.Read(Bits, 0, BitsLength);
//file.Close();
#if GDI
this.gdiImage = Image.FromFile(path);
#endif
#if WPF && !SILVERLIGHT
//BitmapSource.Create()
// BUG: BitmapImage locks the file
this.wpfImage = new BitmapImage(new Uri(path)); // AGHACK
#endif
#if false
float vres = this.image.VerticalResolution;
float hres = this.image.HorizontalResolution;
SizeF size = this.image.PhysicalDimension;
int flags = this.image.Flags;
Size sz = this.image.Size;
GraphicsUnit units = GraphicsUnit.Millimeter;
RectangleF rect = this.image.GetBounds(ref units);
int width = this.image.Width;
#endif
Initialize();
}
XImage(Stream stream)
{
// Create a dummy unique path
this.path = "*" + Guid.NewGuid().ToString("B");
#if GDI
this.gdiImage = Image.FromStream(stream);
#endif
#if WPF
throw new NotImplementedException();
//this.wpfImage = new BitmapImage(new Uri(path));
#endif
#if true_
float vres = this.image.VerticalResolution;
float hres = this.image.HorizontalResolution;
SizeF size = this.image.PhysicalDimension;
int flags = this.image.Flags;
Size sz = this.image.Size;
GraphicsUnit units = GraphicsUnit.Millimeter;
RectangleF rect = this.image.GetBounds(ref units);
int width = this.image.Width;
#endif
Initialize();
}
#if GDI
#if UseGdiObjects
/// <summary>
/// Implicit conversion from Image to XImage.
/// </summary>
public static implicit operator XImage(Image image)
{
return new XImage(image);
}
#endif
/// <summary>
/// Conversion from Image to XImage.
/// </summary>
public static XImage FromGdiPlusImage(Image image)
{
return new XImage(image);
}
#endif
#if WPF && !SILVERLIGHT
/// <summary>
/// Conversion from BitmapSource to XImage.
/// </summary>
public static XImage FromBitmapSource(BitmapSource image)
{
return new XImage(image);
}
#endif
/// <summary>
/// Creates an image from the specified file.
/// </summary>
/// <param name="path">The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.</param>
public static XImage FromFile(string path)
{
if (PdfReader.TestPdfFile(path) > 0)
return new XPdfForm(path);
return new XImage(path);
}
/// <summary>
/// Creates an image from the specified stream.
/// </summary>
/// <param name="stream">A MemoryStream object containing the image data.</param>
/// <returns></returns>
public static XImage FromStream(MemoryStream stream)
{
return new XImage(stream);
}
/// <summary>
/// Tests if a file exist. Supports PDF files with page number suffix.
/// </summary>
/// <param name="path">The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.</param>
public static bool ExistsFile(string path)
{
if (PdfReader.TestPdfFile(path) > 0)
return true;
return File.Exists(path);
}
void Initialize()
{
#if GDI
if (this.gdiImage != null)
{
// ImageFormat has no overridden Equals...
string guid = this.gdiImage.RawFormat.Guid.ToString("B").ToUpper();
switch (guid)
{
case "{B96B3CAA-0728-11D3-9D7B-0000F81EF32E}": // memoryBMP
case "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}": // bmp
case "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}": // png
this.format = XImageFormat.Png;
break;
case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg
this.format = XImageFormat.Jpeg;
break;
case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif
this.format = XImageFormat.Gif;
break;
case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff
this.format = XImageFormat.Tiff;
break;
case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon
this.format = XImageFormat.Icon;
break;
case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf
case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf
case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif
case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD
case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX
default:
throw new InvalidOperationException("Unsupported image format.");
}
return;
}
#endif
#if WPF
#if !SILVERLIGHT
if (this.wpfImage != null)
{
string pixelFormat = this.wpfImage.Format.ToString();
string filename = GetImageFilename(this.wpfImage);
// WPF treats all images as images.
// We give JPEG images a special treatment.
// Test if it's a JPEG:
bool isJpeg = IsJpeg; // TestJpeg(filename);
if (isJpeg)
{
this.format = XImageFormat.Jpeg;
return;
}
switch (pixelFormat)
{
case "Bgr32":
case "Bgra32":
case "Pbgra32":
this.format = XImageFormat.Png;
break;
//case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg
// this.format = XImageFormat.Jpeg;
// break;
//case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif
case "BlackWhite":
case "Indexed1":
case "Indexed4":
case "Indexed8":
case "Gray8":
this.format = XImageFormat.Gif;
break;
//case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff
// this.format = XImageFormat.Tiff;
// break;
//case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon
// this.format = XImageFormat.Icon;
// break;
//case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf
//case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf
//case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif
//case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD
//case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX
default:
Debug.Assert(false, "Unknown pixel format: " + pixelFormat);
this.format = XImageFormat.Gif;
break;// throw new InvalidOperationException("Unsupported image format.");
}
}
#else
// AGHACK
#endif
#endif
}
#if WPF
/// <summary>
/// Gets the image filename.
/// </summary>
/// <param name="bitmapSource">The bitmap source.</param>
internal static string GetImageFilename(BitmapSource bitmapSource)
{
string filename = bitmapSource.ToString();
filename = UrlDecodeStringFromStringInternal(filename);
if (filename.StartsWith("file:///"))
filename = filename.Substring(8); // Remove all 3 slashes!
else if (filename.StartsWith("file://"))
filename = filename.Substring(5); // Keep 2 slashes (UNC path)
return filename;
}
private static string UrlDecodeStringFromStringInternal(string s/*, Encoding e*/)
{
int length = s.Length;
string result = "";
for (int i = 0; i < length; i++)
{
char ch = s[i];
if (ch == '+')
{
ch = ' ';
}
else if ((ch == '%') && (i < (length - 2)))
{
if ((s[i + 1] == 'u') && (i < (length - 5)))
{
int num3 = HexToInt(s[i + 2]);
int num4 = HexToInt(s[i + 3]);
int num5 = HexToInt(s[i + 4]);
int num6 = HexToInt(s[i + 5]);
if (((num3 < 0) || (num4 < 0)) || ((num5 < 0) || (num6 < 0)))
{
goto AddByte;
}
ch = (char)((((num3 << 12) | (num4 << 8)) | (num5 << 4)) | num6);
i += 5;
result += ch;
continue;
}
int num7 = HexToInt(s[i + 1]);
int num8 = HexToInt(s[i + 2]);
if ((num7 >= 0) && (num8 >= 0))
{
byte b = (byte)((num7 << 4) | num8);
i += 2;
result += (char)b;
continue;
}
}
AddByte:
if ((ch & 0xff80) == 0)
{
result += ch;
}
else
{
result += ch;
}
}
return result;
}
private static int HexToInt(char h)
{
if ((h >= '0') && (h <= '9'))
{
return (h - '0');
}
if ((h >= 'a') && (h <= 'f'))
{
return ((h - 'a') + 10);
}
if ((h >= 'A') && (h <= 'F'))
{
return ((h - 'A') + 10);
}
return -1;
}
#endif
#if WPF
/// <summary>
/// Tests if a file is a JPEG.
/// </summary>
/// <param name="filename">The filename.</param>
internal static bool TestJpeg(string filename)
{
byte[] imageBits = null;
return ReadJpegFile(filename, 16, ref imageBits);
}
/// <summary>
/// Reads the JPEG file.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="maxRead">The maximum count of bytes to be read.</param>
/// <param name="imageBits">The bytes read from the file.</param>
/// <returns>False, if file could not be read or is not a JPEG file.</returns>
internal static bool ReadJpegFile(string filename, int maxRead, ref byte[] imageBits)
{
if (File.Exists(filename))
{
FileStream fs = null;
try
{
fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
catch
{
return false;
}
if (fs.Length < 16)
{
fs.Close();
return false;
}
int len = maxRead == -1 ? (int)fs.Length : maxRead;
imageBits = new byte[len];
fs.Read(imageBits, 0, len);
fs.Close();
if (imageBits[0] == 0xff &&
imageBits[1] == 0xd8 &&
imageBits[2] == 0xff &&
imageBits[3] == 0xe0 &&
imageBits[6] == 0x4a &&
imageBits[7] == 0x46 &&
imageBits[8] == 0x49 &&
imageBits[9] == 0x46 &&
imageBits[10] == 0x0)
{
return true;
}
// TODO: Exif: find JFIF header
if (imageBits[0] == 0xff &&
imageBits[1] == 0xd8 &&
imageBits[2] == 0xff &&
imageBits[3] == 0xe1 /*&&
imageBits[6] == 0x4a &&
imageBits[7] == 0x46 &&
imageBits[8] == 0x49 &&
imageBits[9] == 0x46 &&
imageBits[10] == 0x0*/)
{
// Hack: store the file in PDF if extension matches ...
string str = filename.ToLower();
if (str.EndsWith(".jpg") || str.EndsWith(".jpeg"))
return true;
}
}
return false;
}
#endif
/// <summary>
/// Under construction
/// </summary>
public void Dispose()
{
Dispose(true);
//GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes underlying GDI+ object.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
this.disposed = true;
#if GDI
if (this.gdiImage != null)
{
this.gdiImage.Dispose();
this.gdiImage = null;
}
#endif
#if WPF
if (wpfImage != null)
{
wpfImage = null;
}
#endif
}
bool disposed;
/// <summary>
/// Gets the width of the image.
/// </summary>
[Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelWidth, but will become PointWidth in future releases of PDFsharp.")]
public virtual double Width
{
get
{
#if GDI && WPF
double gdiWidth = this.gdiImage.Width;
double wpfWidth = this.wpfImage.PixelWidth;
Debug.Assert(gdiWidth == wpfWidth);
return wpfWidth;
#endif
#if GDI && !WPF
return this.gdiImage.Width;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.PixelWidth;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the height of the image.
/// </summary>
[Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelHeight, but will become PointHeight in future releases of PDFsharp.")]
public virtual double Height
{
get
{
#if GDI && WPF
double gdiHeight = this.gdiImage.Height;
double wpfHeight = this.wpfImage.PixelHeight;
Debug.Assert(gdiHeight == wpfHeight);
return wpfHeight;
#endif
#if GDI && !WPF
return this.gdiImage.Height;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.PixelHeight;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the width of the image in point.
/// </summary>
public virtual double PointWidth
{
get
{
#if GDI && WPF
double gdiWidth = this.gdiImage.Width * 72 / this.gdiImage.HorizontalResolution;
double wpfWidth = this.wpfImage.Width * 72.0 / 96.0;
//Debug.Assert(gdiWidth == wpfWidth);
Debug.Assert(DoubleUtil.AreRoughlyEqual(gdiWidth, wpfWidth, 5));
return wpfWidth;
#endif
#if GDI && !WPF
return this.gdiImage.Width * 72 / this.gdiImage.HorizontalResolution;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
Debug.Assert(Math.Abs(this.wpfImage.PixelWidth * 72 / this.wpfImage.DpiX - this.wpfImage.Width * 72.0 / 96.0) < 0.001);
return this.wpfImage.Width * 72.0 / 96.0;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the height of the image in point.
/// </summary>
public virtual double PointHeight
{
get
{
#if GDI && WPF
double gdiHeight = this.gdiImage.Height * 72 / this.gdiImage.HorizontalResolution;
double wpfHeight = this.wpfImage.Height * 72.0 / 96.0;
Debug.Assert(DoubleUtil.AreRoughlyEqual(gdiHeight, wpfHeight, 5));
return wpfHeight;
#endif
#if GDI && !WPF
return this.gdiImage.Height * 72 / this.gdiImage.HorizontalResolution;
#endif
#if WPF || SILVERLIGHT && !GDI
#if !SILVERLIGHT
Debug.Assert(Math.Abs(this.wpfImage.PixelHeight * 72 / this.wpfImage.DpiY - this.wpfImage.Height * 72.0 / 96.0) < 0.001);
return this.wpfImage.Height * 72.0 / 96.0;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the width of the image in pixels.
/// </summary>
public virtual int PixelWidth
{
get
{
#if GDI && WPF
int gdiWidth = this.gdiImage.Width;
int wpfWidth = this.wpfImage.PixelWidth;
Debug.Assert(gdiWidth == wpfWidth);
return wpfWidth;
#endif
#if GDI && !WPF
return this.gdiImage.Width;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.PixelWidth;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the height of the image in pixels.
/// </summary>
public virtual int PixelHeight
{
get
{
#if GDI && WPF
int gdiHeight = this.gdiImage.Height;
int wpfHeight = this.wpfImage.PixelHeight;
Debug.Assert(gdiHeight == wpfHeight);
return wpfHeight;
#endif
#if GDI && !WPF
return this.gdiImage.Height;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.PixelHeight;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the size in point of the image.
/// </summary>
public virtual XSize Size
{
get { return new XSize(PointWidth, PointHeight); }
}
/// <summary>
/// Gets the horizontal resolution of the image.
/// </summary>
public virtual double HorizontalResolution
{
get
{
#if GDI && WPF
double gdiResolution = this.gdiImage.HorizontalResolution;
double wpfResolution = this.wpfImage.PixelWidth * 96.0 / this.wpfImage.Width;
Debug.Assert(gdiResolution == wpfResolution);
return wpfResolution;
#endif
#if GDI && !WPF
return this.gdiImage.HorizontalResolution;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.DpiX; //.PixelWidth * 96.0 / this.wpfImage.Width;
#else
// AGHACK
return 96;
#endif
#endif
}
}
/// <summary>
/// Gets the vertical resolution of the image.
/// </summary>
public virtual double VerticalResolution
{
get
{
#if GDI && WPF
double gdiResolution = this.gdiImage.VerticalResolution;
double wpfResolution = this.wpfImage.PixelHeight * 96.0 / this.wpfImage.Height;
Debug.Assert(gdiResolution == wpfResolution);
return wpfResolution;
#endif
#if GDI && !WPF
return this.gdiImage.VerticalResolution;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.DpiY; //.PixelHeight * 96.0 / this.wpfImage.Height;
#else
// AGHACK
return 96;
#endif
#endif
}
}
/// <summary>
/// Gets or sets a flag indicating whether image interpolation is to be performed.
/// </summary>
public virtual bool Interpolate
{
get { return this.interpolate; }
set { this.interpolate = value; }
}
bool interpolate = true;
/// <summary>
/// Gets the format of the image.
/// </summary>
public XImageFormat Format
{
get { return this.format; }
}
XImageFormat format;
#if WPF
/// <summary>
/// Gets a value indicating whether this image is JPEG.
/// </summary>
/// <value><c>true</c> if this image is JPEG; otherwise, <c>false</c>.</value>
public virtual bool IsJpeg
{
#if !SILVERLIGHT
//get { if (!isJpeg.HasValue) InitializeGdiHelper(); return isJpeg.HasValue ? isJpeg.Value : false; }
get { if (!isJpeg.HasValue) InitializeJpegQuickTest(); return isJpeg.HasValue ? isJpeg.Value : false; }
//set { isJpeg = value; }
#else
get { return false; } // AGHACK
#endif
}
private bool? isJpeg;
/// <summary>
/// Gets a value indicating whether this image is cmyk.
/// </summary>
/// <value><c>true</c> if this image is cmyk; otherwise, <c>false</c>.</value>
public virtual bool IsCmyk
{
#if !SILVERLIGHT
get { if (!isCmyk.HasValue) InitializeGdiHelper(); return isCmyk.HasValue ? isCmyk.Value : false; }
//set { isCmyk = value; }
#else
get { return false; } // AGHACK
#endif
}
private bool? isCmyk;
#if !SILVERLIGHT
/// <summary>
/// Gets the JPEG memory stream (if IsJpeg returns true).
/// </summary>
/// <value>The memory.</value>
public virtual MemoryStream Memory
{
get { if (!isCmyk.HasValue) InitializeGdiHelper(); return memory; }
//set { memory = value; }
}
MemoryStream memory = null;
/// <summary>
/// Determines if an image is JPEG w/o creating an Image object.
/// </summary>
private void InitializeJpegQuickTest()
{
isJpeg = TestJpeg(GetImageFilename(wpfImage));
}
/// <summary>
/// Initializes the GDI helper.
/// We use GDI+ to detect if image is JPEG.
/// If so, we also determine if it's CMYK and we read the image bytes.
/// </summary>
private void InitializeGdiHelper()
{
if (!isCmyk.HasValue)
{
try
{
using (System.Drawing.Image image = new System.Drawing.Bitmap(GetImageFilename(wpfImage)))
{
string guid = image.RawFormat.Guid.ToString("B").ToUpper();
isJpeg = guid == "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
isCmyk = (image.Flags & ((int)System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk | (int)System.Drawing.Imaging.ImageFlags.ColorSpaceYcck)) != 0;
if (isJpeg.Value)
{
memory = new MemoryStream();
image.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
if ((int)memory.Length == 0)
{
memory = null;
}
}
}
}
catch { }
}
}
#endif
#endif
#if DEBUG_
// TEST
internal void CreateAllImages(string name)
{
if (this.image != null)
{
this.image.Save(name + ".bmp", ImageFormat.Bmp);
this.image.Save(name + ".emf", ImageFormat.Emf);
this.image.Save(name + ".exif", ImageFormat.Exif);
this.image.Save(name + ".gif", ImageFormat.Gif);
this.image.Save(name + ".ico", ImageFormat.Icon);
this.image.Save(name + ".jpg", ImageFormat.Jpeg);
this.image.Save(name + ".png", ImageFormat.Png);
this.image.Save(name + ".tif", ImageFormat.Tiff);
this.image.Save(name + ".wmf", ImageFormat.Wmf);
this.image.Save(name + "2.bmp", ImageFormat.MemoryBmp);
}
}
#endif
#if GDI
internal Image gdiImage;
#endif
#if WPF
internal BitmapSource wpfImage;
#endif
/// <summary>
/// If path starts with '*' the image is created from a stream and the path is a GUID.
/// </summary>
internal string path;
/// <summary>
/// Cache PdfImageTable.ImageSelector to speed up finding the right PdfImage
/// if this image is used more than once.
/// </summary>
internal PdfImageTable.ImageSelector selector;
}
}
| |
// 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 UnpackLowByte()
{
var test = new SimpleBinaryOpTest__UnpackLowByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__UnpackLowByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__UnpackLowByte testClass)
{
var result = Sse2.UnpackLow(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__UnpackLowByte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__UnpackLowByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__UnpackLowByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.UnpackLow(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.UnpackLow(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.UnpackLow(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Byte*)(pClsVar1)),
Sse2.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__UnpackLowByte();
var result = Sse2.UnpackLow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__UnpackLowByte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.UnpackLow(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.UnpackLow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Byte*)(&test._fld1)),
Sse2.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != left[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i % 2 == 0) ? result[i] != left[i/2] : result[i] != right[(i - 1)/2])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.UnpackLow)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading; // For Thread, Mutex
public class TestContextBoundObject
{
public void TestMethod()
{
Thread.Sleep(MutexWaitOne2.c_LONG_SLEEP_TIME);
}
}
/// <summary>
/// WaitOne(System.Int32, System.Boolean)
/// </summary>
///
// Exercises Mutex:
// Waits infinitely,
// Waits a finite time,
// Times out appropriately,
// Throws Exceptions appropriately.
public class MutexWaitOne2
{
#region Public Constants
public const int c_DEFAULT_SLEEP_TIME = 1000; // 1 second
public const int c_LONG_SLEEP_TIME = 5000; // 5 second
#endregion
#region Private Fields
private Mutex m_Mutex = null;
#endregion
#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;
retVal = PosTest7() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest1: Wait Infinite");
try
{
do
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(SleepLongTime));
thread.Start();
if (m_Mutex.WaitOne(Timeout.Infinite) != true)
{
TestLibrary.TestFramework.LogError("001", "Can not wait Infinite");
retVal = false;
break;
}
m_Mutex.ReleaseMutex();
} while (false); // do
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
thread.Join();
}
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest2: Wait some finite time");
try
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(SignalMutex));
thread.Start();
m_Mutex.WaitOne(2 * c_DEFAULT_SLEEP_TIME);
m_Mutex.ReleaseMutex();
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
thread.Join();
}
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest3: Wait some finite time will quit for timeout");
try
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(SignalMutex));
thread.Start();
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
if (false != m_Mutex.WaitOne(c_DEFAULT_SLEEP_TIME / 10))
{
m_Mutex.ReleaseMutex();
TestLibrary.TestFramework.LogError("004", "WaitOne returns true when wait time out");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
thread.Join();
}
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest4: Wait some finite time will quit for timeout when another thread is in nondefault managed context");
try
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(CallContextBoundObjectMethod));
thread.Start();
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
if (false != m_Mutex.WaitOne(c_DEFAULT_SLEEP_TIME))
{
m_Mutex.ReleaseMutex();
TestLibrary.TestFramework.LogError("006", "WaitOne returns true when wait some finite time will quit for timeout when another thread is in nondefault managed context");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
thread.Join();
}
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest5: Wait some finite time will quit for timeout when another thread is in nondefault managed context");
try
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(CallContextBoundObjectMethod));
thread.Start();
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
if (false != m_Mutex.WaitOne(c_DEFAULT_SLEEP_TIME))
{
m_Mutex.ReleaseMutex();
TestLibrary.TestFramework.LogError("008", "WaitOne returns true when wait some finite time will quit for timeout when another thread is in nondefault managed context");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
thread.Join();
}
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest6: Wait infinite time when another thread is in nondefault managed context");
try
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(CallContextBoundObjectMethod));
thread.Start();
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
if (true != m_Mutex.WaitOne(Timeout.Infinite))
{
m_Mutex.ReleaseMutex();
TestLibrary.TestFramework.LogError("010", "WaitOne returns false when wait infinite time when another thread is in nondefault managed context");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
thread.Join();
}
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("PosTest7: Wait infinite time when another thread is in nondefault managed context");
try
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(CallContextBoundObjectMethod));
thread.Start();
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
if (true != m_Mutex.WaitOne(Timeout.Infinite))
{
m_Mutex.ReleaseMutex();
TestLibrary.TestFramework.LogError("012", "WaitOne returns false when wait infinite time when another thread is in nondefault managed context");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("013", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
// Wait for the thread to terminate
if (null != thread)
{
thread.Join();
}
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
#endregion
#region Negative Test Cases
public bool NegTest1()
{
bool retVal = true;
Thread thread = null;
TestLibrary.TestFramework.BeginScenario("NegTest1: AbandonedMutexException should be thrown if a thread exited without releasing a mutex");
try
{
m_Mutex = new Mutex();
thread = new Thread(new ThreadStart(NeverReleaseMutex));
thread.Start();
Thread.Sleep(c_DEFAULT_SLEEP_TIME / 5); // To avoid race
m_Mutex.WaitOne(Timeout.Infinite);
// AbandonedMutexException is not thrown on Windows 98 or Windows ME
//if (Environment.OSVersion.Platform == PlatformID.Win32NT)
//{
TestLibrary.TestFramework.LogError("101", "AbandonedMutexException is not thrown if a thread exited without releasing a mutex");
retVal = false;
//}
}
catch (AbandonedMutexException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
if (null != thread)
{
thread.Join();
}
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ObjectDisposedException should be thrown if current instance has already been disposed");
try
{
m_Mutex = new Mutex();
var thread = new Thread(new ThreadStart(DisposeMutex));
thread.IsBackground = true;
thread.Start();
thread.Join();
m_Mutex.WaitOne(Timeout.Infinite);
TestLibrary.TestFramework.LogError("103", "ObjectDisposedException is not thrown if current instance has already been disposed");
retVal = false;
}
catch (ObjectDisposedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
if (null != m_Mutex)
{
((IDisposable)m_Mutex).Dispose();
}
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
int testInt = 0;
TestLibrary.TestFramework.BeginScenario("NegTest3: Check ArgumentOutOfRangeException will be thrown if millisecondsTimeout is a negative number other than -1");
try
{
testInt = TestLibrary.Generator.GetInt32();
if (testInt > 0)
{
testInt = 0 - testInt;
}
if (testInt == -1)
{
testInt--;
}
m_Mutex = new Mutex();
m_Mutex.WaitOne(testInt);
TestLibrary.TestFramework.LogError("105", "ArgumentOutOfRangeException is not thrown if millisecondsTimeout is a negative number other than -1");
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] testInt = " + testInt);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] testInt = " + testInt);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
finally
{
if (null != m_Mutex)
{
m_Mutex.Dispose();
}
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
MutexWaitOne2 test = new MutexWaitOne2();
TestLibrary.TestFramework.BeginTestCase("MutexWaitOne2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private void SleepLongTime()
{
m_Mutex.WaitOne();
Thread.Sleep(c_LONG_SLEEP_TIME);
m_Mutex.ReleaseMutex();
}
private void SignalMutex()
{
m_Mutex.WaitOne();
Thread.Sleep(c_DEFAULT_SLEEP_TIME);
m_Mutex.ReleaseMutex();
}
private void NeverReleaseMutex()
{
m_Mutex.WaitOne();
Thread.Sleep(c_DEFAULT_SLEEP_TIME);
}
private void DisposeMutex()
{
((IDisposable)m_Mutex).Dispose();
}
private void CallContextBoundObjectMethod()
{
m_Mutex.WaitOne();
TestContextBoundObject obj = new TestContextBoundObject();
obj.TestMethod();
m_Mutex.ReleaseMutex();
}
#endregion
}
| |
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Cms.Core.Configuration;
namespace Umbraco.Cms.Core.Configuration
{
public class JsonConfigManipulator : IConfigManipulator
{
private readonly IConfiguration _configuration;
private readonly object _locker = new object();
public JsonConfigManipulator(IConfiguration configuration) => _configuration = configuration;
public string UmbracoConnectionPath { get; } = $"ConnectionStrings:{ Cms.Core.Constants.System.UmbracoConnectionName}";
public void RemoveConnectionString()
{
var provider = GetJsonConfigurationProvider(UmbracoConnectionPath);
var json = GetJson(provider);
RemoveJsonKey(json, UmbracoConnectionPath);
SaveJson(provider, json);
}
public void SaveConnectionString(string connectionString, string providerName)
{
var provider = GetJsonConfigurationProvider();
var json = GetJson(provider);
var item = GetConnectionItem(connectionString, providerName);
json.Merge(item, new JsonMergeSettings());
SaveJson(provider, json);
}
public void SaveConfigValue(string key, object value)
{
var provider = GetJsonConfigurationProvider();
var json = GetJson(provider);
JToken token = json;
foreach (var propertyName in key.Split(new[] { ':' }))
{
if (token is null)
break;
token = CaseSelectPropertyValues(token, propertyName);
}
if (token is null)
return;
var writer = new JTokenWriter();
writer.WriteValue(value);
token.Replace(writer.Token);
SaveJson(provider, json);
}
public void SaveDisableRedirectUrlTracking(bool disable)
{
var provider = GetJsonConfigurationProvider();
var json = GetJson(provider);
var item = GetDisableRedirectUrlItem(disable);
json.Merge(item, new JsonMergeSettings());
SaveJson(provider, json);
}
public void SetGlobalId(string id)
{
var provider = GetJsonConfigurationProvider();
var json = GetJson(provider);
var item = GetGlobalIdItem(id);
json.Merge(item, new JsonMergeSettings());
SaveJson(provider, json);
}
private object GetGlobalIdItem(string id)
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("Umbraco");
writer.WriteStartObject();
writer.WritePropertyName("CMS");
writer.WriteStartObject();
writer.WritePropertyName("Global");
writer.WriteStartObject();
writer.WritePropertyName("Id");
writer.WriteValue(id);
writer.WriteEndObject();
writer.WriteEndObject();
writer.WriteEndObject();
writer.WriteEndObject();
return writer.Token;
}
private JToken GetDisableRedirectUrlItem(bool value)
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("Umbraco");
writer.WriteStartObject();
writer.WritePropertyName("CMS");
writer.WriteStartObject();
writer.WritePropertyName("WebRouting");
writer.WriteStartObject();
writer.WritePropertyName("DisableRedirectUrlTracking");
writer.WriteValue(value);
writer.WriteEndObject();
writer.WriteEndObject();
writer.WriteEndObject();
writer.WriteEndObject();
return writer.Token;
}
private JToken GetConnectionItem(string connectionString, string providerName)
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("ConnectionStrings");
writer.WriteStartObject();
writer.WritePropertyName(Cms.Core.Constants.System.UmbracoConnectionName);
writer.WriteValue(connectionString);
writer.WriteEndObject();
writer.WriteEndObject();
return writer.Token;
}
private static void RemoveJsonKey(JObject json, string key)
{
JToken token = json;
foreach (var propertyName in key.Split(new[] { ':' }))
{
token = CaseSelectPropertyValues(token, propertyName);
}
token?.Parent?.Remove();
}
private void SaveJson(JsonConfigurationProvider provider, JObject json)
{
lock (_locker)
{
if (provider.Source.FileProvider is PhysicalFileProvider physicalFileProvider)
{
var jsonFilePath = Path.Combine(physicalFileProvider.Root, provider.Source.Path);
using (var sw = new StreamWriter(jsonFilePath, false))
using (var jsonTextWriter = new JsonTextWriter(sw)
{
Formatting = Formatting.Indented,
})
{
json?.WriteTo(jsonTextWriter);
}
}
}
}
private JObject GetJson(JsonConfigurationProvider provider)
{
lock (_locker)
{
if (provider.Source.FileProvider is PhysicalFileProvider physicalFileProvider)
{
var jsonFilePath = Path.Combine(physicalFileProvider.Root, provider.Source.Path);
var serializer = new JsonSerializer();
using (var sr = new StreamReader(jsonFilePath))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize<JObject>(jsonTextReader);
}
}
return null;
}
}
private JsonConfigurationProvider GetJsonConfigurationProvider(string requiredKey = null)
{
if (_configuration is IConfigurationRoot configurationRoot)
{
foreach (var provider in configurationRoot.Providers)
{
if (provider is JsonConfigurationProvider jsonConfigurationProvider)
{
if (requiredKey is null || provider.TryGet(requiredKey, out _))
{
return jsonConfigurationProvider;
}
}
}
}
throw new InvalidOperationException("Could not find a writable json config source");
}
/// <summary>
/// Returns the property value when case insensative
/// </summary>
/// <remarks>
/// This method is required because keys are case insensative in IConfiguration.
/// JObject[..] do not support case insensative and JObject.Property(...) do not return a new JObject.
/// </remarks>
private static JToken CaseSelectPropertyValues(JToken token, string name)
{
if (token is JObject obj)
{
foreach (var property in obj.Properties())
{
if (name is null)
return property.Value;
if (string.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase))
return property.Value;
}
}
return null;
}
}
}
| |
using Signum.Entities.Workflow;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Authorization;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Signum.Engine.Authorization;
using Signum.Entities.Dynamic;
using System.Text.RegularExpressions;
using Signum.Entities.Reflection;
using Signum.Engine.Basics;
using Signum.Engine;
namespace Signum.Engine.Workflow
{
public static class WorkflowLogic
{
public static Action<ICaseMainEntity, WorkflowTransitionContext>? OnTransition;
[AutoExpressionField]
public static bool HasExpired(this WorkflowEntity w) =>
As.Expression(() => w.ExpirationDate.HasValue && w.ExpirationDate.Value < TimeZoneManager.Now);
[AutoExpressionField]
public static IQueryable<WorkflowPoolEntity> WorkflowPools(this WorkflowEntity e) =>
As.Expression(() => Database.Query<WorkflowPoolEntity>().Where(a => a.Workflow == e));
[AutoExpressionField]
public static IQueryable<WorkflowActivityEntity> WorkflowActivities(this WorkflowEntity e) =>
As.Expression(() => Database.Query<WorkflowActivityEntity>().Where(a => a.Lane.Pool.Workflow == e));
public static IEnumerable<WorkflowActivityEntity> WorkflowActivitiesFromCache(this WorkflowEntity e)
{
return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowActivityEntity>();
}
[AutoExpressionField]
public static IQueryable<WorkflowEventEntity> WorkflowEvents(this WorkflowEntity e) =>
As.Expression(() => Database.Query<WorkflowEventEntity>().Where(a => a.Lane.Pool.Workflow == e));
[AutoExpressionField]
public static WorkflowEventEntity WorkflowStartEvent(this WorkflowEntity e) =>
As.Expression(() => e.WorkflowEvents().Where(we => we.Type == WorkflowEventType.Start).SingleOrDefault());
public static IEnumerable<WorkflowEventEntity> WorkflowEventsFromCache(this WorkflowEntity e)
{
return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowEventEntity>();
}
[AutoExpressionField]
public static IQueryable<WorkflowGatewayEntity> WorkflowGateways(this WorkflowEntity e) =>
As.Expression(() => Database.Query<WorkflowGatewayEntity>().Where(a => a.Lane.Pool.Workflow == e));
public static IEnumerable<WorkflowGatewayEntity> WorkflowGatewaysFromCache(this WorkflowEntity e)
{
return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowGatewayEntity>();
}
[AutoExpressionField]
public static IQueryable<WorkflowConnectionEntity> WorkflowConnections(this WorkflowEntity e) =>
As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From.Lane.Pool.Workflow == e && a.To.Lane.Pool.Workflow == e));
public static IEnumerable<WorkflowConnectionEntity> WorkflowConnectionsFromCache(this WorkflowEntity e)
{
return GetWorkflowNodeGraph(e.ToLite()).NextGraph.EdgesWithValue.SelectMany(edge => edge.Value);
}
[AutoExpressionField]
public static IQueryable<WorkflowConnectionEntity> WorkflowMessageConnections(this WorkflowEntity e) =>
As.Expression(() => e.WorkflowConnections().Where(a => a.From.Lane.Pool != a.To.Lane.Pool));
[AutoExpressionField]
public static IQueryable<WorkflowLaneEntity> WorkflowLanes(this WorkflowPoolEntity e) =>
As.Expression(() => Database.Query<WorkflowLaneEntity>().Where(a => a.Pool == e));
[AutoExpressionField]
public static IQueryable<WorkflowConnectionEntity> WorkflowConnections(this WorkflowPoolEntity e) =>
As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From.Lane.Pool == e && a.To.Lane.Pool == e));
[AutoExpressionField]
public static IQueryable<WorkflowGatewayEntity> WorkflowGateways(this WorkflowLaneEntity e) =>
As.Expression(() => Database.Query<WorkflowGatewayEntity>().Where(a => a.Lane == e));
[AutoExpressionField]
public static IQueryable<WorkflowEventEntity> WorkflowEvents(this WorkflowLaneEntity e) =>
As.Expression(() => Database.Query<WorkflowEventEntity>().Where(a => a.Lane == e));
[AutoExpressionField]
public static IQueryable<WorkflowActivityEntity> WorkflowActivities(this WorkflowLaneEntity e) =>
As.Expression(() => Database.Query<WorkflowActivityEntity>().Where(a => a.Lane == e));
[AutoExpressionField]
public static IQueryable<WorkflowConnectionEntity> NextConnections(this IWorkflowNodeEntity e) =>
As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From == e));
[AutoExpressionField]
public static WorkflowEntity Workflow(this CaseActivityEntity ca) =>
As.Expression(() => ca.WorkflowActivity.Lane.Pool.Workflow);
public static IEnumerable<WorkflowConnectionEntity> NextConnectionsFromCache(this IWorkflowNodeEntity e, ConnectionType? type)
{
var result = GetWorkflowNodeGraph(e.Lane.Pool.Workflow.ToLite()).NextConnections(e);
if (type == null)
return result;
return result.Where(a => a.Type == type);
}
[AutoExpressionField]
public static IQueryable<WorkflowConnectionEntity> PreviousConnections(this IWorkflowNodeEntity e) =>
As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.To == e));
public static IEnumerable<WorkflowConnectionEntity> PreviousConnectionsFromCache(this IWorkflowNodeEntity e)
{
return GetWorkflowNodeGraph(e.Lane.Pool.Workflow.ToLite()).PreviousConnections(e);
}
public static ResetLazy<Dictionary<Lite<WorkflowEntity>, WorkflowNodeGraph>> WorkflowGraphLazy = null!;
public static List<Lite<IWorkflowNodeEntity>> AutocompleteNodes(Lite<WorkflowEntity> workflow, string subString, int count, List<Lite<IWorkflowNodeEntity>> excludes)
{
return WorkflowGraphLazy.Value.GetOrThrow(workflow).Autocomplete(subString, count, excludes);
}
public static WorkflowNodeGraph GetWorkflowNodeGraph(Lite<WorkflowEntity> workflow)
{
var graph = WorkflowGraphLazy.Value.GetOrThrow(workflow);
if (graph.TrackId != null)
return graph;
lock (graph)
{
if (graph.TrackId != null)
return graph;
var issues = new List<WorkflowIssue>();
graph.Validate(issues, (g, newDirection) =>
{
throw new InvalidOperationException($"Unexpected direction of gateway '{g}' (Should be '{newDirection.NiceToString()}'). Consider saving Workflow '{workflow}'.");
});
var errors = issues.Where(a => a.Type == WorkflowIssueType.Error);
if (errors.HasItems())
throw new ApplicationException("Errors in Workflow '" + workflow + "':\r\n" + errors.ToString("\r\n").Indent(4));
return graph;
}
}
static Func<WorkflowConfigurationEmbedded> getConfiguration = null!;
public static WorkflowConfigurationEmbedded Configuration
{
get { return getConfiguration(); }
}
static Regex CurrentIsRegex = new Regex($@"{nameof(WorkflowActivityInfo)}\s*\.\s*{nameof(WorkflowActivityInfo.Current)}\s*\.\s*{nameof(WorkflowActivityInfo.Is)}\s*\(\s*""(?<workflowName>[^""]*)""\s*,\s*""(?<activityName>[^""]*)""\s*\)");
internal static List<CustomCompilerError> GetCustomErrors(string code)
{
var matches = CurrentIsRegex.Matches(code).Cast<Match>().ToList();
return matches.Select(m =>
{
var workflowName = m.Groups["workflowName"].Value;
var wa = WorkflowLogic.WorkflowGraphLazy.Value.Values.SingleOrDefault(w => w.Workflow.Name == workflowName);
if (wa == null)
return CreateCompilerError(code, m, $"No workflow with Name '{workflowName}' found.");
var activityName = m.Groups["activityName"].Value;
if (!wa.Activities.Values.Any(a => a.Name == activityName))
return CreateCompilerError(code, m, $"No activity with Name '{activityName}' found in workflow '{workflowName}'.");
return null;
}).NotNull().ToList();
}
private static CustomCompilerError CreateCompilerError(string code, Match m, string errorText)
{
int index = 0;
int line = 1;
while (true)
{
var newIndex = code.IndexOf('\n', index + 1);
if (newIndex >= m.Index || newIndex == -1)
return new CustomCompilerError { ErrorText = errorText, Line = line };
index = newIndex;
line++;
}
}
public static void Start(SchemaBuilder sb, Func<WorkflowConfigurationEmbedded> getConfiguration)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
PermissionAuthLogic.RegisterPermissions(WorkflowPermission.ViewWorkflowPanel);
PermissionAuthLogic.RegisterPermissions(WorkflowPermission.ViewCaseFlow);
WorkflowLogic.getConfiguration = getConfiguration;
sb.Include<WorkflowEntity>()
.WithConstruct(WorkflowOperation.Create)
.WithQuery(() => DynamicQueryCore.Auto(
from e in Database.Query<WorkflowEntity>()
select new
{
Entity = e,
e.Id,
e.Name,
e.MainEntityType,
HasExpired = e.HasExpired(),
e.ExpirationDate,
})
.ColumnDisplayName(a => a.HasExpired, () => WorkflowMessage.HasExpired.NiceToString()))
.WithExpressionFrom((CaseActivityEntity ca) => ca.Workflow());
WorkflowGraph.Register();
QueryLogic.Expressions.Register((WorkflowEntity wf) => wf.WorkflowStartEvent());
QueryLogic.Expressions.Register((WorkflowEntity wf) => wf.HasExpired(), () => WorkflowMessage.HasExpired.NiceToString());
sb.AddIndex((WorkflowEntity wf) => wf.ExpirationDate);
DynamicCode.GetCustomErrors += GetCustomErrors;
sb.Include<WorkflowPoolEntity>()
.WithUniqueIndex(wp => new { wp.Workflow, wp.Name })
.WithSave(WorkflowPoolOperation.Save)
.WithDelete(WorkflowPoolOperation.Delete)
.WithExpressionFrom((WorkflowEntity p) => p.WorkflowPools())
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.BpmnElementId,
e.Workflow,
});
sb.Include<WorkflowLaneEntity>()
.WithUniqueIndex(wp => new { wp.Pool, wp.Name })
.WithSave(WorkflowLaneOperation.Save)
.WithDelete(WorkflowLaneOperation.Delete)
.WithExpressionFrom((WorkflowPoolEntity p) => p.WorkflowLanes())
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.BpmnElementId,
e.Pool,
e.Pool.Workflow,
});
sb.Include<WorkflowActivityEntity>()
.WithUniqueIndex(w => new { w.Lane, w.Name })
.WithSave(WorkflowActivityOperation.Save)
.WithDelete(WorkflowActivityOperation.Delete)
.WithExpressionFrom((WorkflowEntity p) => p.WorkflowActivities())
.WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowActivities())
.WithVirtualMList(wa => wa.BoundaryTimers, e => e.BoundaryOf, WorkflowEventOperation.Save, WorkflowEventOperation.Delete)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.BpmnElementId,
e.Comments,
e.Lane,
e.Lane.Pool.Workflow,
});
sb.Include<WorkflowEventEntity>()
.WithExpressionFrom((WorkflowEntity p) => p.WorkflowEvents())
.WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowEvents())
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Type,
e.Name,
e.BpmnElementId,
e.Lane,
e.Lane.Pool.Workflow,
});
new Graph<WorkflowEventEntity>.Execute(WorkflowEventOperation.Save)
{
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) => {
if (e.Timer == null && e.Type.IsTimer())
throw new InvalidOperationException(ValidationMessage._0IsMandatoryWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.Timer), e.NicePropertyName(a => a.Type), e.Type.NiceToString()));
if (e.Timer != null && !e.Type.IsTimer())
throw new InvalidOperationException(ValidationMessage._0ShouldBeNullWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.Timer), e.NicePropertyName(a => a.Type), e.Type.NiceToString()));
if (e.BoundaryOf == null && e.Type.IsBoundaryTimer())
throw new InvalidOperationException(ValidationMessage._0IsMandatoryWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.BoundaryOf), e.NicePropertyName(a => a.Type), e.Type.NiceToString()));
if (e.BoundaryOf != null && !e.Type.IsBoundaryTimer())
throw new InvalidOperationException(ValidationMessage._0ShouldBeNullWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.BoundaryOf), e.NicePropertyName(a => a.Type), e.Type.NiceToString()));
e.Save();
},
}.Register();
new Graph<WorkflowEventEntity>.Delete(WorkflowEventOperation.Delete)
{
Delete = (e, _) =>
{
if (e.Type.IsScheduledStart())
{
var scheduled = e.ScheduledTask();
if (scheduled != null)
WorkflowEventTaskLogic.DeleteWorkflowEventScheduledTask(scheduled);
}
e.Delete();
},
}.Register();
sb.Include<WorkflowGatewayEntity>()
.WithSave(WorkflowGatewayOperation.Save)
.WithDelete(WorkflowGatewayOperation.Delete)
.WithExpressionFrom((WorkflowEntity p) => p.WorkflowGateways())
.WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowGateways())
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Type,
e.Name,
e.BpmnElementId,
e.Lane,
e.Lane.Pool.Workflow,
});
sb.Include<WorkflowConnectionEntity>()
.WithSave(WorkflowConnectionOperation.Save)
.WithDelete(WorkflowConnectionOperation.Delete)
.WithExpressionFrom((WorkflowEntity p) => p.WorkflowConnections())
.WithExpressionFrom((WorkflowEntity p) => p.WorkflowMessageConnections(), null!)
.WithExpressionFrom((WorkflowPoolEntity p) => p.WorkflowConnections())
.WithExpressionFrom((IWorkflowNodeEntity p) => p.NextConnections(), null!)
.WithExpressionFrom((IWorkflowNodeEntity p) => p.PreviousConnections(), null!)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.BpmnElementId,
e.From,
e.To,
});
WorkflowEventTaskEntity.GetWorkflowEntity = lite => WorkflowGraphLazy.Value.GetOrThrow(lite).Workflow;
WorkflowGraphLazy = sb.GlobalLazy(() =>
{
using (new EntityCache())
{
var events = Database.RetrieveAll<WorkflowEventEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite());
var gateways = Database.RetrieveAll<WorkflowGatewayEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite());
var activities = Database.RetrieveAll<WorkflowActivityEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite());
var connections = Database.RetrieveAll<WorkflowConnectionEntity>().GroupToDictionary(a => a.From.Lane.Pool.Workflow.ToLite());
var result = Database.RetrieveAll<WorkflowEntity>().ToDictionary(workflow => workflow.ToLite(), workflow =>
{
var w = workflow.ToLite();
var nodeGraph = new WorkflowNodeGraph
{
Workflow = workflow,
Events = events.TryGetC(w).EmptyIfNull().ToDictionary(e => e.ToLite()),
Gateways = gateways.TryGetC(w).EmptyIfNull().ToDictionary(g => g.ToLite()),
Activities = activities.TryGetC(w).EmptyIfNull().ToDictionary(a => a.ToLite()),
Connections = connections.TryGetC(w).EmptyIfNull().ToDictionary(c => c.ToLite()),
};
nodeGraph.FillGraphs();
return nodeGraph;
});
return result;
}
}, new InvalidateWith(typeof(WorkflowConnectionEntity)));
WorkflowGraphLazy.OnReset += (e, args) => DynamicCode.OnInvalidated?.Invoke();
Validator.PropertyValidator((WorkflowConnectionEntity c) => c.Condition).StaticPropertyValidation = (e, pi) =>
{
if (e.Condition != null && e.From != null)
{
var conditionType = Conditions.Value.GetOrThrow(e.Condition).MainEntityType;
var workflowType = e.From.Lane.Pool.Workflow.MainEntityType;
if (!conditionType.Is(workflowType))
return WorkflowMessage.Condition0IsDefinedFor1Not2.NiceToString(conditionType, workflowType);
}
return null;
};
StartWorkflowConditions(sb);
StartWorkflowTimerConditions(sb);
StartWorkflowActions(sb);
StartWorkflowScript(sb);
}
}
public static ResetLazy<Dictionary<Lite<WorkflowTimerConditionEntity>, WorkflowTimerConditionEntity>> TimerConditions = null!;
public static WorkflowTimerConditionEntity RetrieveFromCache(this Lite<WorkflowTimerConditionEntity> wc) => TimerConditions.Value.GetOrThrow(wc);
private static void StartWorkflowTimerConditions(SchemaBuilder sb)
{
sb.Include<WorkflowTimerConditionEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.MainEntityType,
e.Eval.Script
});
new Graph<WorkflowTimerConditionEntity>.Execute(WorkflowTimerConditionOperation.Save)
{
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) =>
{
if (!e.IsNew)
{
var oldMainEntityType = e.InDB(a => a.MainEntityType);
if (!oldMainEntityType.Is(e.MainEntityType))
ThrowConnectionError(Database.Query<WorkflowEventEntity>().Where(a => a.Timer!.Condition == e.ToLite()), e, WorkflowTimerConditionOperation.Save);
}
e.Save();
},
}.Register();
new Graph<WorkflowTimerConditionEntity>.Delete(WorkflowTimerConditionOperation.Delete)
{
Delete = (e, _) =>
{
ThrowConnectionError(Database.Query<WorkflowEventEntity>().Where(a => a.Timer!.Condition == e.ToLite()), e, WorkflowTimerConditionOperation.Delete);
e.Delete();
},
}.Register();
new Graph<WorkflowTimerConditionEntity>.ConstructFrom<WorkflowTimerConditionEntity>(WorkflowTimerConditionOperation.Clone)
{
Construct = (e, args) =>
{
return new WorkflowTimerConditionEntity
{
MainEntityType = e.MainEntityType,
Eval = new WorkflowTimerConditionEval { Script = e.Eval.Script }
};
},
}.Register();
TimerConditions = sb.GlobalLazy(() => Database.Query<WorkflowTimerConditionEntity>().ToDictionary(a => a.ToLite()),
new InvalidateWith(typeof(WorkflowTimerConditionEntity)));
}
public static ResetLazy<Dictionary<Lite<WorkflowActionEntity>, WorkflowActionEntity>> Actions = null!;
public static WorkflowActionEntity RetrieveFromCache(this Lite<WorkflowActionEntity> wa) => Actions.Value.GetOrThrow(wa);
private static void StartWorkflowActions(SchemaBuilder sb)
{
sb.Include<WorkflowActionEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.MainEntityType,
e.Eval.Script
});
new Graph<WorkflowActionEntity>.Execute(WorkflowActionOperation.Save)
{
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) =>
{
if (!e.IsNew)
{
var oldMainEntityType = e.InDB(a => a.MainEntityType);
if (!oldMainEntityType.Is(e.MainEntityType))
ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Action == e.ToLite()), e, WorkflowActionOperation.Save);
}
e.Save();
},
}.Register();
new Graph<WorkflowActionEntity>.Delete(WorkflowActionOperation.Delete)
{
Delete = (e, _) =>
{
ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Action == e.ToLite()), e, WorkflowActionOperation.Delete);
e.Delete();
},
}.Register();
new Graph<WorkflowActionEntity>.ConstructFrom<WorkflowActionEntity>(WorkflowActionOperation.Clone)
{
Construct = (e, args) =>
{
return new WorkflowActionEntity
{
MainEntityType = e.MainEntityType,
Eval = new WorkflowActionEval { Script = e.Eval.Script }
};
},
}.Register();
Actions = sb.GlobalLazy(() => Database.Query<WorkflowActionEntity>().ToDictionary(a => a.ToLite()),
new InvalidateWith(typeof(WorkflowActionEntity)));
}
public static ResetLazy<Dictionary<Lite<WorkflowConditionEntity>, WorkflowConditionEntity>> Conditions = null!;
public static WorkflowConditionEntity RetrieveFromCache(this Lite<WorkflowConditionEntity> wc) => Conditions.Value.GetOrThrow(wc);
private static void StartWorkflowConditions(SchemaBuilder sb)
{
sb.Include<WorkflowConditionEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.MainEntityType,
e.Eval.Script
});
new Graph<WorkflowConditionEntity>.Execute(WorkflowConditionOperation.Save)
{
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) =>
{
if (!e.IsNew) {
var oldMainEntityType = e.InDB(a => a.MainEntityType);
if (!oldMainEntityType.Is(e.MainEntityType))
ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Condition == e.ToLite()), e, WorkflowConditionOperation.Save);
}
e.Save();
},
}.Register();
new Graph<WorkflowConditionEntity>.Delete(WorkflowConditionOperation.Delete)
{
Delete = (e, _) =>
{
ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Condition == e.ToLite()), e, WorkflowConditionOperation.Delete);
e.Delete();
},
}.Register();
new Graph<WorkflowConditionEntity>.ConstructFrom<WorkflowConditionEntity>(WorkflowConditionOperation.Clone)
{
Construct = (e, args) =>
{
return new WorkflowConditionEntity
{
MainEntityType = e.MainEntityType,
Eval = new WorkflowConditionEval { Script = e.Eval.Script }
};
},
}.Register();
Conditions = sb.GlobalLazy(() => Database.Query<WorkflowConditionEntity>().ToDictionary(a => a.ToLite()),
new InvalidateWith(typeof(WorkflowConditionEntity)));
}
public static ResetLazy<Dictionary<Lite<WorkflowScriptEntity>, WorkflowScriptEntity>> Scripts = null!;
public static WorkflowScriptEntity RetrieveFromCache(this Lite<WorkflowScriptEntity> ws)=> Scripts.Value.GetOrThrow(ws);
private static void StartWorkflowScript(SchemaBuilder sb)
{
sb.Include<WorkflowScriptEntity>()
.WithQuery(() => s => new
{
Entity = s,
s.Id,
s.Name,
s.MainEntityType,
});
new Graph<WorkflowScriptEntity>.Execute(WorkflowScriptOperation.Save)
{
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) =>
{
if (!e.IsNew)
{
var oldMainEntityType = e.InDB(a => a.MainEntityType);
if (!oldMainEntityType.Is(e.MainEntityType))
ThrowConnectionError(Database.Query<WorkflowActivityEntity>().Where(a => a.Script!.Script == e.ToLite()), e, WorkflowScriptOperation.Save);
}
e.Save();
},
}.Register();
new Graph<WorkflowScriptEntity>.ConstructFrom<WorkflowScriptEntity>(WorkflowScriptOperation.Clone)
{
Construct = (s, _) => new WorkflowScriptEntity() {
MainEntityType = s.MainEntityType,
Eval = new WorkflowScriptEval() { Script = s.Eval.Script }
}
}.Register();
new Graph<WorkflowScriptEntity>.Delete(WorkflowScriptOperation.Delete)
{
Delete = (s, _) =>
{
ThrowConnectionError(Database.Query<WorkflowActivityEntity>().Where(a => a.Script!.Script == s.ToLite()), s, WorkflowScriptOperation.Delete);
s.Delete();
},
}.Register();
Scripts = sb.GlobalLazy(() => Database.Query<WorkflowScriptEntity>().ToDictionary(a => a.ToLite()),
new InvalidateWith(typeof(WorkflowScriptEntity)));
sb.Include<WorkflowScriptRetryStrategyEntity>()
.WithSave(WorkflowScriptRetryStrategyOperation.Save)
.WithDelete(WorkflowScriptRetryStrategyOperation.Delete)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Rule
});
}
private static void ThrowConnectionError(IQueryable<WorkflowConnectionEntity> queryable, Entity entity, IOperationSymbolContainer operation)
{
if (queryable.Count() == 0)
return;
var errors = queryable.Select(a => new { Connection = a.ToLite(), From = a.From.ToLite(), To = a.To.ToLite(), Workflow = a.From.Lane.Pool.Workflow.ToLite() }).ToList();
var formattedErrors = errors.GroupBy(a => a.Workflow).ToString(gr => $"Workflow '{gr.Key}':" +
gr.ToString(a => $"Connection {a.Connection!.Id} ({a.Connection}): {a.From} -> {a.To}", "\r\n").Indent(4),
"\r\n\r\n").Indent(4);
throw new ApplicationException($"Impossible to {operation.Symbol.Key.After('.')} '{entity}' because is used in some connections: \r\n" + formattedErrors);
}
private static void ThrowConnectionError<T>(IQueryable<T> queryable, Entity entity, IOperationSymbolContainer operation)
where T : Entity, IWorkflowNodeEntity
{
if (queryable.Count() == 0)
return;
var errors = queryable.Select(a => new { Entity = a.ToLite(), Workflow = a.Lane.Pool.Workflow.ToLite() }).ToList();
var formattedErrors = errors.GroupBy(a => a.Workflow).ToString(gr => $"Workflow '{gr.Key}':" +
gr.ToString(a => $"{typeof(T).NiceName()} {a.Entity}", "\r\n").Indent(4),
"\r\n\r\n").Indent(4);
throw new ApplicationException($"Impossible to {operation.Symbol.Key.After('.')} '{entity}' because is used in some {typeof(T).NicePluralName()}: \r\n" + formattedErrors);
}
public class WorkflowGraph : Graph<WorkflowEntity>
{
public static void Register()
{
new Execute(WorkflowOperation.Save)
{
CanBeNew = true,
CanBeModified = true,
Execute = (e, args) =>
{
WorkflowLogic.ApplyDocument(e, args.GetArg<WorkflowModel>(), args.TryGetArgC<WorkflowReplacementModel>(), args.TryGetArgC<List<WorkflowIssue>>() ?? new List<WorkflowIssue>());
DynamicCode.OnInvalidated?.Invoke();
}
}.Register();
new ConstructFrom<WorkflowEntity>(WorkflowOperation.Clone)
{
Construct = (w, args) =>
{
WorkflowBuilder wb = new WorkflowBuilder(w);
var result = wb.Clone();
return result;
}
}.Register();
new Delete(WorkflowOperation.Delete)
{
CanDelete = w =>
{
var usedWorkflows = Database.Query<CaseEntity>()
.Where(c => c.Workflow.Is(w) && c.ParentCase != null)
.Select(c => c.ParentCase!.Workflow)
.ToList();
if (usedWorkflows.Any())
return WorkflowMessage.WorkflowUsedIn0ForDecompositionOrCallWorkflow.NiceToString(usedWorkflows.ToString(", "));
return null;
},
Delete = (w, _) =>
{
var wb = new WorkflowBuilder(w);
wb.Delete();
DynamicCode.OnInvalidated?.Invoke();
}
}.Register();
new Execute(WorkflowOperation.Activate)
{
CanExecute = w => w.HasExpired() ? null : WorkflowMessage.Workflow0AlreadyActivated.NiceToString(w),
Execute = (w, _) =>
{
w.ExpirationDate = null;
w.Save();
w.SuspendWorkflowScheduledTasks(false);
}
}.Register();
new Execute(WorkflowOperation.Deactivate)
{
CanExecute = w => w.HasExpired() ? WorkflowMessage.Workflow0HasExpiredOn1.NiceToString(w, w.ExpirationDate!.Value.ToString()) :
w.Cases().SelectMany(c => c.CaseActivities()).Any(ca => ca.DoneDate == null) ? CaseActivityMessage.ThereAreInprogressActivities.NiceToString() : null,
Execute = (w, args) =>
{
w.ExpirationDate = args.GetArg<DateTime>();
w.Save();
w.SuspendWorkflowScheduledTasks(true);
}
}.Register();
}
}
public static void SuspendWorkflowScheduledTasks(this WorkflowEntity workflow, bool value)
{
workflow.WorkflowEvents()
.Where(a => a.Type == WorkflowEventType.ScheduledStart)
.Select(a => a.ScheduledTask())
.UnsafeUpdate()
.Set(a => a.Suspended, a => value)
.Execute();
}
public static Expression<Func<UserEntity, Lite<Entity>, bool>> IsUserConstantActor = (userConstant, actor) =>
actor.Is(userConstant) ||
(actor is Lite<RoleEntity> && AuthLogic.IndirectlyRelated(userConstant.Role).Contains((Lite<RoleEntity>)actor));
public static Expression<Func<UserEntity, Lite<Entity>, bool>> IsUserActorConstant = (user, actorConstant) =>
actorConstant.Is(user) ||
(actorConstant is Lite<RoleEntity> && AuthLogic.InverseIndirectlyRelated((Lite<RoleEntity>)actorConstant).Contains(user.Role));
public static List<WorkflowEntity> GetAllowedStarts()
{
return (from w in Database.Query<WorkflowEntity>()
let s = w.WorkflowEvents().Single(a => a.Type == WorkflowEventType.Start)
let a = (WorkflowActivityEntity)s.NextConnections().Single().To
where !w.HasExpired() && a.Lane.Actors.Any(b => IsUserConstantActor.Evaluate(UserEntity.Current, b))
select w).ToList();
}
public static WorkflowModel GetWorkflowModel(WorkflowEntity workflow)
{
var wb = new WorkflowBuilder(workflow);
return wb.GetWorkflowModel();
}
public static PreviewResult PreviewChanges(WorkflowEntity workflow, WorkflowModel model)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
var document = WorkflowBuilder.ParseDocument(model.DiagramXml);
var wb = new WorkflowBuilder(workflow);
return wb.PreviewChanges(document, model);
}
public static void ApplyDocument(WorkflowEntity workflow, WorkflowModel model, WorkflowReplacementModel? replacements, List<WorkflowIssue> issuesContainer)
{
if (issuesContainer.Any())
throw new InvalidOperationException("issuesContainer should be empty");
if (model == null)
throw new ArgumentNullException(nameof(model));
var wb = new WorkflowBuilder(workflow);
if (workflow.IsNew)
workflow.Save();
wb.ApplyChanges(model, replacements);
wb.ValidateGraph(issuesContainer);
if (issuesContainer.Any(a => a.Type == WorkflowIssueType.Error))
throw new IntegrityCheckException(new Dictionary<Guid, IntegrityCheck>());
workflow.FullDiagramXml = new WorkflowXmlEmbedded { DiagramXml = wb.GetXDocument().ToString() };
workflow.Save();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Framework.Serialization.External
{
/// <summary>
/// Serialize and deserialize LandData as an external format.
/// </summary>
public class LandDataSerializer
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Dictionary<string, Action<LandData, XmlTextReader>> m_ldProcessors
= new Dictionary<string, Action<LandData, XmlTextReader>>();
private static Dictionary<string, Action<LandAccessEntry, XmlTextReader>> m_laeProcessors
= new Dictionary<string, Action<LandAccessEntry, XmlTextReader>>();
static LandDataSerializer()
{
// LandData processors
m_ldProcessors.Add(
"Area", (ld, xtr) => ld.Area = Convert.ToInt32(xtr.ReadElementString("Area")));
m_ldProcessors.Add(
"AuctionID", (ld, xtr) => ld.AuctionID = Convert.ToUInt32(xtr.ReadElementString("AuctionID")));
m_ldProcessors.Add(
"AuthBuyerID", (ld, xtr) => ld.AuthBuyerID = UUID.Parse(xtr.ReadElementString("AuthBuyerID")));
m_ldProcessors.Add(
"Category", (ld, xtr) => ld.Category = (ParcelCategory)Convert.ToSByte(xtr.ReadElementString("Category")));
m_ldProcessors.Add(
"ClaimDate", (ld, xtr) => ld.ClaimDate = Convert.ToInt32(xtr.ReadElementString("ClaimDate")));
m_ldProcessors.Add(
"ClaimPrice", (ld, xtr) => ld.ClaimPrice = Convert.ToInt32(xtr.ReadElementString("ClaimPrice")));
m_ldProcessors.Add(
"GlobalID", (ld, xtr) => ld.GlobalID = UUID.Parse(xtr.ReadElementString("GlobalID")));
m_ldProcessors.Add(
"GroupID", (ld, xtr) => ld.GroupID = UUID.Parse(xtr.ReadElementString("GroupID")));
m_ldProcessors.Add(
"IsGroupOwned", (ld, xtr) => ld.IsGroupOwned = Convert.ToBoolean(xtr.ReadElementString("IsGroupOwned")));
m_ldProcessors.Add(
"Bitmap", (ld, xtr) => ld.Bitmap = Convert.FromBase64String(xtr.ReadElementString("Bitmap")));
m_ldProcessors.Add(
"Description", (ld, xtr) => ld.Description = xtr.ReadElementString("Description"));
m_ldProcessors.Add(
"Flags", (ld, xtr) => ld.Flags = Convert.ToUInt32(xtr.ReadElementString("Flags")));
m_ldProcessors.Add(
"LandingType", (ld, xtr) => ld.LandingType = Convert.ToByte(xtr.ReadElementString("LandingType")));
m_ldProcessors.Add(
"Name", (ld, xtr) => ld.Name = xtr.ReadElementString("Name"));
m_ldProcessors.Add(
"Status", (ld, xtr) => ld.Status = (ParcelStatus)Convert.ToSByte(xtr.ReadElementString("Status")));
m_ldProcessors.Add(
"LocalID", (ld, xtr) => ld.LocalID = Convert.ToInt32(xtr.ReadElementString("LocalID")));
m_ldProcessors.Add(
"MediaAutoScale", (ld, xtr) => ld.MediaAutoScale = Convert.ToByte(xtr.ReadElementString("MediaAutoScale")));
m_ldProcessors.Add(
"MediaID", (ld, xtr) => ld.MediaID = UUID.Parse(xtr.ReadElementString("MediaID")));
m_ldProcessors.Add(
"MediaURL", (ld, xtr) => ld.MediaURL = xtr.ReadElementString("MediaURL"));
m_ldProcessors.Add(
"MusicURL", (ld, xtr) => ld.MusicURL = xtr.ReadElementString("MusicURL"));
m_ldProcessors.Add(
"OwnerID", (ld, xtr) => ld.OwnerID = UUID.Parse(xtr.ReadElementString("OwnerID")));
m_ldProcessors.Add(
"ParcelAccessList", ProcessParcelAccessList);
m_ldProcessors.Add(
"PassHours", (ld, xtr) => ld.PassHours = Convert.ToSingle(xtr.ReadElementString("PassHours")));
m_ldProcessors.Add(
"PassPrice", (ld, xtr) => ld.PassPrice = Convert.ToInt32(xtr.ReadElementString("PassPrice")));
m_ldProcessors.Add(
"SalePrice", (ld, xtr) => ld.SalePrice = Convert.ToInt32(xtr.ReadElementString("SalePrice")));
m_ldProcessors.Add(
"SnapshotID", (ld, xtr) => ld.SnapshotID = UUID.Parse(xtr.ReadElementString("SnapshotID")));
m_ldProcessors.Add(
"UserLocation", (ld, xtr) => ld.UserLocation = Vector3.Parse(xtr.ReadElementString("UserLocation")));
m_ldProcessors.Add(
"UserLookAt", (ld, xtr) => ld.UserLookAt = Vector3.Parse(xtr.ReadElementString("UserLookAt")));
// No longer used here //
// m_ldProcessors.Add("Dwell", (landData, xtr) => return);
m_ldProcessors.Add(
"OtherCleanTime", (ld, xtr) => ld.OtherCleanTime = Convert.ToInt32(xtr.ReadElementString("OtherCleanTime")));
// LandAccessEntryProcessors
m_laeProcessors.Add(
"AgentID", (lae, xtr) => lae.AgentID = UUID.Parse(xtr.ReadElementString("AgentID")));
m_laeProcessors.Add(
"Time", (lae, xtr) =>
{
// We really don't care about temp vs perm here and this
// would break on old oars. Assume all bans are perm
xtr.ReadElementString("Time");
lae.Expires = 0; // Convert.ToUint( xtr.ReadElementString("Time"));
}
);
m_laeProcessors.Add(
"AccessList", (lae, xtr) => lae.Flags = (AccessList)Convert.ToUInt32(xtr.ReadElementString("AccessList")));
}
public static void ProcessParcelAccessList(LandData ld, XmlTextReader xtr)
{
if (!xtr.IsEmptyElement)
{
while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement)
{
LandAccessEntry lae = new LandAccessEntry();
xtr.ReadStartElement("ParcelAccessEntry");
ExternalRepresentationUtils.ExecuteReadProcessors<LandAccessEntry>(lae, m_laeProcessors, xtr);
xtr.ReadEndElement();
ld.ParcelAccessList.Add(lae);
}
}
xtr.Read();
}
/// <summary>
/// Reify/deserialize landData
/// </summary>
/// <param name="serializedLandData"></param>
/// <returns></returns>
/// <exception cref="System.Xml.XmlException"></exception>
public static LandData Deserialize(byte[] serializedLandData)
{
return Deserialize(Encoding.UTF8.GetString(serializedLandData, 0, serializedLandData.Length));
}
/// <summary>
/// Reify/deserialize landData
/// </summary>
/// <param name="serializedLandData"></param>
/// <returns></returns>
/// <exception cref="System.Xml.XmlException"></exception>
public static LandData Deserialize(string serializedLandData)
{
LandData landData = new LandData();
using (XmlTextReader reader = new XmlTextReader(new StringReader(serializedLandData)))
{
reader.ReadStartElement("LandData");
ExternalRepresentationUtils.ExecuteReadProcessors<LandData>(landData, m_ldProcessors, reader);
reader.ReadEndElement();
}
return landData;
}
/// <summary>
/// Serialize land data
/// </summary>
/// <param name='landData'></param>
/// <param name='options'>
/// Serialization options.
/// Can be null if there are no options.
/// "wipe-owners" will write UUID.Zero rather than the ownerID so that a later reload loads all parcels with the estate owner as the owner
/// </param>
public static string Serialize(LandData landData, Dictionary<string, object> options)
{
StringWriter sw = new StringWriter();
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument();
xtw.WriteStartElement("LandData");
xtw.WriteElementString("Area", Convert.ToString(landData.Area));
xtw.WriteElementString("AuctionID", Convert.ToString(landData.AuctionID));
xtw.WriteElementString("AuthBuyerID", landData.AuthBuyerID.ToString());
xtw.WriteElementString("Category", Convert.ToString((sbyte)landData.Category));
xtw.WriteElementString("ClaimDate", Convert.ToString(landData.ClaimDate));
xtw.WriteElementString("ClaimPrice", Convert.ToString(landData.ClaimPrice));
xtw.WriteElementString("GlobalID", landData.GlobalID.ToString());
UUID groupID = options.ContainsKey("wipe-owners") ? UUID.Zero : landData.GroupID;
xtw.WriteElementString("GroupID", groupID.ToString());
bool isGroupOwned = options.ContainsKey("wipe-owners") ? false : landData.IsGroupOwned;
xtw.WriteElementString("IsGroupOwned", Convert.ToString(isGroupOwned));
xtw.WriteElementString("Bitmap", Convert.ToBase64String(landData.Bitmap));
xtw.WriteElementString("Description", landData.Description);
xtw.WriteElementString("Flags", Convert.ToString((uint)landData.Flags));
xtw.WriteElementString("LandingType", Convert.ToString((byte)landData.LandingType));
xtw.WriteElementString("Name", landData.Name);
xtw.WriteElementString("Status", Convert.ToString((sbyte)landData.Status));
xtw.WriteElementString("LocalID", landData.LocalID.ToString());
xtw.WriteElementString("MediaAutoScale", Convert.ToString(landData.MediaAutoScale));
xtw.WriteElementString("MediaID", landData.MediaID.ToString());
xtw.WriteElementString("MediaURL", landData.MediaURL);
xtw.WriteElementString("MusicURL", landData.MusicURL);
UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : landData.OwnerID;
xtw.WriteElementString("OwnerID", ownerID.ToString());
xtw.WriteStartElement("ParcelAccessList");
foreach (LandAccessEntry pal in landData.ParcelAccessList)
{
xtw.WriteStartElement("ParcelAccessEntry");
xtw.WriteElementString("AgentID", pal.AgentID.ToString());
xtw.WriteElementString("Time", pal.Expires.ToString());
xtw.WriteElementString("AccessList", Convert.ToString((uint)pal.Flags));
xtw.WriteEndElement();
}
xtw.WriteEndElement();
xtw.WriteElementString("PassHours", Convert.ToString(landData.PassHours));
xtw.WriteElementString("PassPrice", Convert.ToString(landData.PassPrice));
xtw.WriteElementString("SalePrice", Convert.ToString(landData.SalePrice));
xtw.WriteElementString("SnapshotID", landData.SnapshotID.ToString());
xtw.WriteElementString("UserLocation", landData.UserLocation.ToString());
xtw.WriteElementString("UserLookAt", landData.UserLookAt.ToString());
xtw.WriteElementString("Dwell", "0");
xtw.WriteElementString("OtherCleanTime", Convert.ToString(landData.OtherCleanTime));
xtw.WriteEndElement();
xtw.Close();
sw.Close();
return sw.ToString();
}
}
}
| |
///////////////////////////////////////////////////////////////
// FSXml - A library for representing file system data as //
// Xml. //
// Shukri Adams ([email protected]) //
// https://github.com/shukriadams/browsemonkey //
// MIT License (MIT) Copyright (c) 2014 Shukri Adams //
///////////////////////////////////////////////////////////////
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using vcFramework.IO.Streams;
namespace FSXml
{
/// <summary> Summary description for SharpZipWrap. </summary>
public class SharpZipWrapperLib
{
/// <summary> Zips an existing file </summary>
/// <param name="FileToZip"></param>
/// <param name="ZipedFile"></param>
/// <param name="CompressionLevel"></param>
/// <param name="BlockSize"></param>
public static void ZipFile(
string FileToZip,
string ZipedFile,
int CompressionLevel,
int BlockSize
)
{
FileStream StreamToZip = new FileStream(FileToZip,System.IO.FileMode.Open , System.IO.FileAccess.Read);
System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
ZipEntry ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(CompressionLevel);
byte[] buffer = new byte[BlockSize];
System.Int32 size =StreamToZip.Read(buffer,0,buffer.Length);
ZipStream.Write(buffer,0,size);
try
{
while (size < StreamToZip.Length)
{
int sizeRead =StreamToZip.Read(buffer,0,buffer.Length);
ZipStream.Write(buffer,0,sizeRead);
size += sizeRead;
}
}
catch(System.Exception ex)
{
throw ex;
}
ZipStream.Finish();
ZipStream.Close();
StreamToZip.Close();
}
/// <summary>
///
/// </summary>
/// <param name="inStream"></param>
/// <param name="compressionLevel"></param>
/// <param name="blockSize"></param>
/// <returns></returns>
public static Stream ZipStream(
Stream inStream,
int compressionLevel,
int blockSize
)
{
// "rewinds" instream
inStream.Seek(
0,
SeekOrigin.Begin);
// sets up streams to compress existing file
MemoryStream tempFileReader = new MemoryStream();
ZipOutputStream ZipStream = new ZipOutputStream(tempFileReader);
ZipEntry ZipEntry = new ZipEntry("ZippedStream");
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(compressionLevel);
// copies uncompressed stream into compressed stream
StreamsLib.StreamCopyAll(
(Stream)inStream,
(Stream)ZipStream,
blockSize);
ZipStream.Flush();
ZipStream.CloseEntry();
ZipStream.Finish();
tempFileReader.Flush();
string test = StreamsLib.BinaryStreamToString(tempFileReader, 128);
return tempFileReader;
}
/// <summary> </summary>
/// <param name="strFileAndPath"></param>
/// <returns></returns>
public static Stream GetUnzippedStream(
string strFileAndPath
)
{
ZipInputStream objZipStream = new ZipInputStream(File.OpenRead(strFileAndPath));
objZipStream. GetNextEntry();
return (Stream)objZipStream;
}
/// <summary> </summary>
/// <param name="inStream"></param>
/// <returns></returns>
public static Stream GetUnzippedStream(
Stream inStream,
int BlockSize
)
{
// "rewind" stream
inStream.Seek(0,SeekOrigin.Begin);
MemoryStream outStream = new MemoryStream();
ZipInputStream objZipStream = new ZipInputStream(inStream);
ZipEntry theEntry = null;
theEntry = objZipStream.GetNextEntry();
if (theEntry == null)
return null;
string strtest = theEntry.Name;
// objZipStream.GetNextEntry();
int size = 2048;
byte[] data = new byte[2048];
long lngtest = 0;
while (true)
{
size = objZipStream.Read(data, 0, data.Length);
if (size > 0)
{
lngtest = objZipStream.Position;
outStream.Write(data, 0, size);
}
else
{
break;
}
}
long test1 = inStream.Length;
long test2 = outStream.Length;
objZipStream.Flush();
objZipStream.Close();
return (Stream)outStream;
}
/// <summary> </summary>
/// <param name="strFileAndPath"></param>
public static void UnzipFile(
string strFileAndPath
)
{
ZipInputStream s = new ZipInputStream(File.OpenRead(strFileAndPath));
UnzipFile(s);
}
/// <summary> Unzips an existing zipped file </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void UnzipFile(
ZipInputStream s
)
{
//ZipInputStream s = new ZipInputStream(File.OpenRead(strFileAndPath));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
//Console.WriteLine(theEntry.Name);
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
// create directory
// Directory.CreateDirectory(directoryName);
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(theEntry.Name);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
}
}
}
| |
/*
* 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 mobileanalytics-2014-06-05.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.MobileAnalytics.Model;
using Amazon.MobileAnalytics.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.MobileAnalytics
{
/// <summary>
/// Implementation for accessing MobileAnalytics
///
/// Amazon Mobile Analytics is a service for collecting, visualizing, and understanding
/// app usage data at scale.
/// </summary>
public partial class AmazonMobileAnalyticsClient : AmazonServiceClient, IAmazonMobileAnalytics
{
#region Constructors
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonMobileAnalyticsClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonMobileAnalyticsConfig()) { }
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonMobileAnalyticsClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonMobileAnalyticsConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonMobileAnalyticsClient Configuration Object</param>
public AmazonMobileAnalyticsClient(AmazonMobileAnalyticsConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonMobileAnalyticsClient(AWSCredentials credentials)
: this(credentials, new AmazonMobileAnalyticsConfig())
{
}
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonMobileAnalyticsClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonMobileAnalyticsConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Credentials and an
/// AmazonMobileAnalyticsClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonMobileAnalyticsClient Configuration Object</param>
public AmazonMobileAnalyticsClient(AWSCredentials credentials, AmazonMobileAnalyticsConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonMobileAnalyticsConfig())
{
}
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonMobileAnalyticsConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonMobileAnalyticsClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonMobileAnalyticsClient Configuration Object</param>
public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonMobileAnalyticsConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonMobileAnalyticsConfig())
{
}
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonMobileAnalyticsConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonMobileAnalyticsClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonMobileAnalyticsClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonMobileAnalyticsClient Configuration Object</param>
public AmazonMobileAnalyticsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonMobileAnalyticsConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region PutEvents
/// <summary>
/// The PutEvents operation records one or more events. You can have up to 1,500 unique
/// custom events per app, any combination of up to 40 attributes and metrics per custom
/// event, and any number of attribute or metric values.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutEvents service method.</param>
///
/// <returns>The response from the PutEvents service method, as returned by MobileAnalytics.</returns>
/// <exception cref="Amazon.MobileAnalytics.Model.BadRequestException">
/// An exception object returned when a request fails.
/// </exception>
public PutEventsResponse PutEvents(PutEventsRequest request)
{
var marshaller = new PutEventsRequestMarshaller();
var unmarshaller = PutEventsResponseUnmarshaller.Instance;
return Invoke<PutEventsRequest,PutEventsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the PutEvents operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutEvents operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<PutEventsResponse> PutEventsAsync(PutEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new PutEventsRequestMarshaller();
var unmarshaller = PutEventsResponseUnmarshaller.Instance;
return InvokeAsync<PutEventsRequest,PutEventsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Diagnostics; //for [DebuggerNonUserCode]
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject
{
public ILSL_Api m_LSL_Functions;
public void ApiTypeLSL(IScriptApi api)
{
if (!(api is ILSL_Api))
return;
m_LSL_Functions = (ILSL_Api)api;
}
public void state(string newState)
{
m_LSL_Functions.state(newState);
}
//
// Script functions
//
public LSL_Integer llAbs(int i)
{
return m_LSL_Functions.llAbs(i);
}
public LSL_Float llAcos(double val)
{
return m_LSL_Functions.llAcos(val);
}
public void llAddToLandBanList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandBanList(avatar, hours);
}
public void llAddToLandPassList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandPassList(avatar, hours);
}
public void llAdjustSoundVolume(double volume)
{
m_LSL_Functions.llAdjustSoundVolume(volume);
}
public void llAllowInventoryDrop(int add)
{
m_LSL_Functions.llAllowInventoryDrop(add);
}
public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b)
{
return m_LSL_Functions.llAngleBetween(a, b);
}
public void llApplyImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyImpulse(force, local);
}
public void llApplyRotationalImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyRotationalImpulse(force, local);
}
public LSL_Float llAsin(double val)
{
return m_LSL_Functions.llAsin(val);
}
public LSL_Float llAtan2(double x, double y)
{
return m_LSL_Functions.llAtan2(x, y);
}
public void llAttachToAvatar(int attachment)
{
m_LSL_Functions.llAttachToAvatar(attachment);
}
public LSL_Key llAvatarOnSitTarget()
{
return m_LSL_Functions.llAvatarOnSitTarget();
}
public LSL_Key llAvatarOnLinkSitTarget(int linknum)
{
return m_LSL_Functions.llAvatarOnLinkSitTarget(linknum);
}
public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up)
{
return m_LSL_Functions.llAxes2Rot(fwd, left, up);
}
public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle)
{
return m_LSL_Functions.llAxisAngle2Rot(axis, angle);
}
public LSL_Integer llBase64ToInteger(string str)
{
return m_LSL_Functions.llBase64ToInteger(str);
}
public LSL_String llBase64ToString(string str)
{
return m_LSL_Functions.llBase64ToString(str);
}
public void llBreakAllLinks()
{
m_LSL_Functions.llBreakAllLinks();
}
public void llBreakLink(int linknum)
{
m_LSL_Functions.llBreakLink(linknum);
}
public LSL_Integer llCeil(double f)
{
return m_LSL_Functions.llCeil(f);
}
public void llClearCameraParams()
{
m_LSL_Functions.llClearCameraParams();
}
public void llCloseRemoteDataChannel(string channel)
{
m_LSL_Functions.llCloseRemoteDataChannel(channel);
}
public LSL_Float llCloud(LSL_Vector offset)
{
return m_LSL_Functions.llCloud(offset);
}
public void llCollisionFilter(string name, string id, int accept)
{
m_LSL_Functions.llCollisionFilter(name, id, accept);
}
public void llCollisionSound(string impact_sound, double impact_volume)
{
m_LSL_Functions.llCollisionSound(impact_sound, impact_volume);
}
public void llCollisionSprite(string impact_sprite)
{
m_LSL_Functions.llCollisionSprite(impact_sprite);
}
public LSL_Float llCos(double f)
{
return m_LSL_Functions.llCos(f);
}
public void llCreateLink(string target, int parent)
{
m_LSL_Functions.llCreateLink(target, parent);
}
public LSL_List llCSV2List(string src)
{
return m_LSL_Functions.llCSV2List(src);
}
public LSL_List llDeleteSubList(LSL_List src, int start, int end)
{
return m_LSL_Functions.llDeleteSubList(src, start, end);
}
public LSL_String llDeleteSubString(string src, int start, int end)
{
return m_LSL_Functions.llDeleteSubString(src, start, end);
}
public void llDetachFromAvatar()
{
m_LSL_Functions.llDetachFromAvatar();
}
public LSL_Vector llDetectedGrab(int number)
{
return m_LSL_Functions.llDetectedGrab(number);
}
public LSL_Integer llDetectedGroup(int number)
{
return m_LSL_Functions.llDetectedGroup(number);
}
public LSL_Key llDetectedKey(int number)
{
return m_LSL_Functions.llDetectedKey(number);
}
public LSL_Integer llDetectedLinkNumber(int number)
{
return m_LSL_Functions.llDetectedLinkNumber(number);
}
public LSL_String llDetectedName(int number)
{
return m_LSL_Functions.llDetectedName(number);
}
public LSL_Key llDetectedOwner(int number)
{
return m_LSL_Functions.llDetectedOwner(number);
}
public LSL_Vector llDetectedPos(int number)
{
return m_LSL_Functions.llDetectedPos(number);
}
public LSL_Rotation llDetectedRot(int number)
{
return m_LSL_Functions.llDetectedRot(number);
}
public LSL_Integer llDetectedType(int number)
{
return m_LSL_Functions.llDetectedType(number);
}
public LSL_Vector llDetectedTouchBinormal(int index)
{
return m_LSL_Functions.llDetectedTouchBinormal(index);
}
public LSL_Integer llDetectedTouchFace(int index)
{
return m_LSL_Functions.llDetectedTouchFace(index);
}
public LSL_Vector llDetectedTouchNormal(int index)
{
return m_LSL_Functions.llDetectedTouchNormal(index);
}
public LSL_Vector llDetectedTouchPos(int index)
{
return m_LSL_Functions.llDetectedTouchPos(index);
}
public LSL_Vector llDetectedTouchST(int index)
{
return m_LSL_Functions.llDetectedTouchST(index);
}
public LSL_Vector llDetectedTouchUV(int index)
{
return m_LSL_Functions.llDetectedTouchUV(index);
}
public LSL_Vector llDetectedVel(int number)
{
return m_LSL_Functions.llDetectedVel(number);
}
public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel)
{
m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel);
}
[DebuggerNonUserCode]
public void llDie()
{
m_LSL_Functions.llDie();
}
public LSL_String llDumpList2String(LSL_List src, string seperator)
{
return m_LSL_Functions.llDumpList2String(src, seperator);
}
public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir)
{
return m_LSL_Functions.llEdgeOfWorld(pos, dir);
}
public void llEjectFromLand(string pest)
{
m_LSL_Functions.llEjectFromLand(pest);
}
public void llEmail(string address, string subject, string message)
{
m_LSL_Functions.llEmail(address, subject, message);
}
public LSL_String llEscapeURL(string url)
{
return m_LSL_Functions.llEscapeURL(url);
}
public LSL_Rotation llEuler2Rot(LSL_Vector v)
{
return m_LSL_Functions.llEuler2Rot(v);
}
public LSL_Float llFabs(double f)
{
return m_LSL_Functions.llFabs(f);
}
public LSL_Integer llFloor(double f)
{
return m_LSL_Functions.llFloor(f);
}
public void llForceMouselook(int mouselook)
{
m_LSL_Functions.llForceMouselook(mouselook);
}
public LSL_Float llFrand(double mag)
{
return m_LSL_Functions.llFrand(mag);
}
public LSL_Key llGenerateKey()
{
return m_LSL_Functions.llGenerateKey();
}
public LSL_Vector llGetAccel()
{
return m_LSL_Functions.llGetAccel();
}
public LSL_Integer llGetAgentInfo(string id)
{
return m_LSL_Functions.llGetAgentInfo(id);
}
public LSL_String llGetAgentLanguage(string id)
{
return m_LSL_Functions.llGetAgentLanguage(id);
}
public LSL_List llGetAgentList(LSL_Integer scope, LSL_List options)
{
return m_LSL_Functions.llGetAgentList(scope, options);
}
public LSL_Vector llGetAgentSize(string id)
{
return m_LSL_Functions.llGetAgentSize(id);
}
public LSL_Float llGetAlpha(int face)
{
return m_LSL_Functions.llGetAlpha(face);
}
public LSL_Float llGetAndResetTime()
{
return m_LSL_Functions.llGetAndResetTime();
}
public LSL_String llGetAnimation(string id)
{
return m_LSL_Functions.llGetAnimation(id);
}
public LSL_List llGetAnimationList(string id)
{
return m_LSL_Functions.llGetAnimationList(id);
}
public LSL_Integer llGetAttached()
{
return m_LSL_Functions.llGetAttached();
}
public LSL_List llGetAttachedList(string id)
{
return m_LSL_Functions.llGetAttachedList(id);
}
public LSL_List llGetBoundingBox(string obj)
{
return m_LSL_Functions.llGetBoundingBox(obj);
}
public LSL_Vector llGetCameraPos()
{
return m_LSL_Functions.llGetCameraPos();
}
public LSL_Rotation llGetCameraRot()
{
return m_LSL_Functions.llGetCameraRot();
}
public LSL_Vector llGetCenterOfMass()
{
return m_LSL_Functions.llGetCenterOfMass();
}
public LSL_Vector llGetColor(int face)
{
return m_LSL_Functions.llGetColor(face);
}
public LSL_Key llGetCreator()
{
return m_LSL_Functions.llGetCreator();
}
public LSL_String llGetDate()
{
return m_LSL_Functions.llGetDate();
}
public LSL_Float llGetEnergy()
{
return m_LSL_Functions.llGetEnergy();
}
public LSL_String llGetEnv(LSL_String name)
{
return m_LSL_Functions.llGetEnv(name);
}
public LSL_Vector llGetForce()
{
return m_LSL_Functions.llGetForce();
}
public LSL_Integer llGetFreeMemory()
{
return m_LSL_Functions.llGetFreeMemory();
}
public LSL_Integer llGetUsedMemory()
{
return m_LSL_Functions.llGetUsedMemory();
}
public LSL_Integer llGetFreeURLs()
{
return m_LSL_Functions.llGetFreeURLs();
}
public LSL_Vector llGetGeometricCenter()
{
return m_LSL_Functions.llGetGeometricCenter();
}
public LSL_Float llGetGMTclock()
{
return m_LSL_Functions.llGetGMTclock();
}
public LSL_String llGetHTTPHeader(LSL_Key request_id, string header)
{
return m_LSL_Functions.llGetHTTPHeader(request_id, header);
}
public LSL_Key llGetInventoryCreator(string item)
{
return m_LSL_Functions.llGetInventoryCreator(item);
}
public LSL_Key llGetInventoryKey(string name)
{
return m_LSL_Functions.llGetInventoryKey(name);
}
public LSL_String llGetInventoryName(int type, int number)
{
return m_LSL_Functions.llGetInventoryName(type, number);
}
public LSL_Integer llGetInventoryNumber(int type)
{
return m_LSL_Functions.llGetInventoryNumber(type);
}
public LSL_Integer llGetInventoryPermMask(string item, int mask)
{
return m_LSL_Functions.llGetInventoryPermMask(item, mask);
}
public LSL_Integer llGetInventoryType(string name)
{
return m_LSL_Functions.llGetInventoryType(name);
}
public LSL_Key llGetKey()
{
return m_LSL_Functions.llGetKey();
}
public LSL_Key llGetLandOwnerAt(LSL_Vector pos)
{
return m_LSL_Functions.llGetLandOwnerAt(pos);
}
public LSL_Key llGetLinkKey(int linknum)
{
return m_LSL_Functions.llGetLinkKey(linknum);
}
public LSL_String llGetLinkName(int linknum)
{
return m_LSL_Functions.llGetLinkName(linknum);
}
public LSL_Integer llGetLinkNumber()
{
return m_LSL_Functions.llGetLinkNumber();
}
public LSL_Integer llGetLinkNumberOfSides(int link)
{
return m_LSL_Functions.llGetLinkNumberOfSides(link);
}
public LSL_Integer llGetListEntryType(LSL_List src, int index)
{
return m_LSL_Functions.llGetListEntryType(src, index);
}
public LSL_Integer llGetListLength(LSL_List src)
{
return m_LSL_Functions.llGetListLength(src);
}
public LSL_Vector llGetLocalPos()
{
return m_LSL_Functions.llGetLocalPos();
}
public LSL_Rotation llGetLocalRot()
{
return m_LSL_Functions.llGetLocalRot();
}
public LSL_Float llGetMass()
{
return m_LSL_Functions.llGetMass();
}
public LSL_Float llGetMassMKS()
{
return m_LSL_Functions.llGetMassMKS();
}
public LSL_Integer llGetMemoryLimit()
{
return m_LSL_Functions.llGetMemoryLimit();
}
public void llGetNextEmail(string address, string subject)
{
m_LSL_Functions.llGetNextEmail(address, subject);
}
public LSL_Key llGetNotecardLine(string name, int line)
{
return m_LSL_Functions.llGetNotecardLine(name, line);
}
public LSL_Key llGetNumberOfNotecardLines(string name)
{
return m_LSL_Functions.llGetNumberOfNotecardLines(name);
}
public LSL_Integer llGetNumberOfPrims()
{
return m_LSL_Functions.llGetNumberOfPrims();
}
public LSL_Integer llGetNumberOfSides()
{
return m_LSL_Functions.llGetNumberOfSides();
}
public LSL_String llGetObjectDesc()
{
return m_LSL_Functions.llGetObjectDesc();
}
public LSL_List llGetObjectDetails(string id, LSL_List args)
{
return m_LSL_Functions.llGetObjectDetails(id, args);
}
public LSL_Float llGetObjectMass(string id)
{
return m_LSL_Functions.llGetObjectMass(id);
}
public LSL_String llGetObjectName()
{
return m_LSL_Functions.llGetObjectName();
}
public LSL_Integer llGetObjectPermMask(int mask)
{
return m_LSL_Functions.llGetObjectPermMask(mask);
}
public LSL_Integer llGetObjectPrimCount(string object_id)
{
return m_LSL_Functions.llGetObjectPrimCount(object_id);
}
public LSL_Vector llGetOmega()
{
return m_LSL_Functions.llGetOmega();
}
public LSL_Key llGetOwner()
{
return m_LSL_Functions.llGetOwner();
}
public LSL_Key llGetOwnerKey(string id)
{
return m_LSL_Functions.llGetOwnerKey(id);
}
public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param)
{
return m_LSL_Functions.llGetParcelDetails(pos, param);
}
public LSL_Integer llGetParcelFlags(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelFlags(pos);
}
public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide)
{
return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide);
}
public LSL_String llGetParcelMusicURL()
{
return m_LSL_Functions.llGetParcelMusicURL();
}
public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide)
{
return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide);
}
public LSL_List llGetParcelPrimOwners(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelPrimOwners(pos);
}
public LSL_Integer llGetPermissions()
{
return m_LSL_Functions.llGetPermissions();
}
public LSL_Key llGetPermissionsKey()
{
return m_LSL_Functions.llGetPermissionsKey();
}
public LSL_Vector llGetPos()
{
return m_LSL_Functions.llGetPos();
}
public LSL_List llGetPrimitiveParams(LSL_List rules)
{
return m_LSL_Functions.llGetPrimitiveParams(rules);
}
public LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules)
{
return m_LSL_Functions.llGetLinkPrimitiveParams(linknum, rules);
}
public LSL_Integer llGetRegionAgentCount()
{
return m_LSL_Functions.llGetRegionAgentCount();
}
public LSL_Vector llGetRegionCorner()
{
return m_LSL_Functions.llGetRegionCorner();
}
public LSL_Integer llGetRegionFlags()
{
return m_LSL_Functions.llGetRegionFlags();
}
public LSL_Float llGetRegionFPS()
{
return m_LSL_Functions.llGetRegionFPS();
}
public LSL_String llGetRegionName()
{
return m_LSL_Functions.llGetRegionName();
}
public LSL_Float llGetRegionTimeDilation()
{
return m_LSL_Functions.llGetRegionTimeDilation();
}
public LSL_Vector llGetRootPosition()
{
return m_LSL_Functions.llGetRootPosition();
}
public LSL_Rotation llGetRootRotation()
{
return m_LSL_Functions.llGetRootRotation();
}
public LSL_Rotation llGetRot()
{
return m_LSL_Functions.llGetRot();
}
public LSL_Vector llGetScale()
{
return m_LSL_Functions.llGetScale();
}
public LSL_String llGetScriptName()
{
return m_LSL_Functions.llGetScriptName();
}
public LSL_Integer llGetScriptState(string name)
{
return m_LSL_Functions.llGetScriptState(name);
}
public LSL_String llGetSimulatorHostname()
{
return m_LSL_Functions.llGetSimulatorHostname();
}
public LSL_Integer llGetSPMaxMemory()
{
return m_LSL_Functions.llGetSPMaxMemory();
}
public LSL_Integer llGetStartParameter()
{
return m_LSL_Functions.llGetStartParameter();
}
public LSL_Integer llGetStatus(int status)
{
return m_LSL_Functions.llGetStatus(status);
}
public LSL_String llGetSubString(string src, int start, int end)
{
return m_LSL_Functions.llGetSubString(src, start, end);
}
public LSL_Vector llGetSunDirection()
{
return m_LSL_Functions.llGetSunDirection();
}
public LSL_String llGetTexture(int face)
{
return m_LSL_Functions.llGetTexture(face);
}
public LSL_Vector llGetTextureOffset(int face)
{
return m_LSL_Functions.llGetTextureOffset(face);
}
public LSL_Float llGetTextureRot(int side)
{
return m_LSL_Functions.llGetTextureRot(side);
}
public LSL_Vector llGetTextureScale(int side)
{
return m_LSL_Functions.llGetTextureScale(side);
}
public LSL_Float llGetTime()
{
return m_LSL_Functions.llGetTime();
}
public LSL_Float llGetTimeOfDay()
{
return m_LSL_Functions.llGetTimeOfDay();
}
public LSL_String llGetTimestamp()
{
return m_LSL_Functions.llGetTimestamp();
}
public LSL_Vector llGetTorque()
{
return m_LSL_Functions.llGetTorque();
}
public LSL_Integer llGetUnixTime()
{
return m_LSL_Functions.llGetUnixTime();
}
public LSL_Vector llGetVel()
{
return m_LSL_Functions.llGetVel();
}
public LSL_Float llGetWallclock()
{
return m_LSL_Functions.llGetWallclock();
}
public void llGiveInventory(string destination, string inventory)
{
m_LSL_Functions.llGiveInventory(destination, inventory);
}
public void llGiveInventoryList(string destination, string category, LSL_List inventory)
{
m_LSL_Functions.llGiveInventoryList(destination, category, inventory);
}
public LSL_Integer llGiveMoney(string destination, int amount)
{
return m_LSL_Functions.llGiveMoney(destination, amount);
}
public LSL_Key llTransferLindenDollars(string destination, int amount)
{
return m_LSL_Functions.llTransferLindenDollars(destination, amount);
}
public void llGodLikeRezObject(string inventory, LSL_Vector pos)
{
m_LSL_Functions.llGodLikeRezObject(inventory, pos);
}
public LSL_Float llGround(LSL_Vector offset)
{
return m_LSL_Functions.llGround(offset);
}
public LSL_Vector llGroundContour(LSL_Vector offset)
{
return m_LSL_Functions.llGroundContour(offset);
}
public LSL_Vector llGroundNormal(LSL_Vector offset)
{
return m_LSL_Functions.llGroundNormal(offset);
}
public void llGroundRepel(double height, int water, double tau)
{
m_LSL_Functions.llGroundRepel(height, water, tau);
}
public LSL_Vector llGroundSlope(LSL_Vector offset)
{
return m_LSL_Functions.llGroundSlope(offset);
}
public LSL_Key llHTTPRequest(string url, LSL_List parameters, string body)
{
return m_LSL_Functions.llHTTPRequest(url, parameters, body);
}
public void llHTTPResponse(LSL_Key id, int status, string body)
{
m_LSL_Functions.llHTTPResponse(id, status, body);
}
public LSL_String llInsertString(string dst, int position, string src)
{
return m_LSL_Functions.llInsertString(dst, position, src);
}
public void llInstantMessage(string user, string message)
{
m_LSL_Functions.llInstantMessage(user, message);
}
public LSL_String llIntegerToBase64(int number)
{
return m_LSL_Functions.llIntegerToBase64(number);
}
public LSL_String llKey2Name(string id)
{
return m_LSL_Functions.llKey2Name(id);
}
public LSL_String llGetUsername(string id)
{
return m_LSL_Functions.llGetUsername(id);
}
public LSL_Key llRequestUsername(string id)
{
return m_LSL_Functions.llRequestUsername(id);
}
public LSL_String llGetDisplayName(string id)
{
return m_LSL_Functions.llGetDisplayName(id);
}
public LSL_Key llRequestDisplayName(string id)
{
return m_LSL_Functions.llRequestDisplayName(id);
}
public LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options)
{
return m_LSL_Functions.llCastRay(start, end, options);
}
public void llLinkParticleSystem(int linknum, LSL_List rules)
{
m_LSL_Functions.llLinkParticleSystem(linknum, rules);
}
public LSL_String llList2CSV(LSL_List src)
{
return m_LSL_Functions.llList2CSV(src);
}
public LSL_Float llList2Float(LSL_List src, int index)
{
return m_LSL_Functions.llList2Float(src, index);
}
public LSL_Integer llList2Integer(LSL_List src, int index)
{
return m_LSL_Functions.llList2Integer(src, index);
}
public LSL_Key llList2Key(LSL_List src, int index)
{
return m_LSL_Functions.llList2Key(src, index);
}
public LSL_List llList2List(LSL_List src, int start, int end)
{
return m_LSL_Functions.llList2List(src, start, end);
}
public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride)
{
return m_LSL_Functions.llList2ListStrided(src, start, end, stride);
}
public LSL_Rotation llList2Rot(LSL_List src, int index)
{
return m_LSL_Functions.llList2Rot(src, index);
}
public LSL_String llList2String(LSL_List src, int index)
{
return m_LSL_Functions.llList2String(src, index);
}
public LSL_Vector llList2Vector(LSL_List src, int index)
{
return m_LSL_Functions.llList2Vector(src, index);
}
public LSL_Integer llListen(int channelID, string name, string ID, string msg)
{
return m_LSL_Functions.llListen(channelID, name, ID, msg);
}
public void llListenControl(int number, int active)
{
m_LSL_Functions.llListenControl(number, active);
}
public void llListenRemove(int number)
{
m_LSL_Functions.llListenRemove(number);
}
public LSL_Integer llListFindList(LSL_List src, LSL_List test)
{
return m_LSL_Functions.llListFindList(src, test);
}
public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start)
{
return m_LSL_Functions.llListInsertList(dest, src, start);
}
public LSL_List llListRandomize(LSL_List src, int stride)
{
return m_LSL_Functions.llListRandomize(src, stride);
}
public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end)
{
return m_LSL_Functions.llListReplaceList(dest, src, start, end);
}
public LSL_List llListSort(LSL_List src, int stride, int ascending)
{
return m_LSL_Functions.llListSort(src, stride, ascending);
}
public LSL_Float llListStatistics(int operation, LSL_List src)
{
return m_LSL_Functions.llListStatistics(operation, src);
}
public void llLoadURL(string avatar_id, string message, string url)
{
m_LSL_Functions.llLoadURL(avatar_id, message, url);
}
public LSL_Float llLog(double val)
{
return m_LSL_Functions.llLog(val);
}
public LSL_Float llLog10(double val)
{
return m_LSL_Functions.llLog10(val);
}
public void llLookAt(LSL_Vector target, double strength, double damping)
{
m_LSL_Functions.llLookAt(target, strength, damping);
}
public void llLoopSound(string sound, double volume)
{
m_LSL_Functions.llLoopSound(sound, volume);
}
public void llLoopSoundMaster(string sound, double volume)
{
m_LSL_Functions.llLoopSoundMaster(sound, volume);
}
public void llLoopSoundSlave(string sound, double volume)
{
m_LSL_Functions.llLoopSoundSlave(sound, volume);
}
public LSL_Integer llManageEstateAccess(int action, string avatar)
{
return m_LSL_Functions.llManageEstateAccess(action, avatar);
}
public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset)
{
m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset);
}
public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at)
{
m_LSL_Functions.llMapDestination(simname, pos, look_at);
}
public LSL_String llMD5String(string src, int nonce)
{
return m_LSL_Functions.llMD5String(src, nonce);
}
public LSL_String llSHA1String(string src)
{
return m_LSL_Functions.llSHA1String(src);
}
public void llMessageLinked(int linknum, int num, string str, string id)
{
m_LSL_Functions.llMessageLinked(linknum, num, str, id);
}
public void llMinEventDelay(double delay)
{
m_LSL_Functions.llMinEventDelay(delay);
}
public void llModifyLand(int action, int brush)
{
m_LSL_Functions.llModifyLand(action, brush);
}
public LSL_Integer llModPow(int a, int b, int c)
{
return m_LSL_Functions.llModPow(a, b, c);
}
public void llMoveToTarget(LSL_Vector target, double tau)
{
m_LSL_Functions.llMoveToTarget(target, tau);
}
public void llOffsetTexture(double u, double v, int face)
{
m_LSL_Functions.llOffsetTexture(u, v, face);
}
public void llOpenRemoteDataChannel()
{
m_LSL_Functions.llOpenRemoteDataChannel();
}
public LSL_Integer llOverMyLand(string id)
{
return m_LSL_Functions.llOverMyLand(id);
}
public void llOwnerSay(string msg)
{
m_LSL_Functions.llOwnerSay(msg);
}
public void llParcelMediaCommandList(LSL_List commandList)
{
m_LSL_Functions.llParcelMediaCommandList(commandList);
}
public LSL_List llParcelMediaQuery(LSL_List aList)
{
return m_LSL_Functions.llParcelMediaQuery(aList);
}
public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers)
{
return m_LSL_Functions.llParseString2List(str, separators, spacers);
}
public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers)
{
return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers);
}
public void llParticleSystem(LSL_List rules)
{
m_LSL_Functions.llParticleSystem(rules);
}
public void llPassCollisions(int pass)
{
m_LSL_Functions.llPassCollisions(pass);
}
public void llPassTouches(int pass)
{
m_LSL_Functions.llPassTouches(pass);
}
public void llPlaySound(string sound, double volume)
{
m_LSL_Functions.llPlaySound(sound, volume);
}
public void llPlaySoundSlave(string sound, double volume)
{
m_LSL_Functions.llPlaySoundSlave(sound, volume);
}
public void llPointAt(LSL_Vector pos)
{
m_LSL_Functions.llPointAt(pos);
}
public LSL_Float llPow(double fbase, double fexponent)
{
return m_LSL_Functions.llPow(fbase, fexponent);
}
public void llPreloadSound(string sound)
{
m_LSL_Functions.llPreloadSound(sound);
}
public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local)
{
m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local);
}
public void llRefreshPrimURL()
{
m_LSL_Functions.llRefreshPrimURL();
}
public void llRegionSay(int channelID, string text)
{
m_LSL_Functions.llRegionSay(channelID, text);
}
public void llRegionSayTo(string key, int channelID, string text)
{
m_LSL_Functions.llRegionSayTo(key, channelID, text);
}
public void llReleaseCamera(string avatar)
{
m_LSL_Functions.llReleaseCamera(avatar);
}
public void llReleaseURL(string url)
{
m_LSL_Functions.llReleaseURL(url);
}
public void llReleaseControls()
{
m_LSL_Functions.llReleaseControls();
}
public void llRemoteDataReply(string channel, string message_id, string sdata, int idata)
{
m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata);
}
public void llRemoteDataSetRegion()
{
m_LSL_Functions.llRemoteDataSetRegion();
}
public void llRemoteLoadScript(string target, string name, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param);
}
public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param);
}
public void llRemoveFromLandBanList(string avatar)
{
m_LSL_Functions.llRemoveFromLandBanList(avatar);
}
public void llRemoveFromLandPassList(string avatar)
{
m_LSL_Functions.llRemoveFromLandPassList(avatar);
}
public void llRemoveInventory(string item)
{
m_LSL_Functions.llRemoveInventory(item);
}
public void llRemoveVehicleFlags(int flags)
{
m_LSL_Functions.llRemoveVehicleFlags(flags);
}
public LSL_Key llRequestAgentData(string id, int data)
{
return m_LSL_Functions.llRequestAgentData(id, data);
}
public LSL_Key llRequestInventoryData(string name)
{
return m_LSL_Functions.llRequestInventoryData(name);
}
public void llRequestPermissions(string agent, int perm)
{
m_LSL_Functions.llRequestPermissions(agent, perm);
}
public LSL_Key llRequestSecureURL()
{
return m_LSL_Functions.llRequestSecureURL();
}
public LSL_Key llRequestSimulatorData(string simulator, int data)
{
return m_LSL_Functions.llRequestSimulatorData(simulator, data);
}
public LSL_Key llRequestURL()
{
return m_LSL_Functions.llRequestURL();
}
public void llResetLandBanList()
{
m_LSL_Functions.llResetLandBanList();
}
public void llResetLandPassList()
{
m_LSL_Functions.llResetLandPassList();
}
public void llResetOtherScript(string name)
{
m_LSL_Functions.llResetOtherScript(name);
}
public void llResetScript()
{
m_LSL_Functions.llResetScript();
}
public void llResetTime()
{
m_LSL_Functions.llResetTime();
}
public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param);
}
public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param);
}
public LSL_Float llRot2Angle(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Angle(rot);
}
public LSL_Vector llRot2Axis(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Axis(rot);
}
public LSL_Vector llRot2Euler(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Euler(r);
}
public LSL_Vector llRot2Fwd(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Fwd(r);
}
public LSL_Vector llRot2Left(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Left(r);
}
public LSL_Vector llRot2Up(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Up(r);
}
public void llRotateTexture(double rotation, int face)
{
m_LSL_Functions.llRotateTexture(rotation, face);
}
public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end)
{
return m_LSL_Functions.llRotBetween(start, end);
}
public void llRotLookAt(LSL_Rotation target, double strength, double damping)
{
m_LSL_Functions.llRotLookAt(target, strength, damping);
}
public LSL_Integer llRotTarget(LSL_Rotation rot, double error)
{
return m_LSL_Functions.llRotTarget(rot, error);
}
public void llRotTargetRemove(int number)
{
m_LSL_Functions.llRotTargetRemove(number);
}
public LSL_Integer llRound(double f)
{
return m_LSL_Functions.llRound(f);
}
public LSL_Integer llSameGroup(string agent)
{
return m_LSL_Functions.llSameGroup(agent);
}
public void llSay(int channelID, string text)
{
m_LSL_Functions.llSay(channelID, text);
}
public LSL_Integer llScaleByFactor(double scaling_factor)
{
return m_LSL_Functions.llScaleByFactor(scaling_factor);
}
public LSL_Float llGetMaxScaleFactor()
{
return m_LSL_Functions.llGetMaxScaleFactor();
}
public LSL_Float llGetMinScaleFactor()
{
return m_LSL_Functions.llGetMinScaleFactor();
}
public void llScaleTexture(double u, double v, int face)
{
m_LSL_Functions.llScaleTexture(u, v, face);
}
public LSL_Integer llScriptDanger(LSL_Vector pos)
{
return m_LSL_Functions.llScriptDanger(pos);
}
public void llScriptProfiler(LSL_Integer flags)
{
m_LSL_Functions.llScriptProfiler(flags);
}
public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata)
{
return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata);
}
public void llSensor(string name, string id, int type, double range, double arc)
{
m_LSL_Functions.llSensor(name, id, type, range, arc);
}
public void llSensorRemove()
{
m_LSL_Functions.llSensorRemove();
}
public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate)
{
m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate);
}
public void llSetAlpha(double alpha, int face)
{
m_LSL_Functions.llSetAlpha(alpha, face);
}
public void llSetBuoyancy(double buoyancy)
{
m_LSL_Functions.llSetBuoyancy(buoyancy);
}
public void llSetCameraAtOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraAtOffset(offset);
}
public void llSetCameraEyeOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraEyeOffset(offset);
}
public void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at)
{
m_LSL_Functions.llSetLinkCamera(link, eye, at);
}
public void llSetCameraParams(LSL_List rules)
{
m_LSL_Functions.llSetCameraParams(rules);
}
public void llSetClickAction(int action)
{
m_LSL_Functions.llSetClickAction(action);
}
public void llSetColor(LSL_Vector color, int face)
{
m_LSL_Functions.llSetColor(color, face);
}
public void llSetContentType(LSL_Key id, LSL_Integer type)
{
m_LSL_Functions.llSetContentType(id, type);
}
public void llSetDamage(double damage)
{
m_LSL_Functions.llSetDamage(damage);
}
public void llSetForce(LSL_Vector force, int local)
{
m_LSL_Functions.llSetForce(force, local);
}
public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local)
{
m_LSL_Functions.llSetForceAndTorque(force, torque, local);
}
public void llSetVelocity(LSL_Vector force, int local)
{
m_LSL_Functions.llSetVelocity(force, local);
}
public void llSetAngularVelocity(LSL_Vector force, int local)
{
m_LSL_Functions.llSetAngularVelocity(force, local);
}
public void llSetHoverHeight(double height, int water, double tau)
{
m_LSL_Functions.llSetHoverHeight(height, water, tau);
}
public void llSetInventoryPermMask(string item, int mask, int value)
{
m_LSL_Functions.llSetInventoryPermMask(item, mask, value);
}
public void llSetLinkAlpha(int linknumber, double alpha, int face)
{
m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face);
}
public void llSetLinkColor(int linknumber, LSL_Vector color, int face)
{
m_LSL_Functions.llSetLinkColor(linknumber, color, face);
}
public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules);
}
public void llSetLinkTexture(int linknumber, string texture, int face)
{
m_LSL_Functions.llSetLinkTexture(linknumber, texture, face);
}
public void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetLinkTextureAnim(linknum, mode, face, sizex, sizey, start, length, rate);
}
public void llSetLocalRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetLocalRot(rot);
}
public LSL_Integer llSetMemoryLimit(LSL_Integer limit)
{
return m_LSL_Functions.llSetMemoryLimit(limit);
}
public void llSetObjectDesc(string desc)
{
m_LSL_Functions.llSetObjectDesc(desc);
}
public void llSetObjectName(string name)
{
m_LSL_Functions.llSetObjectName(name);
}
public void llSetObjectPermMask(int mask, int value)
{
m_LSL_Functions.llSetObjectPermMask(mask, value);
}
public void llSetParcelMusicURL(string url)
{
m_LSL_Functions.llSetParcelMusicURL(url);
}
public void llSetPayPrice(int price, LSL_List quick_pay_buttons)
{
m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons);
}
public void llSetPos(LSL_Vector pos)
{
m_LSL_Functions.llSetPos(pos);
}
public LSL_Integer llSetRegionPos(LSL_Vector pos)
{
return m_LSL_Functions.llSetRegionPos(pos);
}
public void llSetPrimitiveParams(LSL_List rules)
{
m_LSL_Functions.llSetPrimitiveParams(rules);
}
public void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParamsFast(linknum, rules);
}
public void llSetPrimURL(string url)
{
m_LSL_Functions.llSetPrimURL(url);
}
public void llSetRemoteScriptAccessPin(int pin)
{
m_LSL_Functions.llSetRemoteScriptAccessPin(pin);
}
public void llSetRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetRot(rot);
}
public void llSetScale(LSL_Vector scale)
{
m_LSL_Functions.llSetScale(scale);
}
public void llSetScriptState(string name, int run)
{
m_LSL_Functions.llSetScriptState(name, run);
}
public void llSetSitText(string text)
{
m_LSL_Functions.llSetSitText(text);
}
public void llSetSoundQueueing(int queue)
{
m_LSL_Functions.llSetSoundQueueing(queue);
}
public void llSetSoundRadius(double radius)
{
m_LSL_Functions.llSetSoundRadius(radius);
}
public void llSetStatus(int status, int value)
{
m_LSL_Functions.llSetStatus(status, value);
}
public void llSetText(string text, LSL_Vector color, double alpha)
{
m_LSL_Functions.llSetText(text, color, alpha);
}
public void llSetTexture(string texture, int face)
{
m_LSL_Functions.llSetTexture(texture, face);
}
public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate);
}
public void llSetTimerEvent(double sec)
{
m_LSL_Functions.llSetTimerEvent(sec);
}
public void llSetTorque(LSL_Vector torque, int local)
{
m_LSL_Functions.llSetTorque(torque, local);
}
public void llSetTouchText(string text)
{
m_LSL_Functions.llSetTouchText(text);
}
public void llSetVehicleFlags(int flags)
{
m_LSL_Functions.llSetVehicleFlags(flags);
}
public void llSetVehicleFloatParam(int param, LSL_Float value)
{
m_LSL_Functions.llSetVehicleFloatParam(param, value);
}
public void llSetVehicleRotationParam(int param, LSL_Rotation rot)
{
m_LSL_Functions.llSetVehicleRotationParam(param, rot);
}
public void llSetVehicleType(int type)
{
m_LSL_Functions.llSetVehicleType(type);
}
public void llSetVehicleVectorParam(int param, LSL_Vector vec)
{
m_LSL_Functions.llSetVehicleVectorParam(param, vec);
}
public void llShout(int channelID, string text)
{
m_LSL_Functions.llShout(channelID, text);
}
public LSL_Float llSin(double f)
{
return m_LSL_Functions.llSin(f);
}
public void llSitTarget(LSL_Vector offset, LSL_Rotation rot)
{
m_LSL_Functions.llSitTarget(offset, rot);
}
public void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot)
{
m_LSL_Functions.llLinkSitTarget(link, offset, rot);
}
public void llSleep(double sec)
{
m_LSL_Functions.llSleep(sec);
}
public void llSound(string sound, double volume, int queue, int loop)
{
m_LSL_Functions.llSound(sound, volume, queue, loop);
}
public void llSoundPreload(string sound)
{
m_LSL_Functions.llSoundPreload(sound);
}
public LSL_Float llSqrt(double f)
{
return m_LSL_Functions.llSqrt(f);
}
public void llStartAnimation(string anim)
{
m_LSL_Functions.llStartAnimation(anim);
}
public void llStopAnimation(string anim)
{
m_LSL_Functions.llStopAnimation(anim);
}
public void llStopHover()
{
m_LSL_Functions.llStopHover();
}
public void llStopLookAt()
{
m_LSL_Functions.llStopLookAt();
}
public void llStopMoveToTarget()
{
m_LSL_Functions.llStopMoveToTarget();
}
public void llStopPointAt()
{
m_LSL_Functions.llStopPointAt();
}
public void llStopSound()
{
m_LSL_Functions.llStopSound();
}
public LSL_Integer llStringLength(string str)
{
return m_LSL_Functions.llStringLength(str);
}
public LSL_String llStringToBase64(string str)
{
return m_LSL_Functions.llStringToBase64(str);
}
public LSL_String llStringTrim(string src, int type)
{
return m_LSL_Functions.llStringTrim(src, type);
}
public LSL_Integer llSubStringIndex(string source, string pattern)
{
return m_LSL_Functions.llSubStringIndex(source, pattern);
}
public void llTakeCamera(string avatar)
{
m_LSL_Functions.llTakeCamera(avatar);
}
public void llTakeControls(int controls, int accept, int pass_on)
{
m_LSL_Functions.llTakeControls(controls, accept, pass_on);
}
public LSL_Float llTan(double f)
{
return m_LSL_Functions.llTan(f);
}
public LSL_Integer llTarget(LSL_Vector position, double range)
{
return m_LSL_Functions.llTarget(position, range);
}
public void llTargetOmega(LSL_Vector axis, double spinrate, double gain)
{
m_LSL_Functions.llTargetOmega(axis, spinrate, gain);
}
public void llTargetRemove(int number)
{
m_LSL_Functions.llTargetRemove(number);
}
public void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt)
{
m_LSL_Functions.llTeleportAgent(agent, simname, pos, lookAt);
}
public void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt)
{
m_LSL_Functions.llTeleportAgentGlobalCoords(agent, global, pos, lookAt);
}
public void llTeleportAgentHome(string agent)
{
m_LSL_Functions.llTeleportAgentHome(agent);
}
public void llTextBox(string avatar, string message, int chat_channel)
{
m_LSL_Functions.llTextBox(avatar, message, chat_channel);
}
public LSL_String llToLower(string source)
{
return m_LSL_Functions.llToLower(source);
}
public LSL_String llToUpper(string source)
{
return m_LSL_Functions.llToUpper(source);
}
public void llTriggerSound(string sound, double volume)
{
m_LSL_Functions.llTriggerSound(sound, volume);
}
public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west)
{
m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west);
}
public LSL_String llUnescapeURL(string url)
{
return m_LSL_Functions.llUnescapeURL(url);
}
public void llUnSit(string id)
{
m_LSL_Functions.llUnSit(id);
}
public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b)
{
return m_LSL_Functions.llVecDist(a, b);
}
public LSL_Float llVecMag(LSL_Vector v)
{
return m_LSL_Functions.llVecMag(v);
}
public LSL_Vector llVecNorm(LSL_Vector v)
{
return m_LSL_Functions.llVecNorm(v);
}
public void llVolumeDetect(int detect)
{
m_LSL_Functions.llVolumeDetect(detect);
}
public LSL_Float llWater(LSL_Vector offset)
{
return m_LSL_Functions.llWater(offset);
}
public void llWhisper(int channelID, string text)
{
m_LSL_Functions.llWhisper(channelID, text);
}
public LSL_Vector llWind(LSL_Vector offset)
{
return m_LSL_Functions.llWind(offset);
}
public LSL_String llXorBase64Strings(string str1, string str2)
{
return m_LSL_Functions.llXorBase64Strings(str1, str2);
}
public LSL_String llXorBase64StringsCorrect(string str1, string str2)
{
return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2);
}
public LSL_List llGetPrimMediaParams(int face, LSL_List rules)
{
return m_LSL_Functions.llGetPrimMediaParams(face, rules);
}
public LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules)
{
return m_LSL_Functions.llGetLinkMedia(link, face, rules);
}
public LSL_Integer llSetPrimMediaParams(int face, LSL_List rules)
{
return m_LSL_Functions.llSetPrimMediaParams(face, rules);
}
public LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules)
{
return m_LSL_Functions.llSetLinkMedia(link, face, rules);
}
public LSL_Integer llClearPrimMedia(LSL_Integer face)
{
return m_LSL_Functions.llClearPrimMedia(face);
}
public LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face)
{
return m_LSL_Functions.llClearLinkMedia(link, face);
}
public LSL_Integer llGetLinkNumberOfSides(LSL_Integer link)
{
return m_LSL_Functions.llGetLinkNumberOfSides(link);
}
public void llSetKeyframedMotion(LSL_List frames, LSL_List options)
{
m_LSL_Functions.llSetKeyframedMotion(frames, options);
}
public void llSetPhysicsMaterial(int material_bits, LSL_Float material_gravity_modifier, LSL_Float material_restitution, LSL_Float material_friction, LSL_Float material_density)
{
m_LSL_Functions.llSetPhysicsMaterial(material_bits, material_gravity_modifier, material_restitution, material_friction, material_density);
}
public LSL_List llGetPhysicsMaterial()
{
return m_LSL_Functions.llGetPhysicsMaterial();
}
public void llSetAnimationOverride(LSL_String animState, LSL_String anim)
{
m_LSL_Functions.llSetAnimationOverride(animState, anim);
}
public void llResetAnimationOverride(LSL_String anim_state)
{
m_LSL_Functions.llResetAnimationOverride(anim_state);
}
public LSL_String llGetAnimationOverride(LSL_String anim_state)
{
return m_LSL_Functions.llGetAnimationOverride(anim_state);
}
public LSL_String llJsonGetValue(LSL_String json, LSL_List specifiers)
{
return m_LSL_Functions.llJsonGetValue(json, specifiers);
}
public LSL_List llJson2List(LSL_String json)
{
return m_LSL_Functions.llJson2List(json);
}
public LSL_String llList2Json(LSL_String type, LSL_List values)
{
return m_LSL_Functions.llList2Json(type, values);
}
public LSL_String llJsonSetValue(LSL_String json, LSL_List specifiers, LSL_String value)
{
return m_LSL_Functions.llJsonSetValue(json, specifiers, value);
}
public LSL_String llJsonValueType(LSL_String json, LSL_List specifiers)
{
return m_LSL_Functions.llJsonValueType(json, specifiers);
}
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.TimeZones;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace NodaTime.Test.TimeZones
{
public class BclDateTimeZoneTest
{
private static readonly ReadOnlyCollection<NamedWrapper<TimeZoneInfo>> BclZones =
(TestHelper.IsRunningOnMono ? GetSafeSystemTimeZones() : TimeZoneInfo.GetSystemTimeZones())
.Select(zone => new NamedWrapper<TimeZoneInfo>(zone, zone.Id))
.ToList()
.AsReadOnly();
private static ReadOnlyCollection<TimeZoneInfo> GetSafeSystemTimeZones() =>
TimeZoneInfo.GetSystemTimeZones()
// Filter time zones that have a rule involving Feb 29th, to avoid https://bugzilla.xamarin.com/show_bug.cgi?id=54468
.Where(ZoneRulesDontReferToLeapDays)
// Recreate all time zones from their rules, to avoid https://bugzilla.xamarin.com/show_bug.cgi?id=54480
// Arguably this is invalid, but it means we're testing that Noda Time can do as well as it can feasibly
// do based on the rules.
.Select(RecreateZone)
.ToList()
.AsReadOnly();
private static bool ZoneRulesDontReferToLeapDays(TimeZoneInfo zone) =>
!zone.GetAdjustmentRules().Any(rule => TransitionRefersToLeapDay(rule.DaylightTransitionStart) ||
TransitionRefersToLeapDay(rule.DaylightTransitionEnd));
private static bool TransitionRefersToLeapDay(TimeZoneInfo.TransitionTime transition) =>
transition.IsFixedDateRule && transition.Month == 2 && transition.Day == 29;
private static TimeZoneInfo RecreateZone(TimeZoneInfo zone) =>
TimeZoneInfo.CreateCustomTimeZone(zone.Id, zone.BaseUtcOffset, zone.DisplayName, zone.StandardName,
zone.DisplayName, zone.GetAdjustmentRules());
// TODO: Check what this does on Mono, both on Windows and Unix.
[Test]
[TestCaseSource(nameof(BclZones))]
public void AreWindowsStyleRules(NamedWrapper<TimeZoneInfo> zoneWrapper)
{
var zone = zoneWrapper.Value;
var expected = !TestHelper.IsRunningOnDotNetCoreUnix;
var rules = zone.GetAdjustmentRules();
if (rules is null || rules.Length == 0)
{
return;
}
Assert.AreEqual(expected, BclDateTimeZone.AreWindowsStyleRules(rules));
}
[Test]
[TestCaseSource(nameof(BclZones))]
[Category("BrokenOnMonoLinux")]
public void AllZoneTransitions(NamedWrapper<TimeZoneInfo> windowsZoneWrapper)
{
var windowsZone = windowsZoneWrapper.Value;
var nodaZone = BclDateTimeZone.FromTimeZoneInfo(windowsZone);
// Currently .NET Core doesn't expose the information we need to determine any DST recurrence
// after the final tzif rule. For the moment, limit how far we check.
// See https://github.com/dotnet/corefx/issues/17117
int endYear = TestHelper.IsRunningOnDotNetCoreUnix ? 2037 : 2050;
Instant instant = Instant.FromUtc(1800, 1, 1, 0, 0);
Instant end = Instant.FromUtc(endYear, 1, 1, 0, 0);
while (instant < end)
{
ValidateZoneEquality(instant - Duration.Epsilon, nodaZone, windowsZone);
ValidateZoneEquality(instant, nodaZone, windowsZone);
instant = nodaZone.GetZoneInterval(instant).RawEnd;
}
}
[Test]
[TestCaseSource(nameof(BclZones))]
public void DisplayName(NamedWrapper<TimeZoneInfo> windowsZoneWrapper)
{
var windowsZone = windowsZoneWrapper.Value;
var nodaZone = BclDateTimeZone.FromTimeZoneInfo(windowsZone);
Assert.AreEqual(windowsZone.DisplayName, nodaZone.DisplayName);
}
/// <summary>
/// This test catches situations where the Noda Time representation doesn't have all the
/// transitions it should; AllZoneTransitions may pass not spot times when we *should* have
/// a transition, because it only uses the transitions it knows about. Instead, here we
/// check each week between 1st January 1950 and 1st January 2050 (or 2037, in some cases).
/// We use midnight UTC, but this is arbitrary. The choice of checking once a week is just
/// practical - it's a relatively slow test, mostly because TimeZoneInfo is slow.
/// </summary>
[Test]
[TestCaseSource(nameof(BclZones))]
[Category("BrokenOnMonoLinux")]
public void AllZonesEveryWeek(NamedWrapper<TimeZoneInfo> windowsZoneWrapper)
{
ValidateZoneEveryWeek(windowsZoneWrapper.Value);
}
[Test]
[TestCaseSource(nameof(BclZones))]
public void AllZonesStartAndEndOfTime(NamedWrapper<TimeZoneInfo> windowsZoneWrapper)
{
var nodaZone = BclDateTimeZone.FromTimeZoneInfo(windowsZoneWrapper.Value);
var firstInterval = nodaZone.GetZoneInterval(Instant.MinValue);
Assert.IsFalse(firstInterval.HasStart);
var lastInterval = nodaZone.GetZoneInterval(Instant.MaxValue);
Assert.IsFalse(lastInterval.HasEnd);
}
private void ValidateZoneEveryWeek(TimeZoneInfo windowsZone)
{
var nodaZone = BclDateTimeZone.FromTimeZoneInfo(windowsZone);
// Currently .NET Core doesn't expose the information we need to determine any DST recurrence
// after the final tzif rule. For the moment, limit how far we check.
// See https://github.com/dotnet/corefx/issues/17117
int endYear = TestHelper.IsRunningOnDotNetCoreUnix ? 2037 : 2050;
Instant instant = Instant.FromUtc(1950, 1, 1, 0, 0);
Instant end = Instant.FromUtc(endYear, 1, 1, 0, 0);
while (instant < end)
{
ValidateZoneEquality(instant, nodaZone, windowsZone);
instant += Duration.OneWeek;
}
}
[Test]
public void ForSystemDefault()
{
// Assume that the local time zone doesn't change between two calls...
TimeZoneInfo local = TimeZoneInfo.Local;
BclDateTimeZone nodaLocal1 = BclDateTimeZone.ForSystemDefault();
BclDateTimeZone nodaLocal2 = BclDateTimeZone.ForSystemDefault();
// Check it's actually the right zone
Assert.AreSame(local, nodaLocal1.OriginalZone);
// Check it's cached
Assert.AreSame(nodaLocal1, nodaLocal2);
}
[Test]
public void DateTimeMinValueStartRuleExtendsToBeginningOfTime()
{
// .NET Core on Unix loses data from rules provided to CreateCustomTimeZone :(
// (It assumes the rules have been created from tzif files, which isn't the case here.)
// See https://github.com/dotnet/corefx/issues/29912
Ignore.When(TestHelper.IsRunningOnDotNetCoreUnix, ".NET Core on Unix mangles custom time zones");
var rules = new[]
{
// Rule for the whole of time, with DST of 1 hour commencing on March 1st
// and ending on September 1st.
TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(
DateTime.MinValue, DateTime.MaxValue.Date, TimeSpan.FromHours(1),
TimeZoneInfo.TransitionTime.CreateFixedDateRule(DateTime.MinValue, 3, 1),
TimeZoneInfo.TransitionTime.CreateFixedDateRule(DateTime.MinValue, 9, 1))
};
var bclZone = TimeZoneInfo.CreateCustomTimeZone("custom", baseUtcOffset: TimeSpan.Zero,
displayName: "DisplayName", standardDisplayName: "Standard",
daylightDisplayName: "Daylight",
adjustmentRules: rules);
var nodaZone = BclDateTimeZone.FromTimeZoneInfo(bclZone);
// Standard time in February BC 101
Assert.AreEqual(Offset.Zero, nodaZone.GetUtcOffset(Instant.FromUtc(-100, 2, 1, 0, 0)));
// Daylight time in July BC 101
Assert.AreEqual(Offset.FromHours(1), nodaZone.GetUtcOffset(Instant.FromUtc(-100, 7, 1, 0, 0)));
// Standard time in October BC 101
Assert.AreEqual(Offset.Zero, nodaZone.GetUtcOffset(Instant.FromUtc(-100, 10, 1, 0, 0)));
}
[Test]
public void AwkwardLeapYears()
{
// This mimics the data on Mono on Linux for Europe/Malta, where there's a BCL adjustment rule for
// each rule for quite a long time. One of those years is 1948, and the daylight transition is February
// 29th. That then fails when we try to build a ZoneInterval at the end of that year.
// See https://github.com/nodatime/nodatime/issues/743 for more details. We've simplified this to just
// a single rule here...
// Amusingly, trying to reproduce the test on Mono with a custom time zone causes Mono to throw -
// quite possibly due to the same root cause that we're testing we've fixed in Noda Time.
// See https://bugzilla.xamarin.com/attachment.cgi?id=21192&action=edit
Ignore.When(TestHelper.IsRunningOnMono, "Mono throws an exception with awkward leap years");
// .NET Core on Unix loses data from rules provided to CreateCustomTimeZone :(
// (It assumes the rules have been created from tzif files, which isn't the case here.)
Ignore.When(TestHelper.IsRunningOnDotNetCoreUnix, ".NET Core on Unix mangles custom time zones");
var rules = new[]
{
TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(
dateStart: new DateTime(1948, 1, 1),
dateEnd: new DateTime(1949, 1, 1).AddDays(-1),
daylightDelta: TimeSpan.FromHours(1),
daylightTransitionStart: TimeZoneInfo.TransitionTime.CreateFixedDateRule(timeOfDay: new DateTime(1, 1, 1, 2, 0, 0), month: 2, day: 29),
daylightTransitionEnd: TimeZoneInfo.TransitionTime.CreateFixedDateRule(timeOfDay: new DateTime(1, 1, 1, 3, 0, 0), month: 10, day: 3))
};
var bclZone = TimeZoneInfo.CreateCustomTimeZone("Europe/Malta", TimeSpan.Zero, "Malta", "Standard", "Daylight", rules);
var nodaZone = BclDateTimeZone.FromTimeZoneInfo(bclZone);
var expectedTransition1 = Instant.FromUtc(1948, 2, 29, 2, 0, 0);
var expectedTransition2 = Instant.FromUtc(1948, 10, 3, 2, 0, 0); // 3am local time
var zoneIntervalBefore = nodaZone.GetZoneInterval(Instant.FromUtc(1947, 1, 1, 0, 0));
Assert.AreEqual(
new ZoneInterval("Standard", Instant.BeforeMinValue, expectedTransition1, Offset.Zero, Offset.Zero),
zoneIntervalBefore);
var daylightZoneInterval = nodaZone.GetZoneInterval(Instant.FromUtc(1948, 6, 1, 0, 0));
Assert.AreEqual(
new ZoneInterval("Daylight", expectedTransition1, expectedTransition2, Offset.FromHours(1), Offset.FromHours(1)),
daylightZoneInterval);
var zoneIntervalAfter = nodaZone.GetZoneInterval(Instant.FromUtc(1949, 1, 1, 0, 0));
Assert.AreEqual(
new ZoneInterval("Standard", expectedTransition2, Instant.AfterMaxValue, Offset.Zero, Offset.Zero),
zoneIntervalAfter);
}
[Test]
public void LocalZoneIsNull()
{
var systemZone = TimeZoneInfo.CreateCustomTimeZone("Normal zone", TimeSpan.Zero, "Display", "Standard");
using (TimeZoneInfoReplacer.Replace(null, systemZone))
{
Assert.Throws<InvalidOperationException>(() => BclDateTimeZone.ForSystemDefault());
}
}
[Test]
public void FakeDaylightSavingTime()
{
// .NET Core on Unix loses data from rules provided to CreateCustomTimeZone :(
// (It assumes the rules have been created from tzif files, which isn't the case here.)
Ignore.When(TestHelper.IsRunningOnDotNetCoreUnix, ".NET Core on Unix mangles custom time zones");
// Linux time zones on Mono can have a strange situation with a "0 savings" adjustment rule to represent
// "we want to change standard time but we can't".
// See https://github.com/nodatime/nodatime/issues/746
// Normally the odd rule would only be in place for a year, but it's simplest to just make it all the time.
// We go into daylight savings at midday on March 10th, and out again at midday on September 25.
// We should be able to use DateTime.MaxValue for dateEnd, but not in .NET 4.5 apparently.
var rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue, new DateTime(9999, 12, 31), TimeSpan.Zero,
TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 12, 0, 0), 3, 10),
TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 12, 0, 0), 9, 25));
var bclZone = TimeZoneInfo.CreateCustomTimeZone("Nasty", TimeSpan.FromHours(4), "Display", "Standard", "Daylight", new[] { rule });
var nodaZone = BclDateTimeZone.FromTimeZoneInfo(bclZone);
var winterInterval = nodaZone.GetZoneInterval(Instant.FromUtc(2017, 2, 1, 0, 0));
var summerInterval = nodaZone.GetZoneInterval(Instant.FromUtc(2017, 6, 1, 0, 0));
var expectedWinter = new ZoneInterval("Standard", Instant.FromUtc(2016, 9, 25, 8, 0), Instant.FromUtc(2017, 3, 10, 8, 0), Offset.FromHours(4), Offset.Zero);
var expectedSummer = new ZoneInterval("Daylight", Instant.FromUtc(2017, 3, 10, 8, 0), Instant.FromUtc(2017, 9, 25, 8, 0), Offset.FromHours(4), Offset.FromHours(1));
Assert.AreEqual(expectedWinter, winterInterval);
Assert.AreEqual(expectedSummer, summerInterval);
}
// See https://github.com/nodatime/nodatime/issues/1524 for the background
// It would be nice to test earlier dates (e.g. 1967 and 1998) where transitions
// actually occurred on the first of the "next month", but the Windows database has very different
// data from TZDB in those cases.
[Test]
public void TransitionAtMidnight()
{
var bclZone = GetBclZoneOrIgnore("E. South America Standard Time");
var nodaTzdbZone = DateTimeZoneProviders.Tzdb["America/Sao_Paulo"];
var nodaBclZone = BclDateTimeZone.FromTimeZoneInfo(bclZone);
// Brazil in 2012:
// Fall back from -02:00 to -03:00 at midnight on February 26th
var expectedFallBack = Instant.FromUtc(2012, 2, 26, 2, 0, 0);
// Spring forward from -03:00 to -02:00 at midnight on October 21st
var expectedSpringForward = Instant.FromUtc(2012, 10, 21, 3, 0, 0);
// This is an arbitrary instant between the fall back and spring forward.
var betweenTransitions = Instant.FromUtc(2012, 6, 1, 0, 0, 0);
// Check that these transitions are as expected when we use TZDB.
var nodaTzdbInterval = nodaTzdbZone.GetZoneInterval(betweenTransitions);
Assert.AreEqual(expectedFallBack, nodaTzdbInterval.Start);
Assert.AreEqual(expectedSpringForward, nodaTzdbInterval.End);
// Check that the real BCL time zone behaves as reported in the issue: the transitions occur one millisecond early
var expectedFallBackBclTransition = expectedFallBack - Duration.FromMilliseconds(1);
Assert.AreEqual(TimeSpan.FromHours(-2), bclZone.GetUtcOffset(expectedFallBackBclTransition.ToDateTimeUtc() - TimeSpan.FromTicks(1)));
Assert.AreEqual(TimeSpan.FromHours(-3), bclZone.GetUtcOffset(expectedFallBackBclTransition.ToDateTimeUtc()));
var expectedSpringForwardBclTransition = expectedSpringForward - Duration.FromMilliseconds(1);
Assert.AreEqual(TimeSpan.FromHours(-3), bclZone.GetUtcOffset(expectedSpringForwardBclTransition.ToDateTimeUtc() - TimeSpan.FromTicks(1)));
Assert.AreEqual(TimeSpan.FromHours(-2), bclZone.GetUtcOffset(expectedSpringForwardBclTransition.ToDateTimeUtc()));
// Assert that Noda Time accounts for the Windows time zone data weirdness, and corrects it to
// a transition at midnight.
var nodaBclInterval = nodaBclZone.GetZoneInterval(betweenTransitions);
Assert.AreEqual(nodaTzdbInterval.Start, nodaBclInterval.Start);
Assert.AreEqual(nodaTzdbInterval.End, nodaBclInterval.End);
// Finally check the use case that was actually reported
var actualStartOfDayAfterSpringForward = nodaBclZone.AtStartOfDay(new LocalDate(2012, 10, 21));
var expectedStartOfDayAfterSpringForward = new LocalDateTime(2012, 10, 21, 1, 0, 0).InZoneStrictly(nodaBclZone);
Assert.AreEqual(expectedStartOfDayAfterSpringForward, actualStartOfDayAfterSpringForward);
}
private void ValidateZoneEquality(Instant instant, DateTimeZone nodaZone, TimeZoneInfo windowsZone)
{
// The BCL is basically broken (up to and including .NET 4.5.1 at least) around its interpretation
// of its own data around the new year. See http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/
// for details. We're not trying to emulate this behaviour.
// It's a lot *better* for .NET 4.6,
// FIXME: Finish this comment, try again. (We don't test against .NET 4.5 any more...)
var utc = instant.InUtc();
if ((utc.Month == 12 && utc.Day == 31) || (utc.Month == 1 && utc.Day == 1))
{
return;
}
var interval = nodaZone.GetZoneInterval(instant);
// Check that the zone interval really represents a transition. It could be a change in
// wall offset, name, or the split between standard time and daylight savings for the interval.
if (interval.RawStart != Instant.BeforeMinValue)
{
var previousInterval = nodaZone.GetZoneInterval(interval.Start - Duration.Epsilon);
Assert.AreNotEqual(new {interval.WallOffset, interval.Name, interval.StandardOffset},
new {previousInterval.WallOffset, previousInterval.Name, previousInterval.StandardOffset},
"Non-transition from {0} to {1}", previousInterval, interval);
}
var nodaOffset = interval.WallOffset;
// Some midnight transitions in the Noda Time representation are actually corrections for the
// BCL data indicating 23:59:59.999 on the previous day. If we're testing around midnight,
// allow the Windows data to be correct for either of those instants.
var acceptableInstants = new List<Instant> { instant };
var localTimeOfDay = instant.InZone(nodaZone).TimeOfDay;
if ((localTimeOfDay == LocalTime.Midnight || localTimeOfDay == LocalTime.MaxValue) && instant > NodaConstants.BclEpoch)
{
acceptableInstants.Add(instant - Duration.FromMilliseconds(1));
}
var expectedOffsetAsTimeSpan = nodaOffset.ToTimeSpan();
// Find an instant that at least has the right offset (so will pass the first assertion).
var instantToTest = acceptableInstants.FirstOrDefault(candidate => windowsZone.GetUtcOffset(candidate.ToDateTimeUtc()) == expectedOffsetAsTimeSpan);
// If the test is definitely going to fail, just use the original instant that was passed in.
if (instantToTest == default)
{
instantToTest = instant;
}
var windowsOffset = windowsZone.GetUtcOffset(instantToTest.ToDateTimeUtc());
Assert.AreEqual(windowsOffset, expectedOffsetAsTimeSpan, "Incorrect offset at {0} in interval {1}", instantToTest, interval);
var bclDaylight = windowsZone.IsDaylightSavingTime(instantToTest.ToDateTimeUtc());
Assert.AreEqual(bclDaylight, interval.Savings != Offset.Zero,
"At {0}, BCL IsDaylightSavingTime={1}; Noda savings={2}",
instant, bclDaylight, interval.Savings);
}
private TimeZoneInfo GetBclZoneOrIgnore(string systemTimeZoneId) =>
TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(z => z.Id == systemTimeZoneId)
?? Ignore.Throw<TimeZoneInfo>($"Time zone {systemTimeZoneId} not found");
}
}
| |
//
// WidgetBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt;
using System.Collections.Generic;
using System.Linq;
using Xwt.Drawing;
using System.Runtime.InteropServices;
namespace Xwt.GtkBackend
{
public partial class WidgetBackend: IWidgetBackend, IGtkWidgetBackend
{
Gtk.Widget widget;
Widget frontend;
Gtk.EventBox eventBox;
IWidgetEventSink eventSink;
WidgetEvent enabledEvents;
bool destroyed;
bool minSizeSet;
class DragDropData
{
public TransferDataSource CurrentDragData;
public Gdk.DragAction DestDragAction;
public Gdk.DragAction SourceDragAction;
public int DragDataRequests;
public TransferDataStore DragData;
public bool DragDataForMotion;
public Gtk.TargetEntry[] ValidDropTypes;
public Point LastDragPosition;
}
DragDropData dragDropInfo;
const WidgetEvent dragDropEvents = WidgetEvent.DragDropCheck | WidgetEvent.DragDrop | WidgetEvent.DragOver | WidgetEvent.DragOverCheck;
void IBackend.InitializeBackend (object frontend, ApplicationContext context)
{
this.frontend = (Widget) frontend;
ApplicationContext = context;
}
void IWidgetBackend.Initialize (IWidgetEventSink sink)
{
eventSink = sink;
Initialize ();
}
public virtual void Initialize ()
{
}
public IWidgetEventSink EventSink {
get { return eventSink; }
}
public Widget Frontend {
get { return frontend; }
}
public ApplicationContext ApplicationContext {
get;
private set;
}
public object NativeWidget {
get {
return RootWidget;
}
}
public Gtk.Widget Widget {
get { return widget; }
set {
if (widget != null) {
value.Visible = widget.Visible;
GtkEngine.ReplaceChild (widget, value);
}
widget = value;
}
}
public Gtk.Widget RootWidget {
get {
return eventBox ?? (Gtk.Widget) Widget;
}
}
public string Name {
get { return Widget.Name; }
set { Widget.Name = value; }
}
public virtual bool Visible {
get { return Widget.Visible; }
set {
Widget.Visible = value;
if (eventBox != null)
eventBox.Visible = value;
}
}
void RunWhenRealized (Action a)
{
if (Widget.IsRealized)
a ();
else {
EventHandler h = null;
h = delegate {
a ();
};
EventsRootWidget.Realized += h;
}
}
public virtual bool Sensitive {
get { return Widget.Sensitive; }
set {
Widget.Sensitive = value;
if (eventBox != null)
eventBox.Sensitive = value;
}
}
public bool CanGetFocus {
get { return Widget.CanFocus; }
set { Widget.CanFocus = value; }
}
public bool HasFocus {
get { return Widget.IsFocus; }
}
public virtual void SetFocus ()
{
if (CanGetFocus)
Widget.GrabFocus ();
}
public string TooltipText {
get {
return Widget.TooltipText;
}
set {
Widget.TooltipText = value;
var engine = Toolkit.GetBackend(Frontend.Surface.ToolkitEngine) as GtkEngine;
engine?.PlatformBackend?.EnableNativeTooltip(Widget);
}
}
static Dictionary<CursorType,Gdk.Cursor> gtkCursors = new Dictionary<CursorType, Gdk.Cursor> ();
Gdk.Cursor gdkCursor;
internal CursorType CurrentCursor { get; private set; }
public void SetCursor (CursorType cursor)
{
AllocEventBox ();
CurrentCursor = cursor;
Gdk.Cursor gc;
if (!gtkCursors.TryGetValue (cursor, out gc)) {
Gdk.CursorType ctype;
if (cursor == CursorType.Arrow)
ctype = Gdk.CursorType.LeftPtr;
else if (cursor == CursorType.Crosshair)
ctype = Gdk.CursorType.Crosshair;
else if (cursor == CursorType.Hand)
ctype = Gdk.CursorType.Hand1;
else if (cursor == CursorType.Hand2 || cursor == CursorType.DragCopy)
ctype = Gdk.CursorType.Hand2;
else if (cursor == CursorType.IBeam)
ctype = Gdk.CursorType.Xterm;
else if (cursor == CursorType.ResizeDown)
ctype = Gdk.CursorType.BottomSide;
else if (cursor == CursorType.ResizeUp)
ctype = Gdk.CursorType.TopSide;
else if (cursor == CursorType.ResizeLeft)
ctype = Gdk.CursorType.LeftSide;
else if (cursor == CursorType.ResizeRight)
ctype = Gdk.CursorType.RightSide;
else if (cursor == CursorType.ResizeLeftRight)
ctype = Gdk.CursorType.SbHDoubleArrow;
else if (cursor == CursorType.ResizeUpDown)
ctype = Gdk.CursorType.SbVDoubleArrow;
else if (cursor == CursorType.ResizeNE)
ctype = Gdk.CursorType.TopRightCorner;
else if (cursor == CursorType.ResizeNW)
ctype = Gdk.CursorType.TopLeftCorner;
else if (cursor == CursorType.ResizeSE)
ctype = Gdk.CursorType.BottomRightCorner;
else if (cursor == CursorType.ResizeSW)
ctype = Gdk.CursorType.BottomLeftCorner;
else if (cursor == CursorType.NotAllowed)
ctype = Gdk.CursorType.XCursor;
else if (cursor == CursorType.Move)
ctype = Gdk.CursorType.Fleur;
else if (cursor == CursorType.Wait)
ctype = Gdk.CursorType.Watch;
else if (cursor == CursorType.Help)
ctype = Gdk.CursorType.QuestionArrow;
else if (cursor == CursorType.Invisible)
ctype = (Gdk.CursorType)(-2); // Gdk.CursorType.None, since Gtk 2.16
else
ctype = Gdk.CursorType.Arrow;
gtkCursors [cursor] = gc = new Gdk.Cursor (ctype);
}
gdkCursor = gc;
// subscribe mouse entered/leaved events, when widget gets/is realized
RunWhenRealized(SubscribeCursorEnterLeaveEvent);
if (immediateCursorChange) // if realized and mouse inside set immediatly
EventsRootWidget.GdkWindow.Cursor = gdkCursor;
}
bool cursorEnterLeaveSubscribed, immediateCursorChange;
void SubscribeCursorEnterLeaveEvent ()
{
if (!cursorEnterLeaveSubscribed) {
cursorEnterLeaveSubscribed = true; // subscribe only once
EventsRootWidget.AddEvents ((int)Gdk.EventMask.EnterNotifyMask);
EventsRootWidget.AddEvents ((int)Gdk.EventMask.LeaveNotifyMask);
EventsRootWidget.EnterNotifyEvent += (o, args) => {
immediateCursorChange = true;
if (gdkCursor != null) ((Gtk.Widget)o).GdkWindow.Cursor = gdkCursor;
};
EventsRootWidget.LeaveNotifyEvent += (o, args) => {
immediateCursorChange = false;
((Gtk.Widget)o).GdkWindow.Cursor = null;
};
}
}
~WidgetBackend ()
{
Dispose (false);
}
public void Dispose ()
{
GC.SuppressFinalize (this);
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (Widget != null && disposing && !destroyed) {
MarkDestroyed (Frontend);
Widget.Destroy ();
}
if (IMContext != null)
IMContext.Dispose ();
}
void MarkDestroyed (Widget w)
{
var wbk = Toolkit.GetBackend (w);
var bk = wbk as WidgetBackend;
if (bk == null) {
var ew = wbk as Xwt.Widget;
if (ew == null)
return;
bk = Toolkit.GetBackend (ew) as WidgetBackend;
if (bk == null)
return;
}
bk.destroyed = true;
foreach (var c in w.Surface.Children)
MarkDestroyed (c);
}
public Size Size {
get {
return new Size (Widget.Allocation.Width, Widget.Allocation.Height);
}
}
public void SetSizeConstraints (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
{
}
DragDropData DragDropInfo {
get {
if (dragDropInfo == null)
dragDropInfo = new DragDropData ();
return dragDropInfo;
}
}
public Point ConvertToParentCoordinates (Point widgetCoordinates)
{
int x = 0, y = 0;
if (RootWidget?.Parent != null)
Widget.TranslateCoordinates (RootWidget.Parent, x, y, out x, out y);
return new Point (x + widgetCoordinates.X, y + widgetCoordinates.Y);
}
public Point ConvertToWindowCoordinates (Point widgetCoordinates)
{
int x = 0, y = 0;
if (RootWidget?.Toplevel != null)
Widget.TranslateCoordinates (RootWidget.Toplevel, x, y, out x, out y);
return new Point (x + widgetCoordinates.X, y + widgetCoordinates.Y);
}
public Point ConvertToScreenCoordinates (Point widgetCoordinates)
{
if (Widget.ParentWindow == null)
return Point.Zero;
int x, y;
Widget.ParentWindow.GetOrigin (out x, out y);
var a = Widget.Allocation;
x += a.X;
y += a.Y;
return new Point (x + widgetCoordinates.X, y + widgetCoordinates.Y);
}
Pango.FontDescription customFont;
public virtual object Font {
get {
return customFont ?? Widget.Style.FontDescription;
}
set {
var fd = (Pango.FontDescription) value;
customFont = fd;
Widget.ModifyFont (fd);
}
}
Color? customBackgroundColor;
public virtual Color BackgroundColor {
get {
return customBackgroundColor.HasValue ? customBackgroundColor.Value : Widget.Style.Background (Gtk.StateType.Normal).ToXwtValue ();
}
set {
customBackgroundColor = value;
AllocEventBox (visibleWindow: true);
OnSetBackgroundColor (value);
}
}
public virtual bool UsingCustomBackgroundColor {
get { return customBackgroundColor.HasValue; }
}
Gtk.Widget IGtkWidgetBackend.Widget {
get { return RootWidget; }
}
protected virtual Gtk.Widget EventsRootWidget {
get { return eventBox ?? Widget; }
}
bool needsEventBox = true; // require event box by default
protected virtual bool NeedsEventBox {
get { return needsEventBox; }
set { needsEventBox = value; }
}
public static Gtk.Widget GetWidget (IWidgetBackend w)
{
return w != null ? ((IGtkWidgetBackend)w).Widget : null;
}
public virtual void UpdateChildPlacement (IWidgetBackend childBackend)
{
SetChildPlacement (childBackend);
}
public static Gtk.Widget GetWidgetWithPlacement (IWidgetBackend childBackend)
{
var backend = (WidgetBackend)childBackend;
var child = backend.RootWidget;
var wrapper = child.Parent as WidgetPlacementWrapper;
if (wrapper != null)
return wrapper;
if (!NeedsAlignmentWrapper (backend.Frontend))
return child;
wrapper = new WidgetPlacementWrapper ();
wrapper.UpdatePlacement (backend.Frontend);
wrapper.Show ();
wrapper.Add (child);
return wrapper;
}
public static void RemoveChildPlacement (Gtk.Widget w)
{
if (w == null)
return;
if (w is WidgetPlacementWrapper) {
var wp = (WidgetPlacementWrapper)w;
wp.Remove (wp.Child);
}
}
static bool NeedsAlignmentWrapper (Widget fw)
{
return fw.HorizontalPlacement != WidgetPlacement.Fill || fw.VerticalPlacement != WidgetPlacement.Fill || fw.Margin.VerticalSpacing != 0 || fw.Margin.HorizontalSpacing != 0;
}
public static void SetChildPlacement (IWidgetBackend childBackend)
{
var backend = (WidgetBackend)childBackend;
var child = backend.RootWidget;
var wrapper = child.Parent as WidgetPlacementWrapper;
var fw = backend.Frontend;
if (!NeedsAlignmentWrapper (fw)) {
if (wrapper != null) {
wrapper.Remove (child);
GtkEngine.ReplaceChild (wrapper, child);
}
return;
}
if (wrapper == null) {
wrapper = new WidgetPlacementWrapper ();
wrapper.Show ();
GtkEngine.ReplaceChild (child, wrapper);
wrapper.Add (child);
}
wrapper.UpdatePlacement (fw);
}
public virtual void UpdateLayout ()
{
Widget.QueueResize ();
if (!Widget.IsRealized) {
// This is a workaround to a GTK bug. When a widget is inside a ScrolledWindow, sometimes the QueueResize call on
// the widget is ignored if the widget is not realized.
var p = Widget.Parent;
while (p != null && !(p is Gtk.ScrolledWindow))
p = p.Parent;
if (p != null)
p.QueueResize ();
}
}
protected void AllocEventBox (bool visibleWindow = false)
{
// Wraps the widget with an event box. Required for some
// widgets such as Label which doesn't have its own gdk window
if (visibleWindow) {
if (eventBox != null)
eventBox.VisibleWindow = true;
else if (EventsRootWidget is Gtk.EventBox)
((Gtk.EventBox)EventsRootWidget).VisibleWindow = true;
}
if (!NeedsEventBox) return;
if (eventBox == null && !EventsRootWidget.GetHasWindow()) {
if (EventsRootWidget is Gtk.EventBox) {
((Gtk.EventBox)EventsRootWidget).VisibleWindow = visibleWindow;
return;
}
eventBox = new Gtk.EventBox ();
eventBox.Visible = Widget.Visible;
eventBox.Sensitive = Widget.Sensitive;
eventBox.VisibleWindow = visibleWindow;
GtkEngine.ReplaceChild (Widget, eventBox);
eventBox.Add (Widget);
}
}
public virtual void EnableEvent (object eventId)
{
if (eventId is WidgetEvent) {
WidgetEvent ev = (WidgetEvent) eventId;
switch (ev) {
case WidgetEvent.DragLeave:
AllocEventBox ();
EventsRootWidget.DragLeave += HandleWidgetDragLeave;
break;
case WidgetEvent.DragStarted:
AllocEventBox ();
EventsRootWidget.DragBegin += HandleWidgetDragBegin;
break;
case WidgetEvent.KeyPressed:
Widget.KeyPressEvent += HandleKeyPressEvent;
break;
case WidgetEvent.KeyReleased:
Widget.KeyReleaseEvent += HandleKeyReleaseEvent;
break;
case WidgetEvent.GotFocus:
EventsRootWidget.AddEvents ((int)Gdk.EventMask.FocusChangeMask);
Widget.FocusGrabbed += HandleWidgetFocusInEvent;
break;
case WidgetEvent.LostFocus:
EventsRootWidget.AddEvents ((int)Gdk.EventMask.FocusChangeMask);
Widget.FocusOutEvent += HandleWidgetFocusOutEvent;
break;
case WidgetEvent.MouseEntered:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.EnterNotifyMask);
EventsRootWidget.EnterNotifyEvent += HandleEnterNotifyEvent;
break;
case WidgetEvent.MouseExited:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.LeaveNotifyMask);
EventsRootWidget.LeaveNotifyEvent += HandleLeaveNotifyEvent;
break;
case WidgetEvent.ButtonPressed:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.ButtonPressMask);
EventsRootWidget.ButtonPressEvent += HandleButtonPressEvent;
break;
case WidgetEvent.ButtonReleased:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.ButtonReleaseMask);
EventsRootWidget.ButtonReleaseEvent += HandleButtonReleaseEvent;
break;
case WidgetEvent.MouseMoved:
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.PointerMotionMask);
EventsRootWidget.MotionNotifyEvent += HandleMotionNotifyEvent;
break;
case WidgetEvent.BoundsChanged:
Widget.SizeAllocated += HandleWidgetBoundsChanged;
break;
case WidgetEvent.MouseScrolled:
AllocEventBox();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.ScrollMask);
Widget.ScrollEvent += HandleScrollEvent;
break;
case WidgetEvent.TextInput:
if (EditableWidget != null) {
EditableWidget.TextInserted += HandleTextInserted;
} else {
RunWhenRealized (delegate {
if (IMContext == null) {
IMContext = new Gtk.IMMulticontext ();
IMContext.ClientWindow = EventsRootWidget.GdkWindow;
IMContext.Commit += HandleImCommitEvent;
}
});
Widget.KeyPressEvent += HandleTextInputKeyPressEvent;
Widget.KeyReleaseEvent += HandleTextInputKeyReleaseEvent;
}
break;
}
if ((ev & dragDropEvents) != 0 && (enabledEvents & dragDropEvents) == 0) {
// Enabling a drag&drop event for the first time
AllocEventBox ();
EventsRootWidget.DragDrop += HandleWidgetDragDrop;
EventsRootWidget.DragMotion += HandleWidgetDragMotion;
EventsRootWidget.DragDataReceived += HandleWidgetDragDataReceived;
}
if ((ev & WidgetEvent.PreferredSizeCheck) != 0) {
EnableSizeCheckEvents ();
}
enabledEvents |= ev;
}
}
public virtual void DisableEvent (object eventId)
{
if (eventId is WidgetEvent) {
WidgetEvent ev = (WidgetEvent) eventId;
switch (ev) {
case WidgetEvent.DragLeave:
EventsRootWidget.DragLeave -= HandleWidgetDragLeave;
break;
case WidgetEvent.DragStarted:
EventsRootWidget.DragBegin -= HandleWidgetDragBegin;
break;
case WidgetEvent.KeyPressed:
Widget.KeyPressEvent -= HandleKeyPressEvent;
break;
case WidgetEvent.KeyReleased:
Widget.KeyReleaseEvent -= HandleKeyReleaseEvent;
break;
case WidgetEvent.GotFocus:
Widget.FocusInEvent -= HandleWidgetFocusInEvent;
break;
case WidgetEvent.LostFocus:
Widget.FocusOutEvent -= HandleWidgetFocusOutEvent;
break;
case WidgetEvent.MouseEntered:
EventsRootWidget.EnterNotifyEvent -= HandleEnterNotifyEvent;
break;
case WidgetEvent.MouseExited:
EventsRootWidget.LeaveNotifyEvent -= HandleLeaveNotifyEvent;
break;
case WidgetEvent.ButtonPressed:
if (!EventsRootWidget.IsRealized)
EventsRootWidget.Events &= ~Gdk.EventMask.ButtonPressMask;
EventsRootWidget.ButtonPressEvent -= HandleButtonPressEvent;
break;
case WidgetEvent.ButtonReleased:
if (!EventsRootWidget.IsRealized)
EventsRootWidget.Events &= Gdk.EventMask.ButtonReleaseMask;
EventsRootWidget.ButtonReleaseEvent -= HandleButtonReleaseEvent;
break;
case WidgetEvent.MouseMoved:
if (!EventsRootWidget.IsRealized)
EventsRootWidget.Events &= Gdk.EventMask.PointerMotionMask;
EventsRootWidget.MotionNotifyEvent -= HandleMotionNotifyEvent;
break;
case WidgetEvent.BoundsChanged:
Widget.SizeAllocated -= HandleWidgetBoundsChanged;
break;
case WidgetEvent.MouseScrolled:
if (!EventsRootWidget.IsRealized)
EventsRootWidget.Events &= ~Gdk.EventMask.ScrollMask;
Widget.ScrollEvent -= HandleScrollEvent;
break;
case WidgetEvent.TextInput:
if (EditableWidget != null) {
EditableWidget.TextInserted -= HandleTextInserted;
} else {
if (IMContext != null)
IMContext.Commit -= HandleImCommitEvent;
Widget.KeyPressEvent -= HandleTextInputKeyPressEvent;
Widget.KeyReleaseEvent -= HandleTextInputKeyReleaseEvent;
}
break;
}
enabledEvents &= ~ev;
if ((ev & dragDropEvents) != 0 && (enabledEvents & dragDropEvents) == 0) {
// All drag&drop events have been disabled
EventsRootWidget.DragDrop -= HandleWidgetDragDrop;
EventsRootWidget.DragMotion -= HandleWidgetDragMotion;
EventsRootWidget.DragDataReceived -= HandleWidgetDragDataReceived;
}
if ((ev & WidgetEvent.PreferredSizeCheck) != 0) {
DisableSizeCheckEvents ();
}
if ((ev & WidgetEvent.GotFocus) == 0 && (enabledEvents & WidgetEvent.LostFocus) == 0 && !EventsRootWidget.IsRealized) {
EventsRootWidget.Events &= ~Gdk.EventMask.FocusChangeMask;
}
}
}
Gdk.Rectangle lastAllocation;
void HandleWidgetBoundsChanged (object o, Gtk.SizeAllocatedArgs args)
{
if (Widget.Allocation != lastAllocation) {
lastAllocation = Widget.Allocation;
ApplicationContext.InvokeUserCode (EventSink.OnBoundsChanged);
}
}
[GLib.ConnectBefore]
void HandleKeyReleaseEvent (object o, Gtk.KeyReleaseEventArgs args)
{
KeyEventArgs kargs = GetKeyReleaseEventArgs (args);
if (kargs == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnKeyReleased (kargs);
});
if (kargs.Handled)
args.RetVal = true;
}
protected virtual KeyEventArgs GetKeyReleaseEventArgs (Gtk.KeyReleaseEventArgs args)
{
Key k = (Key)args.Event.KeyValue;
ModifierKeys m = ModifierKeys.None;
if ((args.Event.State & Gdk.ModifierType.ShiftMask) != 0)
m |= ModifierKeys.Shift;
if ((args.Event.State & Gdk.ModifierType.ControlMask) != 0)
m |= ModifierKeys.Control;
if ((args.Event.State & Gdk.ModifierType.Mod1Mask) != 0)
m |= ModifierKeys.Alt;
return new KeyEventArgs (k, (int)args.Event.KeyValue, m, false, (long)args.Event.Time, string.Empty, string.Empty, args.Event);
}
[GLib.ConnectBefore]
void HandleKeyPressEvent (object o, Gtk.KeyPressEventArgs args)
{
KeyEventArgs kargs = GetKeyPressEventArgs (args);
if (kargs == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnKeyPressed (kargs);
});
if (kargs.Handled)
args.RetVal = true;
}
protected virtual KeyEventArgs GetKeyPressEventArgs (Gtk.KeyPressEventArgs args)
{
Key k = (Key)args.Event.KeyValue;
ModifierKeys m = args.Event.State.ToXwtValue ();
return new KeyEventArgs (k, (int)args.Event.KeyValue, m, false, (long)args.Event.Time, string.Empty, string.Empty, args.Event);
}
protected Gtk.IMContext IMContext { get; set; }
[GLib.ConnectBefore]
void HandleTextInserted (object o, Gtk.TextInsertedArgs args)
{
if (String.IsNullOrEmpty (args.GetText ()))
return;
var pargs = new TextInputEventArgs (args.GetText ());
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnTextInput (pargs);
});
if (pargs.Handled)
((GLib.Object)o).StopSignal ("insert-text");
}
[GLib.ConnectBefore]
void HandleTextInputKeyReleaseEvent (object o, Gtk.KeyReleaseEventArgs args)
{
if (IMContext != null)
IMContext.FilterKeypress (args.Event);
}
[GLib.ConnectBefore]
void HandleTextInputKeyPressEvent (object o, Gtk.KeyPressEventArgs args)
{
if (IMContext != null)
IMContext.FilterKeypress (args.Event);
// new lines are not triggered by im, handle them here
if (args.Event.Key == Gdk.Key.Return ||
args.Event.Key == Gdk.Key.ISO_Enter ||
args.Event.Key == Gdk.Key.KP_Enter) {
var pargs = new TextInputEventArgs (Environment.NewLine);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnTextInput (pargs);
});
}
}
[GLib.ConnectBefore]
void HandleImCommitEvent (object o, Gtk.CommitArgs args)
{
if (String.IsNullOrEmpty (args.Str))
return;
var pargs = new TextInputEventArgs (args.Str);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnTextInput (pargs);
});
if (pargs.Handled)
args.RetVal = true;
}
[GLib.ConnectBefore]
void HandleScrollEvent(object o, Gtk.ScrollEventArgs args)
{
var a = GetScrollEventArgs (args);
if (a == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnMouseScrolled(a);
});
if (a.Handled)
args.RetVal = true;
}
protected virtual MouseScrolledEventArgs GetScrollEventArgs (Gtk.ScrollEventArgs args)
{
var direction = args.Event.Direction.ToXwtValue ();
var pointer_coords = EventsRootWidget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y);
return new MouseScrolledEventArgs ((long) args.Event.Time, pointer_coords.X, pointer_coords.Y, direction);
}
[GLib.ConnectBefore]
void HandleWidgetFocusOutEvent (object o, Gtk.FocusOutEventArgs args)
{
ApplicationContext.InvokeUserCode (EventSink.OnLostFocus);
}
[GLib.ConnectBefore]
void HandleWidgetFocusInEvent (object o, EventArgs args)
{
if (!CanGetFocus)
return;
ApplicationContext.InvokeUserCode (EventSink.OnGotFocus);
}
[GLib.ConnectBefore]
void HandleLeaveNotifyEvent (object o, Gtk.LeaveNotifyEventArgs args)
{
if (args.Event.Detail == Gdk.NotifyType.Inferior)
return;
ApplicationContext.InvokeUserCode (EventSink.OnMouseExited);
}
[GLib.ConnectBefore]
void HandleEnterNotifyEvent (object o, Gtk.EnterNotifyEventArgs args)
{
if (args.Event.Detail == Gdk.NotifyType.Inferior)
return;
ApplicationContext.InvokeUserCode (EventSink.OnMouseEntered);
}
protected virtual void OnEnterNotifyEvent (Gtk.EnterNotifyEventArgs args) {}
[GLib.ConnectBefore]
void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args)
{
var a = GetMouseMovedEventArgs (args);
if (a == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnMouseMoved (a);
});
if (a.Handled)
args.RetVal = true;
}
protected virtual MouseMovedEventArgs GetMouseMovedEventArgs (Gtk.MotionNotifyEventArgs args)
{
var pointer_coords = EventsRootWidget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y);
return new MouseMovedEventArgs ((long) args.Event.Time, pointer_coords.X, pointer_coords.Y);
}
[GLib.ConnectBefore]
void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args)
{
var a = GetButtonReleaseEventArgs (args);
if (a == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnButtonReleased (a);
});
if (a.Handled)
args.RetVal = true;
}
protected virtual ButtonEventArgs GetButtonReleaseEventArgs (Gtk.ButtonReleaseEventArgs args)
{
var a = new ButtonEventArgs ();
var pointer_coords = EventsRootWidget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y);
a.X = pointer_coords.X;
a.Y = pointer_coords.Y;
a.Button = (PointerButton) args.Event.Button;
return a;
}
[GLib.ConnectBeforeAttribute]
void HandleButtonPressEvent (object o, Gtk.ButtonPressEventArgs args)
{
var a = GetButtonPressEventArgs (args);
if (a == null)
return;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnButtonPressed (a);
});
if (a.Handled)
args.RetVal = true;
}
protected virtual ButtonEventArgs GetButtonPressEventArgs (Gtk.ButtonPressEventArgs args)
{
var a = new ButtonEventArgs ();
var pointer_coords = EventsRootWidget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y);
a.X = pointer_coords.X;
a.Y = pointer_coords.Y;
a.Button = (PointerButton) args.Event.Button;
if (args.Event.Type == Gdk.EventType.TwoButtonPress)
a.MultiplePress = 2;
else if (args.Event.Type == Gdk.EventType.ThreeButtonPress)
a.MultiplePress = 3;
else
a.MultiplePress = 1;
a.IsContextMenuTrigger = args.Event.TriggersContextMenu ();
return a;
}
[GLib.ConnectBefore]
void HandleWidgetDragMotion (object o, Gtk.DragMotionArgs args)
{
args.RetVal = DoDragMotion (args.Context, args.X, args.Y, args.Time);
}
internal bool DoDragMotion (Gdk.DragContext context, int x, int y, uint time)
{
DragDropInfo.LastDragPosition = new Point (x, y);
DragDropAction ac;
if ((enabledEvents & WidgetEvent.DragOverCheck) == 0) {
if ((enabledEvents & WidgetEvent.DragOver) != 0)
ac = DragDropAction.Default;
else
ac = ConvertDragAction (DragDropInfo.DestDragAction);
}
else {
// This is a workaround to what seems to be a mac gtk bug.
// Suggested action is set to all when no control key is pressed
var cact = ConvertDragAction (context.Actions);
if (cact == DragDropAction.All)
cact = DragDropAction.Move;
var target = Gtk.Drag.DestFindTarget (EventsRootWidget, context, null);
var targetTypes = Util.GetDragTypes (new Gdk.Atom[] { target });
DragOverCheckEventArgs da = new DragOverCheckEventArgs (new Point (x, y), targetTypes, cact);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnDragOverCheck (da);
});
ac = da.AllowedAction;
if ((enabledEvents & WidgetEvent.DragOver) == 0 && ac == DragDropAction.Default)
ac = DragDropAction.None;
}
if (ac == DragDropAction.None) {
OnSetDragStatus (context, x, y, time, (Gdk.DragAction)0);
return true;
}
else if (ac == DragDropAction.Default) {
// Undefined, we need more data
QueryDragData (context, time, true);
return true;
}
else {
// Gtk.Drag.Highlight (Widget);
OnSetDragStatus (context, x, y, time, ConvertDragAction (ac));
return true;
}
}
[GLib.ConnectBefore]
void HandleWidgetDragDrop (object o, Gtk.DragDropArgs args)
{
args.RetVal = DoDragDrop (args.Context, args.X, args.Y, args.Time);
}
internal bool DoDragDrop (Gdk.DragContext context, int x, int y, uint time)
{
DragDropInfo.LastDragPosition = new Point (x, y);
var cda = ConvertDragAction (context.GetSelectedAction());
DragDropResult res;
if ((enabledEvents & WidgetEvent.DragDropCheck) == 0) {
if ((enabledEvents & WidgetEvent.DragDrop) != 0)
res = DragDropResult.None;
else
res = DragDropResult.Canceled;
}
else {
DragCheckEventArgs da = new DragCheckEventArgs (new Point (x, y), Util.GetDragTypes (context.ListTargets ()), cda);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnDragDropCheck (da);
});
res = da.Result;
if ((enabledEvents & WidgetEvent.DragDrop) == 0 && res == DragDropResult.None)
res = DragDropResult.Canceled;
}
if (res == DragDropResult.Canceled) {
Gtk.Drag.Finish (context, false, false, time);
return true;
}
else if (res == DragDropResult.Success) {
Gtk.Drag.Finish (context, true, cda == DragDropAction.Move, time);
return true;
}
else {
// Undefined, we need more data
QueryDragData (context, time, false);
return true;
}
}
void HandleWidgetDragLeave (object o, Gtk.DragLeaveArgs args)
{
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnDragLeave (EventArgs.Empty);
});
}
void QueryDragData (Gdk.DragContext ctx, uint time, bool isMotionEvent)
{
DragDropInfo.DragDataForMotion = isMotionEvent;
DragDropInfo.DragData = new TransferDataStore ();
DragDropInfo.DragDataRequests = DragDropInfo.ValidDropTypes.Length;
foreach (var t in DragDropInfo.ValidDropTypes) {
var at = Gdk.Atom.Intern (t.Target, true);
Gtk.Drag.GetData (EventsRootWidget, ctx, at, time);
}
}
void HandleWidgetDragDataReceived (object o, Gtk.DragDataReceivedArgs args)
{
args.RetVal = DoDragDataReceived (args.Context, args.X, args.Y, args.SelectionData, args.Info, args.Time);
}
internal bool DoDragDataReceived (Gdk.DragContext context, int x, int y, Gtk.SelectionData selectionData, uint info, uint time)
{
if (DragDropInfo.DragDataRequests == 0) {
// Got the data without requesting it. Create the datastore here
DragDropInfo.DragData = new TransferDataStore ();
DragDropInfo.LastDragPosition = new Point (x, y);
DragDropInfo.DragDataRequests = 1;
}
DragDropInfo.DragDataRequests--;
// If multiple drag/drop data types are supported, we need to iterate through them all and
// append the data. If one of the supported data types is not found, there's no need to
// bail out. We must raise the event
Util.GetSelectionData (ApplicationContext, selectionData, DragDropInfo.DragData);
if (DragDropInfo.DragDataRequests == 0) {
if (DragDropInfo.DragDataForMotion) {
// If no specific action is set, it means that no key has been pressed.
// In that case, use Move or Copy or Link as default (when allowed, in this order).
var cact = ConvertDragAction (context.Actions);
if (cact != DragDropAction.Copy && cact != DragDropAction.Move && cact != DragDropAction.Link) {
if (cact.HasFlag (DragDropAction.Move))
cact = DragDropAction.Move;
else if (cact.HasFlag (DragDropAction.Copy))
cact = DragDropAction.Copy;
else if (cact.HasFlag (DragDropAction.Link))
cact = DragDropAction.Link;
else
cact = DragDropAction.None;
}
DragOverEventArgs da = new DragOverEventArgs (DragDropInfo.LastDragPosition, DragDropInfo.DragData, cact);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnDragOver (da);
});
OnSetDragStatus (context, (int)DragDropInfo.LastDragPosition.X, (int)DragDropInfo.LastDragPosition.Y, time, ConvertDragAction (da.AllowedAction));
return true;
}
else {
// Use Context.Action here since that's the action selected in DragOver
var cda = ConvertDragAction (context.GetSelectedAction());
DragEventArgs da = new DragEventArgs (DragDropInfo.LastDragPosition, DragDropInfo.DragData, cda);
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnDragDrop (da);
});
Gtk.Drag.Finish (context, da.Success, cda == DragDropAction.Move, time);
return true;
}
} else
return false;
}
protected virtual void OnSetDragStatus (Gdk.DragContext context, int x, int y, uint time, Gdk.DragAction action)
{
Gdk.Drag.Status (context, action, time);
}
void HandleWidgetDragBegin (object o, Gtk.DragBeginArgs args)
{
// If SetDragSource has not been called, ignore the event
if (DragDropInfo.SourceDragAction == default (Gdk.DragAction))
return;
DragStartData sdata = null;
ApplicationContext.InvokeUserCode (delegate {
sdata = EventSink.OnDragStarted ();
});
if (sdata == null)
return;
DragDropInfo.CurrentDragData = sdata.Data;
if (sdata.ImageBackend != null) {
var gi = (GtkImage)sdata.ImageBackend;
var img = gi.ToPixbuf (ApplicationContext, Widget);
Gtk.Drag.SetIconPixbuf (args.Context, img, (int)sdata.HotX, (int)sdata.HotY);
}
HandleDragBegin (null, args);
}
class IconInitializer
{
public Gdk.Pixbuf Image;
public double HotX, HotY;
public Gtk.Widget Widget;
public static void Init (Gtk.Widget w, Gdk.Pixbuf image, double hotX, double hotY)
{
IconInitializer ii = new WidgetBackend.IconInitializer ();
ii.Image = image;
ii.HotX = hotX;
ii.HotY = hotY;
ii.Widget = w;
w.DragBegin += ii.Begin;
}
void Begin (object o, Gtk.DragBeginArgs args)
{
Gtk.Drag.SetIconPixbuf (args.Context, Image, (int)HotX, (int)HotY);
Widget.DragBegin -= Begin;
}
}
public void DragStart (DragStartData sdata)
{
AllocEventBox ();
Gdk.DragAction action = ConvertDragAction (sdata.DragAction);
DragDropInfo.CurrentDragData = sdata.Data;
EventsRootWidget.DragBegin += HandleDragBegin;
if (sdata.ImageBackend != null) {
var img = ((GtkImage)sdata.ImageBackend).ToPixbuf (ApplicationContext, Widget);
IconInitializer.Init (EventsRootWidget, img, sdata.HotX, sdata.HotY);
}
Gtk.Drag.Begin (EventsRootWidget, Util.BuildTargetTable (sdata.Data.DataTypes), action, 1, Gtk.Global.CurrentEvent ?? new Gdk.Event (IntPtr.Zero));
}
void HandleDragBegin (object o, Gtk.DragBeginArgs args)
{
EventsRootWidget.DragEnd += HandleWidgetDragEnd;
EventsRootWidget.DragFailed += HandleDragFailed;
EventsRootWidget.DragDataDelete += HandleDragDataDelete;
EventsRootWidget.DragDataGet += HandleWidgetDragDataGet;
}
void HandleWidgetDragDataGet (object o, Gtk.DragDataGetArgs args)
{
Util.SetDragData (DragDropInfo.CurrentDragData, args);
}
void HandleDragFailed (object o, Gtk.DragFailedArgs args)
{
Console.WriteLine ("FAILED");
}
void HandleDragDataDelete (object o, Gtk.DragDataDeleteArgs args)
{
DoDragaDataDelete ();
}
internal void DoDragaDataDelete ()
{
FinishDrag (true);
}
void HandleWidgetDragEnd (object o, Gtk.DragEndArgs args)
{
FinishDrag (false);
}
void FinishDrag (bool delete)
{
EventsRootWidget.DragEnd -= HandleWidgetDragEnd;
EventsRootWidget.DragDataGet -= HandleWidgetDragDataGet;
EventsRootWidget.DragFailed -= HandleDragFailed;
EventsRootWidget.DragDataDelete -= HandleDragDataDelete;
EventsRootWidget.DragBegin -= HandleDragBegin; // This event is subscribed only when manualy starting a drag
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnDragFinished (new DragFinishedEventArgs (delete));
});
}
public void SetDragTarget (TransferDataType[] types, DragDropAction dragAction)
{
DragDropInfo.DestDragAction = ConvertDragAction (dragAction);
var table = Util.BuildTargetTable (types);
DragDropInfo.ValidDropTypes = (Gtk.TargetEntry[]) table;
OnSetDragTarget (DragDropInfo.ValidDropTypes, DragDropInfo.DestDragAction);
}
protected virtual void OnSetDragTarget (Gtk.TargetEntry[] table, Gdk.DragAction actions)
{
AllocEventBox ();
Gtk.Drag.DestSet (EventsRootWidget, Gtk.DestDefaults.Highlight, table, actions);
}
public void SetDragSource (TransferDataType[] types, DragDropAction dragAction)
{
AllocEventBox ();
DragDropInfo.SourceDragAction = ConvertDragAction (dragAction);
var table = Util.BuildTargetTable (types);
OnSetDragSource (Gdk.ModifierType.Button1Mask, (Gtk.TargetEntry[]) table, DragDropInfo.SourceDragAction);
}
protected virtual void OnSetDragSource (Gdk.ModifierType modifierType, Gtk.TargetEntry[] table, Gdk.DragAction actions)
{
Gtk.Drag.SourceSet (EventsRootWidget, modifierType, table, actions);
}
Gdk.DragAction ConvertDragAction (DragDropAction dragAction)
{
Gdk.DragAction action = (Gdk.DragAction)0;
if ((dragAction & DragDropAction.Copy) != 0)
action |= Gdk.DragAction.Copy;
if ((dragAction & DragDropAction.Move) != 0)
action |= Gdk.DragAction.Move;
if ((dragAction & DragDropAction.Link) != 0)
action |= Gdk.DragAction.Link;
return action;
}
DragDropAction ConvertDragAction (Gdk.DragAction dragAction)
{
DragDropAction action = (DragDropAction)0;
if ((dragAction & Gdk.DragAction.Copy) != 0)
action |= DragDropAction.Copy;
if ((dragAction & Gdk.DragAction.Move) != 0)
action |= DragDropAction.Move;
if ((dragAction & Gdk.DragAction.Link) != 0)
action |= DragDropAction.Link;
return action;
}
}
public interface IGtkWidgetBackend
{
Gtk.Widget Widget { get; }
}
class WidgetPlacementWrapper: Gtk.Alignment, IConstraintProvider
{
public WidgetPlacementWrapper (): base (0, 0, 1, 1)
{
}
public void UpdatePlacement (Xwt.Widget widget)
{
LeftPadding = (uint)widget.MarginLeft;
RightPadding = (uint)widget.MarginRight;
TopPadding = (uint)widget.MarginTop;
BottomPadding = (uint)widget.MarginBottom;
Xalign = (float) widget.HorizontalPlacement.GetValue ();
Yalign = (float) widget.VerticalPlacement.GetValue ();
Xscale = (widget.HorizontalPlacement == WidgetPlacement.Fill) ? 1 : 0;
Yscale = (widget.VerticalPlacement == WidgetPlacement.Fill) ? 1 : 0;
}
#region IConstraintProvider implementation
public void GetConstraints (Gtk.Widget target, out SizeConstraint width, out SizeConstraint height)
{
if (Parent is IConstraintProvider)
((IConstraintProvider)Parent).GetConstraints (this, out width, out height);
else
width = height = SizeConstraint.Unconstrained;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="VideoControlsManager.cs" company="Google Inc.">
// 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>
//-----------------------------------------------------------------------
namespace GoogleVR.VideoDemo
{
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class VideoControlsManager : MonoBehaviour
{
private GameObject pauseSprite;
private GameObject playSprite;
private Slider videoScrubber;
private Slider volumeSlider;
private GameObject volumeWidget;
private GameObject settingsPanel;
private GameObject bufferedBackground;
private Vector3 basePosition;
private Text videoPosition;
private Text videoDuration;
public GvrVideoPlayerTexture Player { set; get; }
void Awake()
{
foreach (Text t in GetComponentsInChildren<Text>())
{
if (t.gameObject.name == "curpos_text")
{
videoPosition = t;
}
else if (t.gameObject.name == "duration_text")
{
videoDuration = t;
}
}
foreach (RawImage raw in GetComponentsInChildren<RawImage>(true))
{
if (raw.gameObject.name == "playImage")
{
playSprite = raw.gameObject;
}
else if (raw.gameObject.name == "pauseImage")
{
pauseSprite = raw.gameObject;
}
}
foreach (Slider s in GetComponentsInChildren<Slider>(true))
{
if (s.gameObject.name == "video_slider")
{
videoScrubber = s;
videoScrubber.maxValue = 100;
videoScrubber.minValue = 0;
foreach (Image i in videoScrubber.GetComponentsInChildren<Image>())
{
if (i.gameObject.name == "BufferedBackground")
{
bufferedBackground = i.gameObject;
}
}
}
else if (s.gameObject.name == "volume_slider")
{
volumeSlider = s;
}
}
foreach (RectTransform obj in GetComponentsInChildren<RectTransform>(true))
{
if (obj.gameObject.name == "volume_widget")
{
volumeWidget = obj.gameObject;
}
else if (obj.gameObject.name == "settings_panel")
{
settingsPanel = obj.gameObject;
}
}
}
void Start()
{
foreach (ScrubberEvents s in GetComponentsInChildren<ScrubberEvents>(true))
{
s.ControlManager = this;
}
if (Player != null)
{
Player.Init();
}
}
void Update()
{
if ((!Player.VideoReady || Player.IsPaused))
{
pauseSprite.SetActive(false);
playSprite.SetActive(true);
}
else if (Player.VideoReady && !Player.IsPaused)
{
pauseSprite.SetActive(true);
playSprite.SetActive(false);
}
if (Player.VideoReady)
{
if (basePosition == Vector3.zero)
{
basePosition = videoScrubber.handleRect.localPosition;
}
videoScrubber.maxValue = Player.VideoDuration;
videoScrubber.value = Player.CurrentPosition;
float pct = Player.BufferedPercentage / 100.0f;
float sx = Mathf.Clamp(pct, 0, 1f);
bufferedBackground.transform.localScale = new Vector3(sx, 1, 1);
bufferedBackground.transform.localPosition =
new Vector3(basePosition.x - (basePosition.x * sx), 0, 0);
videoPosition.text = FormatTime(Player.CurrentPosition);
videoDuration.text = FormatTime(Player.VideoDuration);
if (volumeSlider != null)
{
volumeSlider.minValue = 0;
volumeSlider.maxValue = Player.MaxVolume;
volumeSlider.value = Player.CurrentVolume;
}
}
else
{
videoScrubber.value = 0;
}
}
public void OnVolumeUp()
{
if (Player.CurrentVolume < Player.MaxVolume)
{
Player.CurrentVolume += 1;
}
}
public void OnVolumeDown()
{
if (Player.CurrentVolume > 0)
{
Player.CurrentVolume -= 1;
}
}
public void OnToggleVolume()
{
bool visible = !volumeWidget.activeSelf;
volumeWidget.SetActive(visible);
// close settings if volume opens.
settingsPanel.SetActive(settingsPanel.activeSelf && !visible);
}
public void OnToggleSettings()
{
bool visible = !settingsPanel.activeSelf;
settingsPanel.SetActive(visible);
// close settings if volume opens.
volumeWidget.SetActive(volumeWidget.activeSelf && !visible);
}
public void OnPlayPause()
{
bool isPaused = Player.IsPaused;
if (isPaused)
{
Player.Play();
}
else
{
Player.Pause();
}
pauseSprite.SetActive(isPaused);
playSprite.SetActive(!isPaused);
CloseSubPanels();
}
public void OnVolumePositionChanged(float val)
{
if (Player.VideoReady)
{
Debug.Log("Setting current volume to " + val);
Player.CurrentVolume = (int)val;
}
}
public void CloseSubPanels()
{
volumeWidget.SetActive(false);
settingsPanel.SetActive(false);
}
public void Fade(bool show)
{
if (show)
{
StartCoroutine(DoAppear());
}
else
{
StartCoroutine(DoFade());
}
}
IEnumerator DoAppear()
{
CanvasGroup cg = GetComponent<CanvasGroup>();
while (cg.alpha < 1.0)
{
cg.alpha += Time.deltaTime * 2;
yield return null;
}
cg.interactable = true;
yield break;
}
IEnumerator DoFade()
{
CanvasGroup cg = GetComponent<CanvasGroup>();
while (cg.alpha > 0)
{
cg.alpha -= Time.deltaTime;
yield return null;
}
cg.interactable = false;
CloseSubPanels();
yield break;
}
private string FormatTime(long ms)
{
int sec = ((int)(ms / 1000L));
int mn = sec / 60;
sec = sec % 60;
int hr = mn / 60;
mn = mn % 60;
if (hr > 0)
{
return string.Format("{0:00}:{1:00}:{2:00}", hr, mn, sec);
}
return string.Format("{0:00}:{1:00}", mn, sec);
}
}
}
| |
/*
###
# # ######### _______ _ _ ______ _ _
## ######## @ ## |______ | | | ____ | |
################## | |_____| |_____| |_____|
## ############# f r a m e w o r k
# # #########
###
(c) 2015 - 2017 FUGU framework project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace Fugu.Text
{
public class Text : IEnumerable<char>
{
public static Text Empty => new Text();
private StringBuilder _stringBuilder;
private bool _valueDirty = false;
private string _value;
public Text()
: this(null)
{
}
public Text(string value)
{
_value = value ?? string.Empty;
}
public char this[int index]
{
get
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (!_valueDirty)
{
if (_value.Length <= index)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return _value[index];
}
else
{
if (_stringBuilder.Length <= index)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return _stringBuilder[index];
}
}
}
public string Value
{
get
{
if (_valueDirty)
{
_value = _stringBuilder.ToString();
_valueDirty = false;
_stringBuilder.Length = 0;
}
return _value;
}
set
{
_value = value ?? string.Empty;
_valueDirty = false;
if (_stringBuilder != null)
{
_stringBuilder.Length = 0;
}
}
}
public int Length
{
get
{
if (!_valueDirty)
{
return _value?.Length ?? 0;
}
else
{
return _stringBuilder.Length;
}
}
}
public void Clear()
{
if (!_valueDirty)
{
_value = null;
}
else
{
_stringBuilder.Length = 0;
}
}
public char[] ToCharArray()
{
return Value.ToCharArray();
}
public char[] ToCharArray(int startIndex, int length)
{
return Value.ToCharArray(startIndex, length);
}
public Text Append(bool value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(sbyte value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(byte value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(char value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(short value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(int value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(long value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(float value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(double value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(decimal value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(ushort value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(uint value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(ulong value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(Object value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(char[] value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text Append(string value)
{
PrepareStringBuilder();
_stringBuilder.Append(value);
return this;
}
public Text AppendLine()
{
PrepareStringBuilder();
_stringBuilder.AppendLine();
return this;
}
public Text AppendLine(string value)
{
PrepareStringBuilder();
_stringBuilder.AppendLine(value);
return this;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return Value;
}
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
protected bool Equals(Text other)
{
return string.Equals(Value, other.Value);
}
/// <summary>Returns an enumerator that iterates through the collection.</summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<char> GetEnumerator()
{
return ((IEnumerable<char>)Value).GetEnumerator();
}
/// <summary>Determines whether the specified object is equal to the current object.</summary>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Text)obj);
}
/// <summary>Serves as the default hash function. </summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
return Value?.GetHashCode() ?? 0;
}
public static bool operator ==(Text left, Text right)
{
return Equals(left, right);
}
public static bool operator !=(Text left, Text right)
{
return !Equals(left, right);
}
public static implicit operator string(Text text)
{
return text.Value;
}
public static implicit operator Text(string value)
{
return new Text(value);
}
// try inlining for better performance
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void PrepareStringBuilder()
{
if (_stringBuilder == null)
{
_stringBuilder = new StringBuilder();
}
if (_value != null)
{
_stringBuilder.Append(_value);
_value = null;
_valueDirty = true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using OpenGL;
namespace GameCore.Render.OpenGl4CSharp
{
public class FontVAO : IDisposable
{
private ShaderProgram program;
private VBO<Vector3> vertices;
private VBO<Vector2> uvs;
private VBO<int> triangles;
public Vector2 Position { get; set; }
public FontVAO(ShaderProgram program, VBO<Vector3> vertices, VBO<Vector2> uvs, VBO<int> triangles)
{
this.program = program;
this.vertices = vertices;
this.uvs = uvs;
this.triangles = triangles;
}
public void Draw()
{
if (vertices == null) return;
program.Use();
program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(Position.x, Position.y, 0)));
Gl.BindBufferToShaderAttribute(vertices, program, "vertexPosition");
Gl.BindBufferToShaderAttribute(uvs, program, "vertexUV");
Gl.BindBuffer(triangles);
Gl.DrawElements(BeginMode.Triangles, triangles.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
}
public void Dispose()
{
vertices.Dispose();
uvs.Dispose();
triangles.Dispose();
vertices = null;
}
}
/// <summary>
/// The BMFont class can be used to load both the texture and data files associated with
/// the free BMFont tool (http://www.angelcode.com/products/bmfont/)
/// This tool allows
/// </summary>
public class BMFont
{
/// <summary>
/// Stores the ID, height, width and UV information for a single bitmap character
/// as exported by the BMFont tool.
/// </summary>
private struct Character
{
public char id;
public float x1;
public float y1;
public float x2;
public float y2;
public float width;
public float height;
public Character(char _id, float _x1, float _y1, float _x2, float _y2, float _w, float _h)
{
id = _id;
x1 = _x1;
y1 = _y1;
x2 = _x2;
y2 = _y2;
width = _w;
height = _h;
}
}
/// <summary>
/// Text justification to be applied when creating the VAO representing some text.
/// </summary>
public enum Justification
{
Left,
Center,
Right
}
/// <summary>
/// The font texture associated with this bitmap font.
/// </summary>
public Texture FontTexture { get; private set; }
private Dictionary<char, Character> characters = new Dictionary<char, Character>();
/// <summary>
/// The height (in pixels) of this bitmap font.
/// </summary>
public int Height { get; private set; }
/// <summary>
/// Loads both a font descriptor table and the associated texture as exported by BMFont.
/// </summary>
/// <param name="descriptorPath">The path to the font descriptor table.</param>
/// <param name="texturePath">The path to the font texture.</param>
public BMFont(string descriptorPath, string texturePath)
{
this.FontTexture = new Texture(texturePath);
using (StreamReader stream = new StreamReader(descriptorPath))
{
while (!stream.EndOfStream)
{
string line = stream.ReadLine();
if (line.StartsWith("char"))
{
// chars lets the program know how many characters are in this file, ignore it
if (line.StartsWith("chars")) continue;
// split up the different entries on this line to be parsed
string[] split = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int id = 0;
float x1 = 0, y1 = 0, x2 = 0, y2 = 0, w = 0, h = 0;
// parse the contents of the line, looking for key words
for (int i = 0; i < split.Length; i++)
{
if (!split[i].Contains("=")) continue;
string code = split[i].Substring(0, split[i].IndexOf('='));
int value = int.Parse(split[i].Substring(split[i].IndexOf('=') + 1));
if (code == "id") id = value;
else if (code == "x") x1 = (float)value / FontTexture.Size.Width;
else if (code == "y") y1 = 1 - (float)value / FontTexture.Size.Height;
else if (code == "width")
{
w = (float)value;
x2 = x1 + w / FontTexture.Size.Width;
}
else if (code == "height")
{
h = (float)value;
y2 = y1 - h / FontTexture.Size.Height;
this.Height = Math.Max(this.Height, value);
}
}
// store this character into our dictionary (if it doesn't already exist)
Character c = new Character((char)id, x1, y1, x2, y2, w, h);
if (!characters.ContainsKey(c.id)) characters.Add(c.id, c);
}
}
}
}
/// <summary>
/// Gets the width (in pixels) of a string of text using the current loaded font.
/// </summary>
/// <param name="text">The string of text to measure the width of.</param>
/// <returns>The width (in pixels) of the provided text.</returns>
public int GetWidth(string text)
{
int width = 0;
for (int i = 0; i < text.Length; i++)
width += (int)characters[characters.ContainsKey(text[i]) ? text[i] : ' '].width;
return width;
}
public FontVAO CreateString(ShaderProgram program, string text, Justification justification = Justification.Left)
{
Vector3[] vertices = new Vector3[text.Length * 4];
Vector2[] uvs = new Vector2[text.Length * 4];
int[] indices = new int[text.Length * 6];
int xpos = 0, width = 0;
// calculate the initial x position depending on the justification
if (justification != Justification.Left)
{
for (int i = 0; i < text.Length; i++)
width += (int)characters[characters.ContainsKey(text[i]) ? text[i] : ' '].width;
if (justification == Justification.Right) xpos = -width;
else xpos = -width / 2;
}
for (int i = 0; i < text.Length; i++)
{
// grab the character, replacing with ' ' if the character isn't loaded
Character ch = characters[characters.ContainsKey(text[i]) ? text[i] : ' '];
vertices[i * 4 + 0] = new Vector3(xpos, ch.height, 0);
vertices[i * 4 + 1] = new Vector3(xpos, 0, 0);
vertices[i * 4 + 2] = new Vector3(xpos + ch.width, ch.height, 0);
vertices[i * 4 + 3] = new Vector3(xpos + ch.width, 0, 0);
xpos += (int)ch.width;
uvs[i * 4 + 0] = new Vector2(ch.x1, ch.y1);
uvs[i * 4 + 1] = new Vector2(ch.x1, ch.y2);
uvs[i * 4 + 2] = new Vector2(ch.x2, ch.y1);
uvs[i * 4 + 3] = new Vector2(ch.x2, ch.y2);
indices[i * 6 + 0] = i * 4 + 2;
indices[i * 6 + 1] = i * 4 + 0;
indices[i * 6 + 2] = i * 4 + 1;
indices[i * 6 + 3] = i * 4 + 3;
indices[i * 6 + 4] = i * 4 + 2;
indices[i * 6 + 5] = i * 4 + 1;
}
// Create the vertex buffer objects and then create the array object
return new FontVAO(program, new VBO<Vector3>(vertices), new VBO<Vector2>(uvs), new VBO<int>(indices, BufferTarget.ElementArrayBuffer));
}
public static string FontVertexSource = @"
#version 130
uniform mat4 model_matrix;
uniform mat4 ortho_matrix;
in vec3 vertexPosition;
in vec2 vertexUV;
out vec2 uv;
void main(void)
{
uv = vertexUV;
gl_Position = ortho_matrix * model_matrix * vec4(vertexPosition, 1);
}";
public static string FontFragmentSource = @"
#version 130
uniform sampler2D texture;
uniform vec3 color;
in vec2 uv;
out vec4 fragment;
void main(void)
{
vec4 texel = texture2D(texture, uv);
fragment = vec4(texel.rgb * color, texel.a);
}
";
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using log4net;
using NetGore;
using NetGore.Graphics;
using NetGore.Graphics.GUI;
using NetGore.IO;
using NetGore.World;
using SFML.Graphics;
using SFML.Window;
namespace DemoGame.Client
{
class CharacterSelectionScreen : GameMenuScreenBase
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const string ScreenName = "character selection";
const string _title = "Select Character";
const string _unusedCharacterSlotText = "unused";
CharacterSlotControl[] _charSlotControls;
ClientSockets _sockets = null;
/// <summary>
/// Initializes a new instance of the <see cref="CharacterSelectionScreen"/> class.
/// </summary>
/// <param name="screenManager">The <see cref="IScreenManager"/> to add this <see cref="GameScreen"/> to.</param>
public CharacterSelectionScreen(IScreenManager screenManager) : base(screenManager, ScreenName, _title)
{
PlayMusic = true;
}
/// <summary>
/// Handles screen activation, which occurs every time the screen becomes the current
/// active screen. Objects in here often will want to be destroyed on Deactivate().
/// </summary>
public override void Activate()
{
base.Activate();
if (_sockets == null)
_sockets = ClientSockets.Instance;
// Add event listeners
_sockets.PacketHandler.AccountCharacterInfos.AccountCharactersLoaded -= HandleCharInfosUpdated;
_sockets.PacketHandler.AccountCharacterInfos.AccountCharactersLoaded += HandleCharInfosUpdated;
// Ensure the old user info is cleared out
ScreenManager.GetScreen<GameplayScreen>().UserInfo.Clear();
}
/// <summary>
/// Handles screen deactivation, which occurs every time the screen changes from being
/// the current active screen. Good place to clean up any objects created in <see cref="GameScreen.Activate"/>().
/// </summary>
public override void Deactivate()
{
base.Deactivate();
// Remove event listeners
if (_sockets != null)
{
_sockets.PacketHandler.AccountCharacterInfos.AccountCharactersLoaded -= HandleCharInfosUpdated;
}
}
void ClickButton_CharacterSelection(object sender, MouseButtonEventArgs e)
{
var src = (CharacterSlotControl)sender;
var slot = src.Slot;
AccountCharacterInfo charInfo;
if (!_sockets.PacketHandler.AccountCharacterInfos.TryGetInfo(slot, out charInfo))
ScreenManager.SetScreen<CreateCharacterScreen>();
else
{
using (var pw = ClientPacket.SelectAccountCharacter(slot))
{
_sockets.Send(pw, ClientMessageType.System);
}
}
}
void ClickButton_DeleteCharacter(Control sender, MouseButtonEventArgs args)
{
var s = (CharacterSlotControl)sender;
var ci = s.CharInfo;
if (ci == null)
return;
var mb = new DeleteCharacterMessageBox(GUIManager, ci.Name, ci.Index) { Font = GameScreenHelper.DefaultChatFont };
mb.DeleteRequested += DeleteCharacterMsgBox_DeleteRequested;
}
void ClickButton_LogOut(object sender, MouseButtonEventArgs e)
{
// Change screens
ScreenManager.SetScreen<LoginScreen>();
// Disconnect the socket so we actually "log out"
if (_sockets != null)
{
try
{
_sockets.Disconnect();
}
catch (Exception ex)
{
// Ignore errors in disconnecting
Debug.Fail("Disconnect failed: " + ex);
if (log.IsErrorEnabled)
log.ErrorFormat("Failed to disconnect client socket ({0}). Exception: {1}", _sockets, ex);
}
}
}
/// <summary>
/// Handles the corresponding event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs{Byte}"/> instance containing the event data.</param>
void DeleteCharacterMsgBox_DeleteRequested(Control sender, EventArgs<byte> e)
{
using (var pw = ClientPacket.DeleteAccountCharacter(e.Item1))
{
_sockets.Send(pw, ClientMessageType.System);
}
}
/// <summary>
/// Handles the corresponding event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void HandleCharInfosUpdated(AccountCharacterInfos sender, EventArgs e)
{
for (var i = 0; i < _charSlotControls.Length; i++)
{
AccountCharacterInfo charInfo;
if (_sockets.PacketHandler.AccountCharacterInfos.TryGetInfo((byte)i, out charInfo))
_charSlotControls[i].CharInfo = charInfo;
else
_charSlotControls[i].CharInfo = null;
}
}
/// <summary>
/// Handles initialization of the GameScreen. This will be invoked after the GameScreen has been
/// completely and successfully added to the ScreenManager. It is highly recommended that you
/// use this instead of the constructor. This is invoked only once.
/// </summary>
public override void Initialize()
{
base.Initialize();
var cScreen = new Panel(GUIManager, Vector2.Zero, ScreenManager.ScreenSize);
// Create the menu buttons
var menuButtons = GameScreenHelper.CreateMenuButtons(ScreenManager, cScreen, "Log out");
menuButtons["Log out"].Clicked += ClickButton_LogOut;
// Create the character slots
_charSlotControls = new CharacterSlotControl[GameData.MaxCharactersPerAccount];
for (var i = 0; i < GameData.MaxCharactersPerAccount; i++)
{
var c = new CharacterSlotControl(cScreen, (byte)i);
c.Clicked += ClickButton_CharacterSelection;
c.DeleteCharacterClicked += ClickButton_DeleteCharacter;
_charSlotControls[i] = c;
}
}
/// <summary>
/// A <see cref="Control"/> that displays a single character slot.
/// </summary>
class CharacterSlotControl : Panel
{
/// <summary>
/// The name of this <see cref="Control"/> for when looking up the skin information.
/// </summary>
const string _controlSkinName = "Character Slot";
/// <summary>
/// The number of slot controls per row.
/// </summary>
const int _slotsPerRow = 3;
/// <summary>
/// The y-axis offset from the top of the screen (so we don't cover the title).
/// </summary>
const float _yOffset = 120f;
/// <summary>
/// The color of the slot number text.
/// </summary>
static readonly Color _slotNumberTextColor = Color.LimeGreen;
/// <summary>
/// The size of each individual slot.
/// </summary>
static readonly Vector2 _slotSize = new Vector2(320, 180);
/// <summary>
/// The padding between the slots and between the slots.
/// </summary>
static readonly Vector2 slotPadding = new Vector2(10, 10);
readonly Label _charNameControl;
readonly PreviewCharacter _character = new PreviewCharacter();
readonly Label _deleteControl;
readonly byte _slot;
readonly Label _slotNumberControl;
AccountCharacterInfo _charInfo;
ControlBorder _defaultBorder;
ControlBorder _mouseOverBorder;
/// <summary>
/// Initializes a new instance of the <see cref="CharacterSlotControl"/> class.
/// </summary>
/// <param name="parent">Parent <see cref="Control"/> of this <see cref="Control"/>.</param>
/// <param name="slot">The 0-base slot number.</param>
/// <exception cref="NullReferenceException"><paramref name="parent"/> is null.</exception>
public CharacterSlotControl(Control parent, byte slot) : base(parent, Vector2.Zero, _slotSize)
{
_slot = slot;
Size = _slotSize;
UpdatePositioning();
// Create child controls
// Slot number
_slotNumberControl = CreateChildLabel(new Vector2(2, 2), (Slot + 1) + ". ");
_slotNumberControl.ForeColor = _slotNumberTextColor;
// Delete
_deleteControl = CreateChildLabel(Vector2.Zero, "X", true);
_deleteControl.Position = new Vector2(ClientSize.X - _deleteControl.ClientSize.X, 0) - new Vector2(2);
_deleteControl.Clicked += _deleteControl_Clicked;
_deleteControl.ForeColor = Color.White;
_deleteControl.MouseEnter += delegate { _deleteControl.ForeColor = Color.Red; };
_deleteControl.MouseLeave += delegate { _deleteControl.ForeColor = Color.White; };
_deleteControl.IsVisible = (CharInfo != null);
// Character name
var charNameControlPos = _slotNumberControl.Position + new Vector2(_slotNumberControl.Size.X + 2, 0f);
_charNameControl = CreateChildLabel(charNameControlPos, _unusedCharacterSlotText);
}
/// <summary>
/// Notifies listeners when the Delete Character button has been clicked.
/// </summary>
public event TypedEventHandler<Control, MouseButtonEventArgs> DeleteCharacterClicked;
/// <summary>
/// Gets or sets the <see cref="AccountCharacterInfo"/> for the character in this slot.
/// </summary>
public AccountCharacterInfo CharInfo
{
get { return _charInfo; }
set
{
_charInfo = value;
if (CharInfo != null)
_charNameControl.Text = CharInfo.Name;
else
_charNameControl.Text = _unusedCharacterSlotText;
if (_character != null && _charInfo != null)
{
_character.Body = _charInfo.BodyID;
_character.SetPaperDollLayers(_charInfo.EquippedBodies);
_character.Position = GetCharacterPosition();
}
_deleteControl.IsVisible = (_charInfo != null);
}
}
/// <summary>
/// Gets the 0-based character slot number that this control is for.
/// </summary>
public byte Slot
{
get { return _slot; }
}
Label CreateChildLabel(Vector2 position, string text, bool enabled = false)
{
var ret = GameScreenHelper.CreateMenuLabel(this, position, text);
ret.IsEnabled = enabled;
ret.CanFocus = enabled;
ret.IsBoundToParentArea = false;
return ret;
}
/// <summary>
/// Draws the <see cref="Control"/>.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to draw to.</param>
protected override void DrawControl(ISpriteBatch spriteBatch)
{
base.DrawControl(spriteBatch);
if (_character != null && _charInfo != null)
_character.Draw(spriteBatch);
}
/// <summary>
/// Gets the position to draw the <see cref="PreviewCharacter"/> at.
/// </summary>
/// <returns>The position to draw the <see cref="PreviewCharacter"/> at.</returns>
Vector2 GetCharacterPosition()
{
var sp = ScreenPosition;
var cs = ClientSize;
var max = sp + cs;
var center = sp + (cs / 2f);
var offset = _character.Size / 2f;
var pos = center - offset;
pos.Y = max.Y - _character.Size.Y - 5;
return pos;
}
/// <summary>
/// When overridden in the derived class, loads the skinning information for the <see cref="Control"/>
/// from the given <paramref name="skinManager"/>.
/// </summary>
/// <param name="skinManager">The <see cref="ISkinManager"/> to load the skinning information from.</param>
public override void LoadSkin(ISkinManager skinManager)
{
_defaultBorder = skinManager.GetBorder(_controlSkinName);
_mouseOverBorder = skinManager.GetBorder(_controlSkinName, "MouseOver");
if (IsMouseEntered)
Border = _mouseOverBorder;
else
Border = _defaultBorder;
}
/// <summary>
/// Handles when the mouse has entered the area of the <see cref="Control"/>.
/// This is called immediately before <see cref="Control.OnMouseEnter"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseEnter"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseEnter(MouseMoveEventArgs e)
{
base.OnMouseEnter(e);
Border = _mouseOverBorder;
}
/// <summary>
/// Handles when the mouse has left the area of the <see cref="Control"/>.
/// This is called immediately before <see cref="Control.OnMouseLeave"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseLeave"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseLeave(MouseMoveEventArgs e)
{
base.OnMouseLeave(e);
Border = _defaultBorder;
}
/// <summary>
/// Sets the default values for the <see cref="Control"/>. This should always begin with a call to the
/// base class's method to ensure that changes to settings are hierchical.
/// </summary>
protected override void SetDefaultValues()
{
base.SetDefaultValues();
ResizeToChildren = false;
}
/// <summary>
/// Updates the <see cref="Control"/>. This is called for every <see cref="Control"/>, even if it is disabled or
/// not visible.
/// </summary>
/// <param name="currentTime">The current time in milliseconds.</param>
protected override void UpdateControl(TickCount currentTime)
{
base.UpdateControl(currentTime);
if (_character != null)
_character.Update();
}
/// <summary>
/// Updates the position of the slot.
/// </summary>
void UpdatePositioning()
{
// Find the x-axis offset to use to center the slots
var xOffset = _slotSize.X * _slotsPerRow;
xOffset += (_slotsPerRow - 1) * slotPadding.X;
xOffset = Parent.ClientSize.X - xOffset;
xOffset /= 2;
var offset = new Vector2(xOffset, _yOffset);
// Find the position
var row = Slot % _slotsPerRow;
var column = Slot / _slotsPerRow;
var pos = offset + (new Vector2(row, column) * (slotPadding + _slotSize));
Position = pos;
}
/// <summary>
/// Handles the Clicked event of the <see cref="_deleteControl"/> control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="SFML.Window.MouseButtonEventArgs"/> instance containing the event data.</param>
void _deleteControl_Clicked(Control sender, MouseButtonEventArgs e)
{
if (DeleteCharacterClicked != null)
DeleteCharacterClicked.Raise(this, e);
}
}
class DeleteCharacterMessageBox : MessageBox
{
const string _msgBoxMsg =
@"Are you sure you wish to delete your character `{0}`? This cannot be undone!
Press ""OK"" to delete the character, or ""Cancel"" to abort.";
const string _msgBoxTitle = "Delete character?";
readonly byte _slot;
public DeleteCharacterMessageBox(IGUIManager guiManager, string characterName, byte slot)
: base(guiManager, _msgBoxTitle, string.Format(_msgBoxMsg, characterName), MessageBoxButton.OkCancel)
{
_slot = slot;
DisposeOnSelection = true;
}
/// <summary>
/// Notifies listeners when this control has requested the character to be deleted.
/// </summary>
public event TypedEventHandler<Control, EventArgs<byte>> DeleteRequested;
public byte CharacterSlot
{
get { return _slot; }
}
/// <summary>
/// Handles when the <see cref="MessageBox"/> has been closed from an option button being clicked.
/// This is called immediately before <see cref="CheckBox.TickedOverSpriteChanged"/>.
/// Override this method instead of using an event hook on <see cref="CheckBox.TickedOverSpriteChanged"/> when possible.
/// </summary>
/// <param name="button">The button that was used to close the <see cref="MessageBox"/>.</param>
protected override void OnOptionSelected(MessageBoxButton button)
{
if (button == MessageBoxButton.Ok)
{
if (DeleteRequested != null)
DeleteRequested.Raise(this, EventArgsHelper.Create(CharacterSlot));
}
base.OnOptionSelected(button);
}
}
class PreviewCharacter : Entity, IGetTime
{
static readonly SkeletonManager _skeletonManager = SkeletonManager.Create(ContentPaths.Build);
readonly ICharacterSprite _characterSprite;
BodyID _body;
/// <summary>
/// Initializes a new instance of the <see cref="PreviewCharacter"/> class.
/// </summary>
public PreviewCharacter()
{
_characterSprite = Character.CreateCharacterSprite(this, this, _skeletonManager);
}
public BodyID Body
{
get { return _body; }
set
{
if (_body == value)
return;
_body = value;
var bodyInfo = BodyInfoManager.Instance.GetBody(Body);
if (bodyInfo != null)
{
_characterSprite.SetSet(bodyInfo.Walk, bodyInfo.Size);
_characterSprite.SetBody(bodyInfo.Body);
_characterSprite.SetPaperDollLayers(null);
Size = bodyInfo.Size;
}
else
{
_characterSprite.SetSet(null, Vector2.Zero);
_characterSprite.SetBody(null);
_characterSprite.SetPaperDollLayers(null);
Size = Vector2.One;
}
}
}
/// <summary>
/// When overridden in the derived class, gets if this <see cref="Entity"/> will collide against
/// walls. If false, this <see cref="Entity"/> will pass through walls and completely ignore them.
/// </summary>
public override bool CollidesAgainstWalls
{
get { return false; }
}
public void Draw(ISpriteBatch sb)
{
_characterSprite.Draw(sb, Position, Direction.East, Color.White);
}
public void SetPaperDollLayers(IEnumerable<string> values)
{
_characterSprite.SetPaperDollLayers(values);
}
public void Update()
{
if (_characterSprite != null)
_characterSprite.Update(GetTime());
}
/// <summary>
/// Perform pre-collision velocity and position updating.
/// </summary>
/// <param name="map">The map.</param>
/// <param name="deltaTime">The amount of that that has elapsed time since last update.</param>
public override void UpdateVelocity(IMap map, int deltaTime)
{
}
#region IGetTime Members
/// <summary>
/// Gets the current time in milliseconds.
/// </summary>
/// <returns>The current time in milliseconds.</returns>
public TickCount GetTime()
{
return TickCount.Now;
}
#endregion
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace RemoteConfig.Server.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* 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
*
* 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.
*/
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace Avro
{
internal delegate T Function<T>();
/// <summary>
/// Class for record schemas
/// </summary>
public class RecordSchema : NamedSchema
{
/// <summary>
/// List of fields in the record
/// </summary>
public List<Field> Fields { get; private set; }
/// <summary>
/// Number of fields in the record
/// </summary>
public int Count { get { return Fields.Count; } }
/// <summary>
/// Map of field name and Field object for faster field lookups
/// </summary>
private readonly IDictionary<string, Field> fieldLookup;
private readonly IDictionary<string, Field> fieldAliasLookup;
private bool request;
/// <summary>
/// Static function to return new instance of the record schema
/// </summary>
/// <param name="type">type of record schema, either record or error</param>
/// <param name="jtok">JSON object for the record schema</param>
/// <param name="props">dictionary that provides access to custom properties</param>
/// <param name="names">list of named schema already read</param>
/// <param name="encspace">enclosing namespace of the records schema</param>
/// <returns>new RecordSchema object</returns>
internal static RecordSchema NewInstance(Type type, JToken jtok, PropertyMap props, SchemaNames names, string encspace)
{
bool request = false;
JToken jfields = jtok["fields"]; // normal record
if (null == jfields)
{
jfields = jtok["request"]; // anonymous record from messages
if (null != jfields) request = true;
}
if (null == jfields)
throw new SchemaParseException($"'fields' cannot be null for record at '{jtok.Path}'");
if (jfields.Type != JTokenType.Array)
throw new SchemaParseException($"'fields' not an array for record at '{jtok.Path}'");
var name = GetName(jtok, encspace);
var aliases = NamedSchema.GetAliases(jtok, name.Space, name.EncSpace);
var fields = new List<Field>();
var fieldMap = new Dictionary<string, Field>();
var fieldAliasMap = new Dictionary<string, Field>();
RecordSchema result;
try
{
result = new RecordSchema(type, name, aliases, props, fields, request, fieldMap, fieldAliasMap, names,
JsonHelper.GetOptionalString(jtok, "doc"));
}
catch (SchemaParseException e)
{
throw new SchemaParseException($"{e.Message} at '{jtok.Path}'", e);
}
int fieldPos = 0;
foreach (JObject jfield in jfields)
{
string fieldName = JsonHelper.GetRequiredString(jfield, "name");
Field field = createField(jfield, fieldPos++, names, name.Namespace); // add record namespace for field look up
fields.Add(field);
try
{
addToFieldMap(fieldMap, fieldName, field);
addToFieldMap(fieldAliasMap, fieldName, field);
if (null != field.Aliases) // add aliases to field lookup map so reader function will find it when writer field name appears only as an alias on the reader field
foreach (string alias in field.Aliases)
addToFieldMap(fieldAliasMap, alias, field);
}
catch (SchemaParseException e)
{
throw new SchemaParseException($"{e.Message} at '{jfield.Path}'", e);
}
}
return result;
}
/// <summary>
/// Constructor for the record schema
/// </summary>
/// <param name="type">type of record schema, either record or error</param>
/// <param name="name">name of the record schema</param>
/// <param name="aliases">list of aliases for the record name</param>
/// <param name="props">custom properties on this schema</param>
/// <param name="fields">list of fields for the record</param>
/// <param name="request">true if this is an anonymous record with 'request' instead of 'fields'</param>
/// <param name="fieldMap">map of field names and field objects</param>
/// <param name="fieldAliasMap">map of field aliases and field objects</param>
/// <param name="names">list of named schema already read</param>
/// <param name="doc">documentation for this named schema</param>
private RecordSchema(Type type, SchemaName name, IList<SchemaName> aliases, PropertyMap props,
List<Field> fields, bool request, IDictionary<string, Field> fieldMap,
IDictionary<string, Field> fieldAliasMap, SchemaNames names, string doc)
: base(type, name, aliases, props, names, doc)
{
if (!request && null == name.Name) throw new SchemaParseException("name cannot be null for record schema.");
this.Fields = fields;
this.request = request;
this.fieldLookup = fieldMap;
this.fieldAliasLookup = fieldAliasMap;
}
/// <summary>
/// Creates a new field for the record
/// </summary>
/// <param name="jfield">JSON object for the field</param>
/// <param name="pos">position number of the field</param>
/// <param name="names">list of named schemas already read</param>
/// <param name="encspace">enclosing namespace of the records schema</param>
/// <returns>new Field object</returns>
private static Field createField(JToken jfield, int pos, SchemaNames names, string encspace)
{
var name = JsonHelper.GetRequiredString(jfield, "name");
var doc = JsonHelper.GetOptionalString(jfield, "doc");
var jorder = JsonHelper.GetOptionalString(jfield, "order");
Field.SortOrder sortorder = Field.SortOrder.ignore;
if (null != jorder)
sortorder = (Field.SortOrder) Enum.Parse(typeof(Field.SortOrder), jorder);
var aliases = Field.GetAliases(jfield);
var props = Schema.GetProperties(jfield);
var defaultValue = jfield["default"];
JToken jtype = jfield["type"];
if (null == jtype)
throw new SchemaParseException($"'type' was not found for field: name at '{jfield.Path}'");
var schema = Schema.ParseJson(jtype, names, encspace);
return new Field(schema, name, aliases, pos, doc, defaultValue, sortorder, props);
}
private static void addToFieldMap(Dictionary<string, Field> map, string name, Field field)
{
if (map.ContainsKey(name))
throw new SchemaParseException("field or alias " + name + " is a duplicate name");
map.Add(name, field);
}
/// <summary>
/// Returns the field with the given name.
/// </summary>
/// <param name="name">field name</param>
/// <returns>Field object</returns>
public Field this[string name]
{
get
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
Field field;
return fieldLookup.TryGetValue(name, out field) ? field : null;
}
}
/// <summary>
/// Returns true if and only if the record contains a field by the given name.
/// </summary>
/// <param name="fieldName">The name of the field</param>
/// <returns>true if the field exists, false otherwise</returns>
public bool Contains(string fieldName)
{
return fieldLookup.ContainsKey(fieldName);
}
/// <summary>
/// Gets a field with a specified name.
/// </summary>
/// <param name="fieldName">Name of the field to get.</param>
/// <param name="field">
/// When this method returns true, contains the field with the specified name. When this
/// method returns false, null.
/// </param>
/// <returns>True if a field with the specified name exists; false otherwise.</returns>
public bool TryGetField(string fieldName, out Field field)
{
return fieldLookup.TryGetValue(fieldName, out field);
}
/// <summary>
/// Gets a field with a specified alias.
/// </summary>
/// <param name="fieldName">Alias of the field to get.</param>
/// <param name="field">
/// When this method returns true, contains the field with the specified alias. When this
/// method returns false, null.
/// </param>
/// <returns>True if a field with the specified alias exists; false otherwise.</returns>
public bool TryGetFieldAlias(string fieldName, out Field field)
{
return fieldAliasLookup.TryGetValue(fieldName, out field);
}
/// <summary>
/// Returns an enumerator which enumerates over the fields of this record schema
/// </summary>
/// <returns>Enumerator over the field in the order of their definition</returns>
public IEnumerator<Field> GetEnumerator()
{
return Fields.GetEnumerator();
}
/// <summary>
/// Writes the records schema in JSON format
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="names">list of named schemas already written</param>
/// <param name="encspace">enclosing namespace of the record schema</param>
protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
{
base.WriteJsonFields(writer, names, encspace);
// we allow reading for empty fields, so writing of records with empty fields are allowed as well
if (request)
writer.WritePropertyName("request");
else
writer.WritePropertyName("fields");
writer.WriteStartArray();
if (null != this.Fields && this.Fields.Count > 0)
{
foreach (Field field in this)
field.writeJson(writer, names, this.Namespace); // use the namespace of the record for the fields
}
writer.WriteEndArray();
}
/// <summary>
/// Compares equality of two record schemas
/// </summary>
/// <param name="obj">record schema to compare against this schema</param>
/// <returns>true if the two schemas are equal, false otherwise</returns>
public override bool Equals(object obj)
{
if (obj == this) return true;
if (obj != null && obj is RecordSchema)
{
RecordSchema that = obj as RecordSchema;
return protect(() => true, () =>
{
if (this.SchemaName.Equals(that.SchemaName) && this.Count == that.Count)
{
for (int i = 0; i < Fields.Count; i++) if (!Fields[i].Equals(that.Fields[i])) return false;
return areEqual(that.Props, this.Props);
}
return false;
}, that);
}
return false;
}
/// <summary>
/// Hash code function
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return protect(() => 0, () =>
{
int result = SchemaName.GetHashCode();
foreach (Field f in Fields) result += 29 * f.GetHashCode();
result += getHashCode(Props);
return result;
}, this);
}
/// <summary>
/// Checks if this schema can read data written by the given schema. Used for decoding data.
/// </summary>
/// <param name="writerSchema">writer schema</param>
/// <returns>true if this and writer schema are compatible based on the AVRO specification, false otherwise</returns>
public override bool CanRead(Schema writerSchema)
{
if ((writerSchema.Tag != Type.Record) && (writerSchema.Tag != Type.Error)) return false;
RecordSchema that = writerSchema as RecordSchema;
return protect(() => true, () =>
{
if (!that.SchemaName.Equals(SchemaName))
if (!InAliases(that.SchemaName))
return false;
foreach (Field f in this)
{
Field f2 = that[f.Name];
if (null == f2) // reader field not in writer field, check aliases of reader field if any match with a writer field
if (null != f.Aliases)
foreach (string alias in f.Aliases)
{
f2 = that[alias];
if (null != f2) break;
}
if (f2 == null && f.DefaultValue != null)
continue; // Writer field missing, reader has default.
if (f2 != null && f.Schema.CanRead(f2.Schema)) continue; // Both fields exist and are compatible.
return false;
}
return true;
}, that);
}
private class RecordSchemaPair
{
public readonly RecordSchema first;
public readonly RecordSchema second;
public RecordSchemaPair(RecordSchema first, RecordSchema second)
{
this.first = first;
this.second = second;
}
}
[ThreadStatic]
private static List<RecordSchemaPair> seen;
/**
* We want to protect against infinite recursion when the schema is recursive. We look into a thread local
* to see if we have been into this if so, we execute the bypass function otherwise we execute the main function.
* Before executing the main function, we ensure that we create a marker so that if we come back here recursively
* we can detect it.
*
* The infinite loop happens in ToString(), Equals() and GetHashCode() methods.
* Though it does not happen for CanRead() because of the current implemenation of UnionSchema's can read,
* it could potenitally happen.
* We do a linear seach for the marker as we don't expect the list to be very long.
*/
private T protect<T>(Function<T> bypass, Function<T> main, RecordSchema that)
{
if (seen == null)
seen = new List<RecordSchemaPair>();
else if (seen.Find((RecordSchemaPair rs) => rs.first == this && rs.second == that) != null)
return bypass();
RecordSchemaPair p = new RecordSchemaPair(this, that);
seen.Add(p);
try { return main(); }
finally { seen.Remove(p); }
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
using umbraco.cms.businesslogic.template;
using System.Collections.Generic;
namespace Umbraco.Web.Mvc
{
public class RenderRouteHandler : IRouteHandler
{
// Define reserved dictionary keys for controller, action and area specified in route additional values data
private static class ReservedAdditionalKeys
{
internal const string Controller = "c";
internal const string Action = "a";
internal const string Area = "ar";
}
public RenderRouteHandler(IControllerFactory controllerFactory)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
_controllerFactory = controllerFactory;
}
/// <summary>
/// Contructor generally used for unit testing
/// </summary>
/// <param name="controllerFactory"></param>
/// <param name="umbracoContext"></param>
internal RenderRouteHandler(IControllerFactory controllerFactory, UmbracoContext umbracoContext)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
_controllerFactory = controllerFactory;
_umbracoContext = umbracoContext;
}
private readonly IControllerFactory _controllerFactory;
private readonly UmbracoContext _umbracoContext;
/// <summary>
/// Returns the current UmbracoContext
/// </summary>
public UmbracoContext UmbracoContext
{
get { return _umbracoContext ?? UmbracoContext.Current; }
}
#region IRouteHandler Members
/// <summary>
/// Assigns the correct controller based on the Umbraco request and returns a standard MvcHandler to prcess the response,
/// this also stores the render model into the data tokens for the current RouteData.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (UmbracoContext == null)
{
throw new NullReferenceException("There is not current UmbracoContext, it must be initialized before the RenderRouteHandler executes");
}
var docRequest = UmbracoContext.PublishedContentRequest;
if (docRequest == null)
{
throw new NullReferenceException("There is not current PublishedContentRequest, it must be initialized before the RenderRouteHandler executes");
}
SetupRouteDataForRequest(
new RenderModel(docRequest.PublishedContent, docRequest.Culture),
requestContext,
docRequest);
return GetHandlerForRoute(requestContext, docRequest);
}
#endregion
/// <summary>
/// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
/// </summary>
/// <param name="renderModel"></param>
/// <param name="requestContext"></param>
/// <param name="docRequest"></param>
internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
{
//put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
requestContext.RouteData.DataTokens.Add("umbraco", renderModel); //required for the RenderModelBinder and view engine
requestContext.RouteData.DataTokens.Add("umbraco-doc-request", docRequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add("umbraco-context", UmbracoContext); //required for UmbracoTemplatePage
}
private void UpdateRouteDataForRequest(RenderModel renderModel, RequestContext requestContext)
{
if (renderModel == null) throw new ArgumentNullException("renderModel");
if (requestContext == null) throw new ArgumentNullException("requestContext");
requestContext.RouteData.DataTokens["umbraco"] = renderModel;
// the rest should not change -- it's only the published content that has changed
}
/// <summary>
/// Checks the request and query strings to see if it matches the definition of having a Surface controller
/// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
internal static PostedDataProxyInfo GetFormInfo(RequestContext requestContext)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
//if it is a POST/GET then a value must be in the request
if (requestContext.HttpContext.Request.QueryString["ufprt"].IsNullOrWhiteSpace()
&& requestContext.HttpContext.Request.Form["ufprt"].IsNullOrWhiteSpace())
{
return null;
}
string encodedVal;
switch (requestContext.HttpContext.Request.RequestType)
{
case "POST":
//get the value from the request.
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.Form["ufprt"];
break;
case "GET":
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.QueryString["ufprt"];
break;
default:
return null;
}
string decryptedString;
try
{
decryptedString = encodedVal.DecryptWithMachineKey();
}
catch (FormatException)
{
LogHelper.Warn<RenderRouteHandler>("A value was detected in the ufprt parameter but Umbraco could not decrypt the string");
return null;
}
var parsedQueryString = HttpUtility.ParseQueryString(decryptedString);
var decodedParts = new Dictionary<string, string>();
foreach (var key in parsedQueryString.AllKeys)
{
decodedParts[key] = parsedQueryString[key];
}
//validate all required keys exist
//the controller
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Controller))
return null;
//the action
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Action))
return null;
//the area
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Area))
return null;
foreach (var item in decodedParts.Where(x => new[] {
ReservedAdditionalKeys.Controller,
ReservedAdditionalKeys.Action,
ReservedAdditionalKeys.Area }.Contains(x.Key) == false))
{
// Populate route with additional values which aren't reserved values so they eventually to action parameters
requestContext.RouteData.Values[item.Key] = item.Value;
}
//return the proxy info without the surface id... could be a local controller.
return new PostedDataProxyInfo
{
ControllerName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
ActionName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
Area = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
};
}
/// <summary>
/// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that
/// the right DataTokens are set.
/// </summary>
/// <param name="requestContext"></param>
/// <param name="postedInfo"></param>
internal static IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (postedInfo == null) throw new ArgumentNullException("postedInfo");
//set the standard route values/tokens
requestContext.RouteData.Values["controller"] = postedInfo.ControllerName;
requestContext.RouteData.Values["action"] = postedInfo.ActionName;
IHttpHandler handler;
//get the route from the defined routes
using (RouteTable.Routes.GetReadLock())
{
Route surfaceRoute;
if (postedInfo.Area.IsNullOrWhiteSpace())
{
//find the controller in the route table without an area
var surfaceRoutes = RouteTable.Routes.OfType<Route>()
.Where(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
x.DataTokens.ContainsKey("area") == false).ToList();
// If more than one route is found, find one with a matching action
if (surfaceRoutes.Count() > 1)
{
surfaceRoute = surfaceRoutes.FirstOrDefault(x =>
x.Defaults["action"] != null &&
x.Defaults["action"].ToString().InvariantEquals(postedInfo.ActionName));
}
else
{
surfaceRoute = surfaceRoutes.SingleOrDefault();
}
}
else
{
//find the controller in the route table with the specified area
surfaceRoute = RouteTable.Routes.OfType<Route>()
.SingleOrDefault(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
x.DataTokens.ContainsKey("area") &&
x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area));
}
if (surfaceRoute == null)
throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName);
//set the area if one is there.
if (surfaceRoute.DataTokens.ContainsKey("area"))
{
requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"];
}
//set the 'Namespaces' token so the controller factory knows where to look to construct it
if (surfaceRoute.DataTokens.ContainsKey("Namespaces"))
{
requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"];
}
handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext);
}
return handler;
}
/// <summary>
/// Returns a RouteDefinition object based on the current renderModel
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
/// <returns></returns>
internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");
var defaultControllerType = DefaultRenderMvcControllerResolver.Current.GetDefaultControllerType();
var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
//creates the default route definition which maps to the 'UmbracoController' controller
var def = new RouteDefinition
{
ControllerName = defaultControllerName,
ControllerType = defaultControllerType,
PublishedContentRequest = publishedContentRequest,
ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
HasHijackedRoute = false
};
//check that a template is defined), if it doesn't and there is a hijacked route it will just route
// to the index Action
if (publishedContentRequest.HasTemplate)
{
//the template Alias should always be already saved with a safe name.
//if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
// with the action name attribute.
var templateName = publishedContentRequest.TemplateAlias.Split('.')[0].ToSafeAlias();
def.ActionName = templateName;
}
//check if there's a custom controller assigned, base on the document type alias.
var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias);
//check if that controller exists
if (controllerType != null)
{
//ensure the controller is of type IRenderMvcController and ControllerBase
if (TypeHelper.IsTypeAssignableFrom<IRenderController>(controllerType)
&& TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType))
{
//set the controller and name to the custom one
def.ControllerType = controllerType;
def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
if (def.ControllerName != defaultControllerName)
{
def.HasHijackedRoute = true;
}
}
else
{
LogHelper.Warn<RenderRouteHandler>(
"The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.",
() => publishedContentRequest.PublishedContent.DocumentTypeAlias,
() => controllerType.FullName,
() => typeof(IRenderController).FullName,
() => typeof(ControllerBase).FullName);
//we cannot route to this custom controller since it is not of the correct type so we'll continue with the defaults
// that have already been set above.
}
}
//store the route definition
requestContext.RouteData.DataTokens["umbraco-route-def"] = def;
return def;
}
internal IHttpHandler GetHandlerOnMissingTemplate(PublishedContentRequest pcr)
{
if (pcr == null) throw new ArgumentNullException("pcr");
// missing template, so we're in a 404 here
// so the content, if any, is a custom 404 page of some sort
if (!pcr.HasPublishedContent)
// means the builder could not find a proper document to handle 404
return new PublishedContentNotFoundHandler();
if (!pcr.HasTemplate)
// means the engine could find a proper document, but the document has no template
// at that point there isn't much we can do and there is no point returning
// to Mvc since Mvc can't do much
return new PublishedContentNotFoundHandler("In addition, no template exists to render the custom 404.");
// so we have a template, so we should have a rendering engine
if (pcr.RenderingEngine == RenderingEngine.WebForms) // back to webforms ?
return GetWebFormsHandler();
if (pcr.RenderingEngine != RenderingEngine.Mvc) // else ?
return new PublishedContentNotFoundHandler("In addition, no rendering engine exists to render the custom 404.");
return null;
}
/// <summary>
/// this will determine the controller and set the values in the route data
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");
var routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
//Need to check for a special case if there is form data being posted back to an Umbraco URL
var postedInfo = GetFormInfo(requestContext);
if (postedInfo != null)
{
return HandlePostedValues(requestContext, postedInfo);
}
//Now we can check if we are supposed to render WebForms when the route has not been hijacked
if (publishedContentRequest.RenderingEngine == RenderingEngine.WebForms
&& publishedContentRequest.HasTemplate
&& routeDef.HasHijackedRoute == false)
{
return GetWebFormsHandler();
}
//here we need to check if there is no hijacked route and no template assigned, if this is the case
//we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
if (!publishedContentRequest.HasTemplate && !routeDef.HasHijackedRoute)
{
publishedContentRequest.UpdateOnMissingTemplate(); // will go 404
// HandleHttpResponseStatus returns a value indicating that the request should
// not be processed any further, eg because it has been redirect. then, exit.
if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest))
return null;
var handler = GetHandlerOnMissingTemplate(publishedContentRequest);
// if it's not null it can be either the PublishedContentNotFoundHandler (no document was
// found to handle 404, or document with no template was found) or the WebForms handler
// (a document was found and its template is WebForms)
// if it's null it means that a document was found and its template is Mvc
// if we have a handler, return now
if (handler != null)
return handler;
// else we are running Mvc
// update the route data - because the PublishedContent has changed
UpdateRouteDataForRequest(
new RenderModel(publishedContentRequest.PublishedContent, publishedContentRequest.Culture),
requestContext);
// update the route definition
routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
}
//no post values, just route to the controller/action requried (local)
requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
if (!string.IsNullOrWhiteSpace(routeDef.ActionName))
{
requestContext.RouteData.Values["action"] = routeDef.ActionName;
}
// Set the session state requirements
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));
// reset the friendly path so in the controllers and anything occuring after this point in time,
//the URL is reset back to the original request.
requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);
return new UmbracoMvcHandler(requestContext);
}
/// <summary>
/// Returns the handler for webforms requests
/// </summary>
/// <returns></returns>
internal static IHttpHandler GetWebFormsHandler()
{
return (global::umbraco.UmbracoDefault)BuildManager.CreateInstanceFromVirtualPath("~/default.aspx", typeof(global::umbraco.UmbracoDefault));
}
private SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext, string controllerName)
{
return _controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
}
}
| |
#pragma warning disable 675 // Bitwise-or operator used on a sign-extended operand
#region Java Info
/**
* Class GifDecoder - Decodes a GIF file into one or more frames.
* <br><pre>
* Example:
* GifDecoder d = new GifDecoder();
* d.read("sample.gif");
* int n = d.getFrameCount();
* for (int i = 0; i < n; i++) {
* BufferedImage frame = d.getFrame(i); // frame i
* int t = d.getDelay(i); // display duration of frame in milliseconds
* // do something with frame
* }
* </pre>
* No copyright asserted on the source code of this class. May be used for
* any purpose, however, refer to the Unisys LZW patent for any additional
* restrictions. Please forward any corrections to [email protected].
*
* @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's ImageMagick.
* @version 1.03 November 2003
*
*/
#endregion
using System;
using System.Collections;
using System.Drawing;
using System.IO;
namespace Free.Controls.TreeView
{
public class GifFrame
{
private Image _image;
public Image Image
{
get { return _image; }
}
private int _delay;
public int Delay
{
get { return _delay; }
}
public GifFrame(Image im, int del)
{
_image=im;
_delay=del;
}
}
public class GifDecoder
{
public const int StatusOK=0;//File read status: No errors.
public const int StatusFormatError=1; //File read status: Error decoding file (may be partially decoded)
public const int StatusOpenError=2; //Unable to open source.
private Stream inStream;
private int status;
private int width; // full image width
private int height; // full image height
private bool gctFlag; // global color table used
private int gctSize; // size of global color table
private int loopCount=1; // iterations; 0 = repeat forever
private int[] gct; // global color table
private int[] lct; // local color table
private int[] act; // active color table
private int bgIndex; // background color index
private int bgColor; // background color
private int lastBgColor; // previous bg color
private int pixelAspect; // pixel aspect ratio
private bool lctFlag; // local color table flag
private bool interlace; // interlace flag
private int lctSize; // local color table size
private int ix, iy, iw, ih; // current image rectangle
private Rectangle lastRect; // last image rect
private Image image; // current frame
private Bitmap bitmap;
private Image lastImage; // previous frame
private byte[] block=new byte[256]; // current data block
private int blockSize=0; // block size
// last graphic control extension info
private int dispose=0;
// 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
private int lastDispose=0;
private bool transparency=false; // use transparent color
private int delay=0; // delay in milliseconds
private int transIndex; // transparent color index
private const int MaxStackSize=4096;
// max decoder pixel stack size
// LZW decoder working arrays
private short[] prefix;
private byte[] suffix;
private byte[] pixelStack;
private byte[] pixels;
private ArrayList frames; // frames read from current file
private int frameCount;
private bool _makeTransparent;
/**
* Gets the number of frames read from file.
* @return frame count
*/
public int FrameCount
{
get
{
return frameCount;
}
}
/**
* Gets the first (or only) image read.
*
* @return BufferedImage containing first frame, or null if none.
*/
public Image Image
{
get
{
return GetFrame(0).Image;
}
}
/**
* Gets the "Netscape" iteration count, if any.
* A count of 0 means repeat indefinitiely.
*
* @return iteration count if one was specified, else 1.
*/
public int LoopCount
{
get
{
return loopCount;
}
}
public GifDecoder(Stream stream, bool makeTransparent)
{
_makeTransparent=makeTransparent;
if(Read(stream)!=0)
throw new InvalidOperationException();
}
/**
* Creates new frame image from current data (and previous
* frames as specified by their disposition codes).
*/
private int[] GetPixels(Bitmap bitmap)
{
int[] pixels=new int[3*image.Width*image.Height];
int count=0;
for(int th=0; th<image.Height; th++)
{
for(int tw=0; tw<image.Width; tw++)
{
Color color=bitmap.GetPixel(tw, th);
pixels[count]=color.R;
count++;
pixels[count]=color.G;
count++;
pixels[count]=color.B;
count++;
}
}
return pixels;
}
private void SetPixels(int[] pixels)
{
int count=0;
for(int th=0; th<image.Height; th++)
{
for(int tw=0; tw<image.Width; tw++)
{
Color color=Color.FromArgb(pixels[count++]);
bitmap.SetPixel(tw, th, color);
}
}
if(_makeTransparent) bitmap.MakeTransparent(bitmap.GetPixel(0, 0));
}
private void SetPixels()
{
// expose destination image's pixels as int array
// int[] dest =
// (( int ) image.getRaster().getDataBuffer()).getData();
int[] dest=GetPixels(bitmap);
// fill in starting image contents based on last image's dispose code
if(lastDispose>0)
{
if(lastDispose==3)
{
// use image before last
int n=frameCount-2;
if(n>0)
{
lastImage=GetFrame(n-1).Image;
}
else
{
lastImage=null;
}
}
if(lastImage!=null)
{
// int[] prev =
// ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();
int[] prev=GetPixels(new Bitmap(lastImage));
Array.Copy(prev, 0, dest, 0, width*height);
// copy pixels
if(lastDispose==2)
{
// fill last image rect area with background color
Graphics g=Graphics.FromImage(image);
Color c=Color.Empty;
if(transparency)
{
c=Color.FromArgb(0, 0, 0, 0); // assume background is transparent
}
else
{
c=Color.FromArgb(lastBgColor);
// c = new Color(lastBgColor); // use given background color
}
Brush brush=new SolidBrush(c);
g.FillRectangle(brush, lastRect);
brush.Dispose();
g.Dispose();
}
}
}
// copy each source line to the appropriate place in the destination
int pass=1;
int inc=8;
int iline=0;
for(int i=0; i<ih; i++)
{
int line=i;
if(interlace)
{
if(iline>=ih)
{
pass++;
switch(pass)
{
case 2:
iline=4;
break;
case 3:
iline=2;
inc=4;
break;
case 4:
iline=1;
inc=2;
break;
}
}
line=iline;
iline+=inc;
}
line+=iy;
if(line<height)
{
int k=line*width;
int dx=k+ix; // start of line in dest
int dlim=dx+iw; // end of dest line
if((k+width)<dlim)
{
dlim=k+width; // past dest edge
}
int sx=i*iw; // start of line in source
while(dx<dlim)
{
// map color and insert in destination
int index=((int)pixels[sx++])&0xff;
int c=act[index];
if(c!=0)
{
dest[dx]=c;
}
dx++;
}
}
}
SetPixels(dest);
}
/**
* Gets the image contents of frame n.
*
* @return BufferedImage representation of frame.
*/
public GifFrame GetFrame(int n)
{
if((n>=0)&&(n<frameCount))
return (GifFrame)frames[n];
else
throw new ArgumentOutOfRangeException();
}
/**
* Gets image size.
*
* @return GIF image dimensions
*/
public Size FrameSize
{
get
{
return new Size(width, height);
}
}
/**
* Reads GIF image from stream
*
* @param BufferedInputStream containing GIF file.
* @return read status code (0 = no errors)
*/
private int Read(Stream inStream)
{
Init();
if(inStream!=null)
{
this.inStream=inStream;
ReadHeader();
if(!Error())
{
ReadContents();
if(frameCount<0)
{
status=StatusFormatError;
}
}
inStream.Close();
}
else
{
status=StatusOpenError;
}
return status;
}
/**
* Decodes LZW image data into pixel array.
* Adapted from John Cristy's ImageMagick.
*/
private void DecodeImageData()
{
int NullCode=-1;
int npix=iw*ih;
int available,
clear,
code_mask,
code_size,
end_of_information,
in_code,
old_code,
bits,
code,
count,
i,
datum,
data_size,
first,
top,
bi,
pi;
if((pixels==null)||(pixels.Length<npix))
{
pixels=new byte[npix]; // allocate new pixel array
}
if(prefix==null) prefix=new short[MaxStackSize];
if(suffix==null) suffix=new byte[MaxStackSize];
if(pixelStack==null) pixelStack=new byte[MaxStackSize+1];
// Initialize GIF data stream decoder.
data_size=Read();
clear=1<<data_size;
end_of_information=clear+1;
available=clear+2;
old_code=NullCode;
code_size=data_size+1;
code_mask=(1<<code_size)-1;
for(code=0; code<clear; code++)
{
prefix[code]=0;
suffix[code]=(byte)code;
}
// Decode GIF pixel stream.
datum=bits=count=first=top=pi=bi=0;
for(i=0; i<npix; )
{
if(top==0)
{
if(bits<code_size)
{
// Load bytes until there are enough bits for a code.
if(count==0)
{
// Read a new data block.
count=ReadBlock();
if(count<=0)
break;
bi=0;
}
datum+=(((int)block[bi])&0xff)<<bits;
bits+=8;
bi++;
count--;
continue;
}
// Get the next code.
code=datum&code_mask;
datum>>=code_size;
bits-=code_size;
// Interpret the code
if((code>available)||(code==end_of_information))
break;
if(code==clear)
{
// Reset decoder.
code_size=data_size+1;
code_mask=(1<<code_size)-1;
available=clear+2;
old_code=NullCode;
continue;
}
if(old_code==NullCode)
{
pixelStack[top++]=suffix[code];
old_code=code;
first=code;
continue;
}
in_code=code;
if(code==available)
{
pixelStack[top++]=(byte)first;
code=old_code;
}
while(code>clear)
{
pixelStack[top++]=suffix[code];
code=prefix[code];
}
first=((int)suffix[code])&0xff;
// Add a new string to the string table,
if(available>=MaxStackSize)
break;
pixelStack[top++]=(byte)first;
prefix[available]=(short)old_code;
suffix[available]=(byte)first;
available++;
if(((available&code_mask)==0)
&&(available<MaxStackSize))
{
code_size++;
code_mask+=available;
}
old_code=in_code;
}
// Pop a pixel off the pixel stack.
top--;
pixels[pi++]=pixelStack[top];
i++;
}
for(i=pi; i<npix; i++)
{
pixels[i]=0; // clear missing pixels
}
}
/**
* Returns true if an error was encountered during reading/decoding
*/
private bool Error()
{
return status!=StatusOK;
}
/**
* Initializes or re-initializes reader
*/
private void Init()
{
status=StatusOK;
frameCount=0;
frames=new ArrayList();
gct=null;
lct=null;
}
/**
* Reads a single byte from the input stream.
*/
private int Read()
{
int curByte=0;
try
{
curByte=inStream.ReadByte();
}
catch(IOException)
{
status=StatusFormatError;
}
return curByte;
}
/**
* Reads next variable length block from input.
*
* @return number of bytes stored in "buffer"
*/
private int ReadBlock()
{
blockSize=Read();
int n=0;
if(blockSize>0)
{
try
{
int count=0;
while(n<blockSize)
{
count=inStream.Read(block, n, blockSize-n);
if(count==-1)
break;
n+=count;
}
}
catch(IOException)
{
}
if(n<blockSize)
{
status=StatusFormatError;
}
}
return n;
}
/**
* Reads color table as 256 RGB integer values
*
* @param ncolors int number of colors to read
* @return int array containing 256 colors (packed ARGB with full alpha)
*/
private int[] ReadColorTable(int ncolors)
{
int nbytes=3*ncolors;
int[] tab=null;
byte[] c=new byte[nbytes];
int n=0;
try
{
n=inStream.Read(c, 0, c.Length);
}
catch(IOException)
{
}
if(n<nbytes)
{
status=StatusFormatError;
}
else
{
tab=new int[256]; // max size to avoid bounds checks
int i=0;
int j=0;
while(i<ncolors)
{
int r=((int)c[j++])&0xff;
int g=((int)c[j++])&0xff;
int b=((int)c[j++])&0xff;
tab[i++]=(int)(0xff000000|(r<<16)|(g<<8)|b);
}
}
return tab;
}
/**
* Main file parser. Reads GIF content blocks.
*/
private void ReadContents()
{
// read GIF file content blocks
bool done=false;
while(!(done||Error()))
{
int code=Read();
switch(code)
{
case 0x2C: // image separator
ReadImage();
break;
case 0x21: // extension
code=Read();
switch(code)
{
case 0xf9: // graphics control extension
ReadGraphicControlExt();
break;
case 0xff: // application extension
ReadBlock();
String app="";
for(int i=0; i<11; i++)
{
app+=(char)block[i];
}
if(app.Equals("NETSCAPE2.0"))
{
ReadNetscapeExt();
}
else
Skip(); // don't care
break;
default: // uninteresting extension
Skip();
break;
}
break;
case 0x3b: // terminator
done=true;
break;
case 0x00: // bad byte, but keep going and see what happens
break;
default:
status=StatusFormatError;
break;
}
}
}
/**
* Reads Graphics Control Extension values
*/
private void ReadGraphicControlExt()
{
Read(); // block size
int packed=Read(); // packed fields
dispose=(packed&0x1c)>>2; // disposal method
if(dispose==0)
{
dispose=1; // elect to keep old image if discretionary
}
transparency=(packed&1)!=0;
delay=ReadShort()*10; // delay in milliseconds
transIndex=Read(); // transparent color index
Read(); // block terminator
}
/**
* Reads GIF file header information.
*/
private void ReadHeader()
{
String id="";
for(int i=0; i<6; i++)
{
id+=(char)Read();
}
if(!id.StartsWith("GIF"))
{
status=StatusFormatError;
return;
}
ReadLSD();
if(gctFlag&&!Error())
{
gct=ReadColorTable(gctSize);
bgColor=gct[bgIndex];
}
}
/**
* Reads next frame image
*/
private void ReadImage()
{
ix=ReadShort(); // (sub)image position & size
iy=ReadShort();
iw=ReadShort();
ih=ReadShort();
int packed=Read();
lctFlag=(packed&0x80)!=0; // 1 - local color table flag
interlace=(packed&0x40)!=0; // 2 - interlace flag
// 3 - sort flag
// 4-5 - reserved
lctSize=2<<(packed&7); // 6-8 - local color table size
if(lctFlag)
{
lct=ReadColorTable(lctSize); // read table
act=lct; // make local table active
}
else
{
act=gct; // make global table active
if(bgIndex==transIndex)
bgColor=0;
}
int save=0;
if(transparency)
{
save=act[transIndex];
act[transIndex]=0; // set transparent color if specified
}
if(act==null)
{
status=StatusFormatError; // no color table defined
}
if(Error()) return;
DecodeImageData(); // decode pixel data
Skip();
if(Error()) return;
frameCount++;
// create new image to receive frame data
// image =
// new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
bitmap=new Bitmap(width, height);
image=bitmap;
SetPixels(); // transfer pixel data to image
frames.Add(new GifFrame(bitmap, delay)); // add image to frame list
if(transparency)
{
act[transIndex]=save;
}
ResetFrame();
}
/**
* Reads Logical Screen Descriptor
*/
private void ReadLSD()
{
// logical screen size
width=ReadShort();
height=ReadShort();
// packed fields
int packed=Read();
gctFlag=(packed&0x80)!=0; // 1 : global color table flag
// 2-4 : color resolution
// 5 : gct sort flag
gctSize=2<<(packed&7); // 6-8 : gct size
bgIndex=Read(); // background color index
pixelAspect=Read(); // pixel aspect ratio
}
/**
* Reads Netscape extenstion to obtain iteration count
*/
private void ReadNetscapeExt()
{
do
{
ReadBlock();
if(block[0]==1)
{
// loop count sub-block
int b1=((int)block[1])&0xff;
int b2=((int)block[2])&0xff;
loopCount=(b2<<8)|b1;
}
} while((blockSize>0)&&!Error());
}
/**
* Reads next 16-bit value, LSB first
*/
private int ReadShort()
{
// read 16-bit value, LSB first
return Read()|(Read()<<8);
}
/**
* Resets frame state for reading next image.
*/
private void ResetFrame()
{
lastDispose=dispose;
lastRect=new Rectangle(ix, iy, iw, ih);
lastImage=image;
lastBgColor=bgColor;
lct=null;
}
/**
* Skips variable length blocks up to and including
* next zero length block.
*/
private void Skip()
{
do
{
ReadBlock();
} while((blockSize>0)&&!Error());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Security;
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: Used when implementing a custom TraceLoggingTypeInfo.
/// The instance of this type is provided to the TypeInfo.WriteData method.
/// All operations are forwarded to the current thread's DataCollector.
/// Note that this abstraction would allow us to expose the custom
/// serialization system to partially-trusted code. If we end up not
/// making custom serialization public, or if we only expose it to
/// full-trust code, this abstraction is unnecessary (though it probably
/// doesn't hurt anything).
/// </summary>
[SecuritySafeCritical]
internal unsafe class TraceLoggingDataCollector
{
internal static readonly TraceLoggingDataCollector Instance = new TraceLoggingDataCollector();
private TraceLoggingDataCollector()
{
return;
}
/// <summary>
/// Marks the start of a non-blittable array or enumerable.
/// </summary>
/// <returns>Bookmark to be passed to EndBufferedArray.</returns>
public int BeginBufferedArray()
{
return DataCollector.ThreadInstance.BeginBufferedArray();
}
/// <summary>
/// Marks the end of a non-blittable array or enumerable.
/// </summary>
/// <param name="bookmark">The value returned by BeginBufferedArray.</param>
/// <param name="count">The number of items in the array.</param>
public void EndBufferedArray(int bookmark, int count)
{
DataCollector.ThreadInstance.EndBufferedArray(bookmark, count);
}
/// <summary>
/// Adds the start of a group to the event.
/// This has no effect on the event payload, but is provided to allow
/// WriteMetadata and WriteData implementations to have similar
/// sequences of calls, allowing for easier verification of correctness.
/// </summary>
public TraceLoggingDataCollector AddGroup()
{
return this;
}
/// <summary>
/// Adds a Boolean value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(bool value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(bool));
}
/// <summary>
/// Adds an SByte value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
//[CLSCompliant(false)]
public void AddScalar(sbyte value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(sbyte));
}
/// <summary>
/// Adds a Byte value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(byte value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(byte));
}
/// <summary>
/// Adds an Int16 value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(short value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(short));
}
/// <summary>
/// Adds a UInt16 value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
//[CLSCompliant(false)]
public void AddScalar(ushort value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(ushort));
}
/// <summary>
/// Adds an Int32 value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(int value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(int));
}
/// <summary>
/// Adds a UInt32 value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
//[CLSCompliant(false)]
public void AddScalar(uint value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(uint));
}
/// <summary>
/// Adds an Int64 value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(long value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(long));
}
/// <summary>
/// Adds a UInt64 value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
//[CLSCompliant(false)]
public void AddScalar(ulong value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(ulong));
}
/// <summary>
/// Adds an IntPtr value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(IntPtr value)
{
DataCollector.ThreadInstance.AddScalar(&value, IntPtr.Size);
}
/// <summary>
/// Adds a UIntPtr value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
//[CLSCompliant(false)]
public void AddScalar(UIntPtr value)
{
DataCollector.ThreadInstance.AddScalar(&value, UIntPtr.Size);
}
/// <summary>
/// Adds a Single value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(float value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(float));
}
/// <summary>
/// Adds a Double value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(double value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(double));
}
/// <summary>
/// Adds a Char value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(char value)
{
DataCollector.ThreadInstance.AddScalar(&value, sizeof(char));
}
/// <summary>
/// Adds a Guid value to the event payload.
/// </summary>
/// <param name="value">Value to be added.</param>
public void AddScalar(Guid value)
{
DataCollector.ThreadInstance.AddScalar(&value, 16);
}
/// <summary>
/// Adds a counted String value to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length string.
/// </param>
public void AddBinary(string value)
{
DataCollector.ThreadInstance.AddBinary(value, value == null ? 0 : value.Length * 2);
}
/// <summary>
/// Adds an array of Byte values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddBinary(byte[] value)
{
DataCollector.ThreadInstance.AddBinary(value, value == null ? 0 : value.Length);
}
/// <summary>
/// Adds an array of Boolean values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(bool[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(bool));
}
/// <summary>
/// Adds an array of SByte values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
//[CLSCompliant(false)]
public void AddArray(sbyte[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(sbyte));
}
/// <summary>
/// Adds an array of Int16 values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(short[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(short));
}
/// <summary>
/// Adds an array of UInt16 values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
//[CLSCompliant(false)]
public void AddArray(ushort[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(ushort));
}
/// <summary>
/// Adds an array of Int32 values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(int[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(int));
}
/// <summary>
/// Adds an array of UInt32 values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
//[CLSCompliant(false)]
public void AddArray(uint[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(uint));
}
/// <summary>
/// Adds an array of Int64 values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(long[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(long));
}
/// <summary>
/// Adds an array of UInt64 values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
//[CLSCompliant(false)]
public void AddArray(ulong[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(ulong));
}
/// <summary>
/// Adds an array of IntPtr values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(IntPtr[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, IntPtr.Size);
}
/// <summary>
/// Adds an array of UIntPtr values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
//[CLSCompliant(false)]
public void AddArray(UIntPtr[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, UIntPtr.Size);
}
/// <summary>
/// Adds an array of Single values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(float[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(float));
}
/// <summary>
/// Adds an array of Double values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(double[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(double));
}
/// <summary>
/// Adds an array of Char values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(char[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(char));
}
/// <summary>
/// Adds an array of Guid values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddArray(Guid[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, 16);
}
/// <summary>
/// Adds an array of Byte values to the event payload.
/// </summary>
/// <param name="value">
/// Value to be added. A null value is treated as a zero-length array.
/// </param>
public void AddCustom(byte[] value)
{
DataCollector.ThreadInstance.AddArray(value, value == null ? 0 : value.Length, sizeof(byte));
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2007 - 2020 Microting A/S
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using eFormCore;
using Microsoft.EntityFrameworkCore;
using Microting.eForm.Dto;
using Microting.eForm.Helpers;
using Microting.eForm.Infrastructure;
using Microting.eForm.Infrastructure.Constants;
using Microting.eForm.Infrastructure.Data.Entities;
using Microting.eForm.Infrastructure.Helpers;
using NUnit.Framework;
namespace eFormSDK.Integration.Base.CoreTests
{
[TestFixture]
public class CoreTestFolders : DbTestFixture
{
private Core sut;
private TestHelpers testHelpers;
private string path;
public override async Task DoSetup()
{
#region Setup SettingsTableContent
DbContextHelper dbContextHelper = new DbContextHelper(ConnectionString);
SqlController sql = new SqlController(dbContextHelper);
await sql.SettingUpdate(Settings.token, "abc1234567890abc1234567890abcdef").ConfigureAwait(false);
await sql.SettingUpdate(Settings.firstRunDone, "true").ConfigureAwait(false);
await sql.SettingUpdate(Settings.knownSitesDone, "true").ConfigureAwait(false);
#endregion
sut = new Core();
sut.HandleCaseCreated += EventCaseCreated;
sut.HandleCaseRetrived += EventCaseRetrived;
sut.HandleCaseCompleted += EventCaseCompleted;
sut.HandleCaseDeleted += EventCaseDeleted;
sut.HandleFileDownloaded += EventFileDownloaded;
sut.HandleSiteActivated += EventSiteActivated;
await sut.StartSqlOnly(ConnectionString).ConfigureAwait(false);
path = Assembly.GetExecutingAssembly().Location;
path = Path.GetDirectoryName(path).Replace(@"file:", "");
await sut.SetSdkSetting(Settings.fileLocationPicture, Path.Combine(path, "output", "dataFolder", "picture"));
await sut.SetSdkSetting(Settings.fileLocationPdf, Path.Combine(path, "output", "dataFolder", "pdf"));
await sut.SetSdkSetting(Settings.fileLocationJasper, Path.Combine(path, "output", "dataFolder", "reports"));
testHelpers = new TestHelpers();
await testHelpers.GenerateDefaultLanguages();
//sut.StartLog(new CoreBase());
}
#region folder
[Test]
public async Task Core_Folders_CreateFolder_DoesCreateNewFolder()
{
// Arrange
string folderName = Guid.NewGuid().ToString();
string folderDescription = Guid.NewGuid().ToString();
//Act
List<KeyValuePair<string, string>> names = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions = new List<KeyValuePair<string, string>>();
names.Add(new KeyValuePair<string, string> ("da", folderName));
descriptions.Add(new KeyValuePair<string, string>("da",folderDescription.Replace(" ", " ")));
await sut.FolderCreate(names, descriptions, null).ConfigureAwait(false);
//Assert
var folderVersions = DbContext.FolderVersions.AsNoTracking().ToList();
var folders = DbContext.Folders.AsNoTracking().ToList();
var folderTranslations = DbContext.FolderTranslations.AsNoTracking().ToList();
var folderTranslationVersions = DbContext.FolderTranslationVersions.AsNoTracking().ToList();
Assert.NotNull(folders);
Assert.NotNull(folderVersions);
Assert.AreEqual(1, folders.Count);
Assert.AreEqual(2, folderVersions.Count);
Assert.AreEqual(1, folderTranslations.Count);
Assert.AreEqual(1, folderTranslationVersions.Count);
Assert.AreEqual(null, folders[0].Name);
Assert.AreEqual(null, folders[0].Description);
Assert.AreEqual(folders[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(null, folderVersions[0].Name);
Assert.AreEqual(null, folderVersions[0].Description);
Assert.AreEqual(folderVersions[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(folderName, folderTranslations[0].Name);
Assert.AreEqual(folderDescription, folderTranslations[0].Description);
Assert.AreEqual(folderTranslations[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(folderName, folderTranslationVersions[0].Name);
Assert.AreEqual(folderDescription, folderTranslationVersions[0].Description);
Assert.AreEqual(folderTranslationVersions[0].WorkflowState, Constants.WorkflowStates.Created);
}
[Test]
public async Task Core_Folders_CreateFolder_DoesCreateNewFolderWithTranslations()
{
// Arrange
string folderName = Guid.NewGuid().ToString();
string enfolderName = Guid.NewGuid().ToString();
string defolderName = Guid.NewGuid().ToString();
string folderDescription = Guid.NewGuid().ToString();
string enfolderDescription = Guid.NewGuid().ToString();
string defolderDescription = Guid.NewGuid().ToString();
//Act
List<KeyValuePair<string, string>> names = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions = new List<KeyValuePair<string, string>>();
names.Add(new KeyValuePair<string, string> ("da", folderName));
names.Add(new KeyValuePair<string, string> ("en-US", enfolderName));
names.Add(new KeyValuePair<string, string> ("de-DE", defolderName));
descriptions.Add(new KeyValuePair<string, string>("da",folderDescription.Replace(" ", " ")));
descriptions.Add(new KeyValuePair<string, string>("en-US",enfolderDescription.Replace(" ", " ")));
descriptions.Add(new KeyValuePair<string, string>("de-DE",defolderDescription.Replace(" ", " ")));
await sut.FolderCreate(names, descriptions, null).ConfigureAwait(false);
//Assert
var folderVersions = DbContext.FolderVersions.AsNoTracking().ToList();
var folders = DbContext.Folders.AsNoTracking().ToList();
var folderTranslations = DbContext.FolderTranslations.AsNoTracking().ToList();
var folderTranslationVersions = DbContext.FolderTranslationVersions.AsNoTracking().ToList();
Assert.NotNull(folders);
Assert.NotNull(folderVersions);
Assert.AreEqual(1, folders.Count);
Assert.AreEqual(2, folderVersions.Count);
Assert.AreEqual(3, folderTranslations.Count);
Assert.AreEqual(3, folderTranslationVersions.Count);
Assert.AreEqual(null, folders[0].Name);
Assert.AreEqual(null, folders[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folders[0].WorkflowState);
Assert.AreEqual(null, folderVersions[0].Name);
Assert.AreEqual(null, folderVersions[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created,folderVersions[0].WorkflowState);
Assert.AreEqual(folderName, folderTranslations[0].Name);
Assert.AreEqual(folderDescription, folderTranslations[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[0].WorkflowState);
Assert.AreEqual(enfolderName, folderTranslations[1].Name);
Assert.AreEqual(enfolderDescription, folderTranslations[1].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[1].WorkflowState);
Assert.AreEqual(defolderName, folderTranslations[2].Name);
Assert.AreEqual(defolderDescription, folderTranslations[2].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[2].WorkflowState);
Assert.AreEqual(folderName, folderTranslationVersions[0].Name);
Assert.AreEqual(folderDescription, folderTranslationVersions[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[0].WorkflowState);
Assert.AreEqual(enfolderName, folderTranslationVersions[1].Name);
Assert.AreEqual(enfolderDescription, folderTranslationVersions[1].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[1].WorkflowState);
Assert.AreEqual(defolderName, folderTranslationVersions[2].Name);
Assert.AreEqual(defolderDescription, folderTranslationVersions[2].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[2].WorkflowState);
}
[Test]
public async Task Core_Folders_CreateSubFolder_DoesCreateSubFolder()
{
// Arrange
string folderName = Guid.NewGuid().ToString();
string folderDescription = Guid.NewGuid().ToString();
List<KeyValuePair<string, string>> names = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions = new List<KeyValuePair<string, string>>();
names.Add(new KeyValuePair<string, string> ("da", folderName));
descriptions.Add(new KeyValuePair<string, string>("da",folderDescription.Replace(" ", " ")));
await sut.FolderCreate(names, descriptions, null).ConfigureAwait(false);
int firstFolderId = DbContext.Folders.First().Id;
string subFolderName = Guid.NewGuid().ToString();
string subFolderDescription = Guid.NewGuid().ToString();
// Act
List<KeyValuePair<string, string>> names1 = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions1 = new List<KeyValuePair<string, string>>();
names1.Add(new KeyValuePair<string, string> ("da", subFolderName));
descriptions1.Add(new KeyValuePair<string, string>("da",subFolderDescription.Replace(" ", " ")));
await sut.FolderCreate(names1, descriptions1, firstFolderId).ConfigureAwait(false);
var folderVersions = DbContext.FolderVersions.AsNoTracking().ToList();
var folders = DbContext.Folders.AsNoTracking().ToList();
var folderTranslations = DbContext.FolderTranslations.AsNoTracking().ToList();
var folderTranslationVersions = DbContext.FolderTranslationVersions.AsNoTracking().ToList();
Assert.NotNull(folders);
Assert.NotNull(folderVersions);
Assert.AreEqual(2, folders.Count);
Assert.AreEqual(4, folderVersions.Count);
Assert.AreEqual(2, folderTranslations.Count);
Assert.AreEqual(2, folderTranslationVersions.Count);
Assert.AreEqual(null,folders[0].Name);
Assert.AreEqual(null,folders[0].Description);
Assert.AreEqual(null,folders[1].Name);
Assert.AreEqual(null,folders[1].Description);
Assert.AreEqual(folders[1].ParentId, firstFolderId);
Assert.AreEqual(null,folderVersions[0].Name);
Assert.AreEqual(null,folderVersions[0].Description);
Assert.AreEqual(null, folderVersions[0].ParentId);
Assert.AreEqual(null,folderVersions[1].Name);
Assert.AreEqual(null,folderVersions[1].Description);
Assert.AreEqual(null, folderVersions[1].ParentId);
Assert.AreEqual(null,folderVersions[2].Name);
Assert.AreEqual(null,folderVersions[2].Description);
Assert.AreEqual(firstFolderId, folderVersions[2].ParentId);
Assert.AreEqual(null,folderVersions[3].Name);
Assert.AreEqual(null,folderVersions[3].Description);
Assert.AreEqual(firstFolderId, folderVersions[3].ParentId);
Assert.AreEqual(folderName,folderTranslations[0].Name);
Assert.AreEqual(folderDescription,folderTranslations[0].Description);
Assert.AreEqual(subFolderName,folderTranslations[1].Name);
Assert.AreEqual(subFolderDescription,folderTranslations[1].Description);
Assert.AreEqual(folderName,folderTranslationVersions[0].Name);
Assert.AreEqual(folderDescription,folderTranslationVersions[0].Description);
Assert.AreEqual(subFolderName,folderTranslationVersions[1].Name);
Assert.AreEqual(subFolderDescription,folderTranslationVersions[1].Description);
}
[Test]
public async Task Core_Folders_CreateSubFolder_DoesCreateSubFolderWithTranslations()
{
// Arrange
string folderName = Guid.NewGuid().ToString();
string enfolderName = Guid.NewGuid().ToString();
string defolderName = Guid.NewGuid().ToString();
string folderDescription = Guid.NewGuid().ToString();
string enfolderDescription = Guid.NewGuid().ToString();
string defolderDescription = Guid.NewGuid().ToString();
List<KeyValuePair<string, string>> names = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions = new List<KeyValuePair<string, string>>();
names.Add(new KeyValuePair<string, string> ("da", folderName));
names.Add(new KeyValuePair<string, string> ("en-US", enfolderName));
names.Add(new KeyValuePair<string, string> ("de-DE", defolderName));
descriptions.Add(new KeyValuePair<string, string>("da",folderDescription.Replace(" ", " ")));
descriptions.Add(new KeyValuePair<string, string>("en-US",enfolderDescription.Replace(" ", " ")));
descriptions.Add(new KeyValuePair<string, string>("de-DE",defolderDescription.Replace(" ", " ")));
await sut.FolderCreate(names, descriptions, null).ConfigureAwait(false);
int firstFolderId = DbContext.Folders.First().Id;
string subFolderName = Guid.NewGuid().ToString();
string ensubFolderName = Guid.NewGuid().ToString();
string desubFolderName = Guid.NewGuid().ToString();
string subFolderDescription = Guid.NewGuid().ToString();
string ensubFolderDescription = Guid.NewGuid().ToString();
string desubFolderDescription = Guid.NewGuid().ToString();
// Act
List<KeyValuePair<string, string>> names1 = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions1 = new List<KeyValuePair<string, string>>();
names1.Add(new KeyValuePair<string, string> ("da", subFolderName));
names1.Add(new KeyValuePair<string, string> ("en-US", ensubFolderName));
names1.Add(new KeyValuePair<string, string> ("de-DE", desubFolderName));
descriptions1.Add(new KeyValuePair<string, string>("da",subFolderDescription.Replace(" ", " ")));
descriptions1.Add(new KeyValuePair<string, string>("en-US",ensubFolderDescription.Replace(" ", " ")));
descriptions1.Add(new KeyValuePair<string, string>("de-DE",desubFolderDescription.Replace(" ", " ")));
await sut.FolderCreate(names1, descriptions1, firstFolderId).ConfigureAwait(false);
var folderVersions = DbContext.FolderVersions.AsNoTracking().ToList();
var folders = DbContext.Folders.AsNoTracking().ToList();
var folderTranslations = DbContext.FolderTranslations.AsNoTracking().ToList();
var folderTranslationVersions = DbContext.FolderTranslationVersions.AsNoTracking().ToList();
Assert.NotNull(folders);
Assert.NotNull(folderVersions);
Assert.AreEqual(2, folders.Count);
Assert.AreEqual(4, folderVersions.Count);
Assert.AreEqual(6, folderTranslations.Count);
Assert.AreEqual(6, folderTranslationVersions.Count);
Assert.AreEqual(null,folders[0].Name);
Assert.AreEqual(null,folders[0].Description);
Assert.AreEqual(null,folders[1].Name);
Assert.AreEqual(null,folders[1].Description);
Assert.AreEqual( firstFolderId,folders[1].ParentId);
Assert.AreEqual(null,folderVersions[0].Name);
Assert.AreEqual(null,folderVersions[0].Description);
Assert.AreEqual(null, folderVersions[0].ParentId);
Assert.AreEqual(null,folderVersions[1].Name);
Assert.AreEqual(null,folderVersions[1].Description);
Assert.AreEqual(null, folderVersions[1].ParentId);
Assert.AreEqual(null,folderVersions[2].Name);
Assert.AreEqual(null,folderVersions[2].Description);
Assert.AreEqual(firstFolderId, folderVersions[2].ParentId);
Assert.AreEqual(null,folderVersions[3].Name);
Assert.AreEqual(null,folderVersions[3].Description);
Assert.AreEqual(firstFolderId, folderVersions[3].ParentId);
Assert.AreEqual(folderName,folderTranslations[0].Name);
Assert.AreEqual(folderDescription,folderTranslations[0].Description);
Assert.AreEqual(enfolderName,folderTranslations[1].Name);
Assert.AreEqual(enfolderDescription,folderTranslations[1].Description);
Assert.AreEqual(defolderName,folderTranslations[2].Name);
Assert.AreEqual(defolderDescription,folderTranslations[2].Description);
Assert.AreEqual(subFolderName,folderTranslations[3].Name);
Assert.AreEqual(subFolderDescription,folderTranslations[3].Description);
Assert.AreEqual(ensubFolderName,folderTranslations[4].Name);
Assert.AreEqual(ensubFolderDescription,folderTranslations[4].Description);
Assert.AreEqual(desubFolderName,folderTranslations[5].Name);
Assert.AreEqual(desubFolderDescription,folderTranslations[5].Description);
Assert.AreEqual(folderName,folderTranslationVersions[0].Name);
Assert.AreEqual(folderDescription,folderTranslationVersions[0].Description);
Assert.AreEqual(enfolderName,folderTranslationVersions[1].Name);
Assert.AreEqual(enfolderDescription,folderTranslationVersions[1].Description);
Assert.AreEqual(defolderName,folderTranslationVersions[2].Name);
Assert.AreEqual(defolderDescription,folderTranslationVersions[2].Description);
Assert.AreEqual(subFolderName,folderTranslationVersions[3].Name);
Assert.AreEqual(subFolderDescription,folderTranslationVersions[3].Description);
Assert.AreEqual(ensubFolderName,folderTranslationVersions[4].Name);
Assert.AreEqual(ensubFolderDescription,folderTranslationVersions[4].Description);
Assert.AreEqual(desubFolderName,folderTranslationVersions[5].Name);
Assert.AreEqual(desubFolderDescription,folderTranslationVersions[5].Description);
}
[Test]
public async Task Core_Folders_DeleteFolder_DoesMarkFolderAsRemoved()
{
// Arrange
string folderName = Guid.NewGuid().ToString();
string folderDescription = Guid.NewGuid().ToString();
Folder folder = new Folder();
folder.Name = folderName;
folder.Description = folderDescription;
folder.WorkflowState = Constants.WorkflowStates.Created;
folder.MicrotingUid = 23123;
await folder.Create(DbContext).ConfigureAwait(false);
//Act
await sut.FolderDelete(folder.Id);
var folderVersions = DbContext.FolderVersions.AsNoTracking().ToList();
var folders = DbContext.Folders.AsNoTracking().ToList();
//Assert
Assert.NotNull(folders);
Assert.NotNull(folderVersions);
Assert.AreEqual(1, folders.Count);
Assert.AreEqual(2, folderVersions.Count);
Assert.AreEqual(folders[0].Name, folderName);
Assert.AreEqual(folders[0].Description, folderDescription);
Assert.AreEqual(folders[0].WorkflowState, Constants.WorkflowStates.Removed);
Assert.AreEqual(folderVersions[0].Name, folders[0].Name);
Assert.AreEqual(folderVersions[0].Description, folders[0].Description);
Assert.AreEqual(folderVersions[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(folderVersions[1].Name, folders[0].Name);
Assert.AreEqual(folderVersions[1].Description, folders[0].Description);
Assert.AreEqual(folderVersions[1].WorkflowState, Constants.WorkflowStates.Removed);
}
[Test]
public async Task Core_Folders_UpdateFolder_DoesUpdateFolder()
{
// Arrange
string folderName = Guid.NewGuid().ToString();
string folderDescription = Guid.NewGuid().ToString();
Folder folder = new Folder {WorkflowState = Constants.WorkflowStates.Created, MicrotingUid = 23123};
await folder.Create(DbContext).ConfigureAwait(false);
FolderTranslation folderTranslation = new FolderTranslation
{
FolderId = folder.Id,
Name = folderName,
Description = folderDescription,
LanguageId = DbContext.Languages.First(x => x.LanguageCode == "da").Id
};
await folderTranslation.Create(DbContext);
//Act
string newFolderName = Guid.NewGuid().ToString();
string newDescription = Guid.NewGuid().ToString();
List<KeyValuePair<string, string>> names1 = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions1 = new List<KeyValuePair<string, string>>();
names1.Add(new KeyValuePair<string, string> ("da", newFolderName));
descriptions1.Add(new KeyValuePair<string, string>("da",newDescription.Replace(" ", " ")));
await sut.FolderUpdate(folder.Id, names1, descriptions1, null).ConfigureAwait(false);
//await sut.FolderUpdate(folder.Id, newFolderName, newDescription, null).ConfigureAwait(false);
var folderVersions = DbContext.FolderVersions.AsNoTracking().ToList();
var folders = DbContext.Folders.AsNoTracking().ToList();
var folderTranslations = DbContext.FolderTranslations.AsNoTracking().ToList();
var folderTranslationVersions = DbContext.FolderTranslationVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(folders);
Assert.NotNull(folderVersions);
Assert.AreEqual(1, folders.Count);
Assert.AreEqual(1, folderVersions.Count);
Assert.AreEqual(1, folderTranslations.Count);
Assert.AreEqual(2, folderTranslationVersions.Count);
Assert.AreEqual(null, folders[0].Name);
Assert.AreEqual(null, folders[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folders[0].WorkflowState);
Assert.AreEqual(null,folderVersions[0].Name);
Assert.AreEqual(null, folderVersions[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderVersions[0].WorkflowState);
Assert.AreEqual(newFolderName, folderTranslations[0].Name);
Assert.AreEqual(newDescription, folderTranslations[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[0].WorkflowState);
Assert.AreEqual(folderName, folderTranslationVersions[0].Name);
Assert.AreEqual(folderDescription, folderTranslationVersions[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[0].WorkflowState);
Assert.AreEqual(newFolderName, folderTranslationVersions[1].Name);
Assert.AreEqual(newDescription, folderTranslationVersions[1].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[1].WorkflowState);
}
[Test]
public async Task Core_Folders_UpdateFolder_DoesUpdateFolderWithTranslations()
{
// Arrange
string folderName = Guid.NewGuid().ToString();
string enfolderName = Guid.NewGuid().ToString();
string defolderName = Guid.NewGuid().ToString();
string folderDescription = Guid.NewGuid().ToString();
string enfolderDescription = Guid.NewGuid().ToString();
string defolderDescription = Guid.NewGuid().ToString();
Folder folder = new Folder {WorkflowState = Constants.WorkflowStates.Created, MicrotingUid = 23123};
await folder.Create(DbContext).ConfigureAwait(false);
FolderTranslation folderTranslation = new FolderTranslation
{
FolderId = folder.Id,
Name = folderName,
Description = folderDescription,
LanguageId = DbContext.Languages.First(x => x.LanguageCode == "da").Id
};
await folderTranslation.Create(DbContext);
folderTranslation = new FolderTranslation
{
FolderId = folder.Id,
Name = enfolderName,
Description = enfolderDescription,
LanguageId = DbContext.Languages.First(x => x.LanguageCode == "en-US").Id
};
await folderTranslation.Create(DbContext);
folderTranslation = new FolderTranslation
{
FolderId = folder.Id,
Name = defolderName,
Description = defolderDescription,
LanguageId = DbContext.Languages.First(x => x.LanguageCode == "de-DE").Id
};
await folderTranslation.Create(DbContext);
//Act
string newFolderName = Guid.NewGuid().ToString();
string ennewFolderName = Guid.NewGuid().ToString();
string denewFolderName = Guid.NewGuid().ToString();
string newDescription = Guid.NewGuid().ToString();
string ennewDescription = Guid.NewGuid().ToString();
string denewDescription = Guid.NewGuid().ToString();
List<KeyValuePair<string, string>> names1 = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions1 = new List<KeyValuePair<string, string>>();
names1.Add(new KeyValuePair<string, string> ("da", newFolderName));
names1.Add(new KeyValuePair<string, string> ("en-US", ennewFolderName));
names1.Add(new KeyValuePair<string, string> ("de-DE", denewFolderName));
descriptions1.Add(new KeyValuePair<string, string>("da",newDescription.Replace(" ", " ")));
descriptions1.Add(new KeyValuePair<string, string>("en-US",ennewDescription.Replace(" ", " ")));
descriptions1.Add(new KeyValuePair<string, string>("de-DE",denewDescription.Replace(" ", " ")));
await sut.FolderUpdate(folder.Id, names1, descriptions1, null).ConfigureAwait(false);
//await sut.FolderUpdate(folder.Id, newFolderName, newDescription, null).ConfigureAwait(false);
var folderVersions = DbContext.FolderVersions.AsNoTracking().ToList();
var folders = DbContext.Folders.AsNoTracking().ToList();
var folderTranslations = DbContext.FolderTranslations.AsNoTracking().ToList();
var folderTranslationVersions = DbContext.FolderTranslationVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(folders);
Assert.NotNull(folderVersions);
Assert.AreEqual(1, folders.Count);
Assert.AreEqual(1, folderVersions.Count);
Assert.AreEqual(3, folderTranslations.Count);
Assert.AreEqual(6, folderTranslationVersions.Count);
Assert.AreEqual(null, folders[0].Name);
Assert.AreEqual(null, folders[0].Description);
Assert.AreEqual(null,folderVersions[0].Name);
Assert.AreEqual(null, folderVersions[0].Description);
Assert.AreEqual(newFolderName, folderTranslations[0].Name);
Assert.AreEqual(newDescription, folderTranslations[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[0].WorkflowState);
Assert.AreEqual(ennewFolderName, folderTranslations[1].Name);
Assert.AreEqual(ennewDescription, folderTranslations[1].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[1].WorkflowState);
Assert.AreEqual(denewFolderName, folderTranslations[2].Name);
Assert.AreEqual(denewDescription, folderTranslations[2].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[2].WorkflowState);
Assert.AreEqual(folderName, folderTranslationVersions[0].Name);
Assert.AreEqual(folderDescription, folderTranslationVersions[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[0].WorkflowState);
Assert.AreEqual(enfolderName, folderTranslationVersions[1].Name);
Assert.AreEqual(enfolderDescription, folderTranslationVersions[1].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[1].WorkflowState);
Assert.AreEqual(defolderName, folderTranslationVersions[2].Name);
Assert.AreEqual(defolderDescription, folderTranslationVersions[2].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[2].WorkflowState);
Assert.AreEqual(newFolderName, folderTranslationVersions[3].Name);
Assert.AreEqual(newDescription, folderTranslationVersions[3].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[3].WorkflowState);
Assert.AreEqual(ennewFolderName, folderTranslationVersions[4].Name);
Assert.AreEqual(ennewDescription, folderTranslationVersions[4].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[4].WorkflowState);
Assert.AreEqual(denewFolderName, folderTranslationVersions[5].Name);
Assert.AreEqual(denewDescription, folderTranslationVersions[5].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[5].WorkflowState);
}
[Test]
public async Task Core_Folders_UpdateFolder_DoesUpdateSingleFolderTranslation()
{
// Arrange
string folderName = Guid.NewGuid().ToString();
string enfolderName = Guid.NewGuid().ToString();
string defolderName = Guid.NewGuid().ToString();
string folderDescription = Guid.NewGuid().ToString();
string enfolderDescription = Guid.NewGuid().ToString();
string defolderDescription = Guid.NewGuid().ToString();
Folder folder = new Folder {WorkflowState = Constants.WorkflowStates.Created, MicrotingUid = 23123};
await folder.Create(DbContext).ConfigureAwait(false);
FolderTranslation folderTranslation = new FolderTranslation
{
FolderId = folder.Id,
Name = folderName,
Description = folderDescription,
LanguageId = DbContext.Languages.First(x => x.LanguageCode == "da").Id
};
await folderTranslation.Create(DbContext);
folderTranslation = new FolderTranslation
{
FolderId = folder.Id,
Name = enfolderName,
Description = enfolderDescription,
LanguageId = DbContext.Languages.First(x => x.LanguageCode == "en-US").Id
};
await folderTranslation.Create(DbContext);
folderTranslation = new FolderTranslation
{
FolderId = folder.Id,
Name = defolderName,
Description = defolderDescription,
LanguageId = DbContext.Languages.First(x => x.LanguageCode == "de-DE").Id
};
await folderTranslation.Create(DbContext);
//Act
string newFolderName = Guid.NewGuid().ToString();
string ennewFolderName = Guid.NewGuid().ToString();
string denewFolderName = Guid.NewGuid().ToString();
string newDescription = Guid.NewGuid().ToString();
string ennewDescription = Guid.NewGuid().ToString();
string denewDescription = Guid.NewGuid().ToString();
List<KeyValuePair<string, string>> names1 = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> descriptions1 = new List<KeyValuePair<string, string>>();
names1.Add(new KeyValuePair<string, string> ("de-DE", denewFolderName));
descriptions1.Add(new KeyValuePair<string, string>("de-DE",denewDescription.Replace(" ", " ")));
await sut.FolderUpdate(folder.Id, names1, descriptions1, null).ConfigureAwait(false);
//await sut.FolderUpdate(folder.Id, newFolderName, newDescription, null).ConfigureAwait(false);
var folderVersions = DbContext.FolderVersions.AsNoTracking().ToList();
var folders = DbContext.Folders.AsNoTracking().ToList();
var folderTranslations = DbContext.FolderTranslations.AsNoTracking().ToList();
var folderTranslationVersions = DbContext.FolderTranslationVersions.AsNoTracking().ToList();
//Assert
Assert.NotNull(folders);
Assert.NotNull(folderVersions);
Assert.AreEqual(1, folders.Count);
Assert.AreEqual(1, folderVersions.Count);
Assert.AreEqual(3, folderTranslations.Count);
Assert.AreEqual(4, folderTranslationVersions.Count);
Assert.AreEqual(null, folders[0].Name);
Assert.AreEqual(null, folders[0].Description);
Assert.AreEqual(null,folderVersions[0].Name);
Assert.AreEqual(null, folderVersions[0].Description);
Assert.AreEqual(folderName, folderTranslations[0].Name);
Assert.AreEqual(folderDescription, folderTranslations[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[0].WorkflowState);
Assert.AreEqual(enfolderName, folderTranslations[1].Name);
Assert.AreEqual(enfolderDescription, folderTranslations[1].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[1].WorkflowState);
Assert.AreEqual(denewFolderName, folderTranslations[2].Name);
Assert.AreEqual(denewDescription, folderTranslations[2].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslations[2].WorkflowState);
Assert.AreEqual(folderName, folderTranslationVersions[0].Name);
Assert.AreEqual(folderDescription, folderTranslationVersions[0].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[0].WorkflowState);
Assert.AreEqual(enfolderName, folderTranslationVersions[1].Name);
Assert.AreEqual(enfolderDescription, folderTranslationVersions[1].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[1].WorkflowState);
Assert.AreEqual(defolderName, folderTranslationVersions[2].Name);
Assert.AreEqual(defolderDescription, folderTranslationVersions[2].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[2].WorkflowState);
Assert.AreEqual(denewFolderName, folderTranslationVersions[3].Name);
Assert.AreEqual(denewDescription, folderTranslationVersions[3].Description);
Assert.AreEqual(Constants.WorkflowStates.Created, folderTranslationVersions[3].WorkflowState);
}
#endregion
#region eventhandlers
public void EventCaseCreated(object sender, EventArgs args)
{
// Does nothing for web implementation
}
public void EventCaseRetrived(object sender, EventArgs args)
{
// Does nothing for web implementation
}
public void EventCaseCompleted(object sender, EventArgs args)
{
// Does nothing for web implementation
}
public void EventCaseDeleted(object sender, EventArgs args)
{
// Does nothing for web implementation
}
public void EventFileDownloaded(object sender, EventArgs args)
{
// Does nothing for web implementation
}
public void EventSiteActivated(object sender, EventArgs args)
{
// Does nothing for web implementation
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------
// ConvertTestFixture.cs
//
// Contains the definition of the ConvertTestFixture class.
// Copyright 2009 Steve Guidi.
//
// File created: 2/6/2009 7:09:48 PM
// ----------------------------------------------------------------------------
using System;
using System.Linq;
using System.Reflection;
using Jolt.Test.Types;
using NUnit.Framework;
namespace Jolt.Test
{
[TestFixture]
public sealed class ConvertTestFixture
{
#region public methods --------------------------------------------------------------------
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is a Type object.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Type()
{
Assert.That(Convert.ToXmlDocCommentMember(typeof(int)), Is.EqualTo("T:System.Int32"));
Assert.That(Convert.ToXmlDocCommentMember(typeof(System.Xml.XmlDocument)), Is.EqualTo("T:System.Xml.XmlDocument"));
Assert.That(Convert.ToXmlDocCommentMember(GetType()), Is.EqualTo("T:Jolt.Test.ConvertTestFixture"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Net.WebRequestMethods.File)),
Is.EqualTo("T:System.Net.WebRequestMethods.File"));
}
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is a Type object representing a generic
/// type.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Type_Generic()
{
Assert.That(Convert.ToXmlDocCommentMember(typeof(System.Action<,,,>)), Is.EqualTo("T:System.Action`4"));
Assert.That(Convert.ToXmlDocCommentMember(typeof(__GenericTestType<int, char, byte>)), Is.EqualTo("T:Jolt.Test.Types.__GenericTestType`3"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.List<>)),
Is.EqualTo("T:System.Collections.Generic.List`1"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.List<>.Enumerator)),
Is.EqualTo("T:System.Collections.Generic.List`1.Enumerator"));
}
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is an EventInfo object.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Event()
{
Assert.That(
Convert.ToXmlDocCommentMember(__GenericTestType<int, int, int>.InstanceEvent),
Is.EqualTo("E:Jolt.Test.Types.__GenericTestType`3._InstanceEvent"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Console).GetEvent("CancelKeyPress")),
Is.EqualTo("E:System.Console.CancelKeyPress"));
}
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is a FieldInfo object.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Field()
{
Assert.That(
Convert.ToXmlDocCommentMember(typeof(int).GetField("MaxValue")),
Is.EqualTo("F:System.Int32.MaxValue"));
Assert.That(
Convert.ToXmlDocCommentMember(FieldType<int,int>.Field),
Is.EqualTo("F:Jolt.Test.Types.FieldType`2._Field"));
}
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is a PropertyInfo object.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Property()
{
Assert.That(Convert.ToXmlDocCommentMember(typeof(string).GetProperty("Length")), Is.EqualTo("P:System.String.Length"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.KeyValuePair<,>).GetProperty("Value")),
Is.EqualTo("P:System.Collections.Generic.KeyValuePair`2.Value"));
}
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is a PropertyInfo object representing
/// an indexer.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Indexer()
{
Assert.That(Convert.ToXmlDocCommentMember(typeof(string).GetProperty("Chars")), Is.EqualTo("P:System.String.Chars(System.Int32)"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.List<>).GetProperty("Item")),
Is.EqualTo("P:System.Collections.Generic.List`1.Item(System.Int32)"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.List<int>).GetProperty("Item")),
Is.EqualTo("P:System.Collections.Generic.List`1.Item(System.Int32)"));
Assert.That(
Convert.ToXmlDocCommentMember(IndexerType<int, int>.Indexer_4),
Is.EqualTo("P:Jolt.Test.Types.IndexerType`2.Item(System.Int32,`0,`1,`0)"));
Assert.That(
Convert.ToXmlDocCommentMember(IndexerType<int, int>.Indexer_1),
Is.EqualTo("P:Jolt.Test.Types.IndexerType`2.Item(System.Action{System.Action{System.Action{`1}}})"));
Assert.That(
Convert.ToXmlDocCommentMember(IndexerType<int, int>.Indexer_3),
Is.EqualTo("P:Jolt.Test.Types.IndexerType`2.Item(`0[],System.Action{System.Action{`1}[0:,0:][]}[][],`0[0:,0:,0:,0:][0:,0:,0:][0:,0:][])"));
Assert.That(
Convert.ToXmlDocCommentMember(PointerTestType<int>.Property),
Is.EqualTo("P:Jolt.Test.Types.PointerTestType`1.Item(System.Int32*[],System.Action{System.Action{`0[]}[][]}[],System.Int16***[0:,0:,0:][0:,0:][])"));
}
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is a ConstructorInfo object.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Constructor()
{
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.List<>).GetConstructor(NonPublicStatic, null, Type.EmptyTypes, null)),
Is.EqualTo("M:System.Collections.Generic.List`1.#cctor"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(string).GetConstructor(NonPublicStatic, null, Type.EmptyTypes, null)),
Is.EqualTo("M:System.String.#cctor"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(Exception).GetConstructor(Type.EmptyTypes)),
Is.EqualTo("M:System.Exception.#ctor"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.List<>).GetConstructor(new Type[] { typeof(int) })),
Is.EqualTo("M:System.Collections.Generic.List`1.#ctor(System.Int32)"));
Assert.That(
Convert.ToXmlDocCommentMember(ConstructorType<int, int>.Constructor_4),
Is.EqualTo("M:Jolt.Test.Types.ConstructorType`2.#ctor(System.Int32,`0,`1,`1)"));
Assert.That(
Convert.ToXmlDocCommentMember(ConstructorType<int, int>.Constructor_1),
Is.EqualTo("M:Jolt.Test.Types.ConstructorType`2.#ctor(System.Action{System.Action{System.Action{`0}}})"));
Assert.That(
Convert.ToXmlDocCommentMember(ConstructorType<int, int>.Constructor_3),
Is.EqualTo("M:Jolt.Test.Types.ConstructorType`2.#ctor(`0[],System.Action{System.Action{System.Action{`1}[][]}[]}[][]@,`1[0:,0:,0:,0:][0:,0:,0:][0:,0:][])"));
Assert.That(
Convert.ToXmlDocCommentMember(PointerTestType<int>.Constructor),
Is.EqualTo("M:Jolt.Test.Types.PointerTestType`1.#ctor(System.Action{`0[]}[],System.String***[0:,0:,0:][0:,0:][]@)"));
}
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is a ConstructorInfo object.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Method()
{
Assert.That(
Convert.ToXmlDocCommentMember(typeof(int).GetMethod("GetHashCode")),
Is.EqualTo("M:System.Int32.GetHashCode"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(string).GetMethod("Insert")),
Is.EqualTo("M:System.String.Insert(System.Int32,System.String)"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.List<>).GetMethod("Clear")),
Is.EqualTo("M:System.Collections.Generic.List`1.Clear"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(System.Collections.Generic.List<>).GetMethod("ConvertAll")),
Is.EqualTo("M:System.Collections.Generic.List`1.ConvertAll``1(System.Converter{`0,``0})"));
Assert.That(
Convert.ToXmlDocCommentMember(typeof(Enumerable).GetMethods().Single(m => m.Name == "ToLookup" && m.GetParameters().Length == 4)),
Is.EqualTo("M:System.Linq.Enumerable.ToLookup``3(System.Collections.Generic.IEnumerable{``0},System.Func{``0,``1},System.Func{``0,``2},System.Collections.Generic.IEqualityComparer{``1})"));
Assert.That(
Convert.ToXmlDocCommentMember(PointerTestType<int>.Method),
Is.EqualTo("M:Jolt.Test.Types.PointerTestType`1._method``1(System.Int32,`0[0:,0:]@,System.Action{``0[0:,0:][]}*[][0:,0:]@,System.Action{System.Int32**[0:,0:,0:][]})"));
}
/// <summary>
/// Verifies the behavior of the ToXmlDocCommentMember() method
/// when the given parameter is a MethodInfo object that refers
/// to an operator.
/// </summary>
[Test]
public void ToXmlDocCommentMember_Operator()
{
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Subtraction),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Subtraction(Jolt.Test.Types.OperatorTestType{`0,`1},Jolt.Test.Types.OperatorTestType{`0,`1})"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Explcit_ToInt),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Explicit(Jolt.Test.Types.OperatorTestType{`0,`1})~System.Int32"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Explcit_FromInt),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Explicit(System.Int32)~Jolt.Test.Types.OperatorTestType{`0,`1}"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Implcit_ToLong),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Implicit(Jolt.Test.Types.OperatorTestType{`0,`1})~System.Int64"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Implcit_FromLong),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Implicit(System.Int64)~Jolt.Test.Types.OperatorTestType{`0,`1}"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Explicit_FromT),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Explicit(`0)~Jolt.Test.Types.OperatorTestType{`0,`1}"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Explicit_FromU),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Explicit(`1)~Jolt.Test.Types.OperatorTestType{`0,`1}"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Explicit_FromAction),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Explicit(System.Action{System.Action{System.Action{`1}}})~Jolt.Test.Types.OperatorTestType{`0,`1}"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Implicit_ToTArray),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Implicit(Jolt.Test.Types.OperatorTestType{`0,`1})~`0[]"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Implicit_ToUArray),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Implicit(Jolt.Test.Types.OperatorTestType{`0,`1})~`1[0:,0:,0:,0:][0:,0:,0:][0:,0:][]"));
Assert.That(
Convert.ToXmlDocCommentMember(OperatorTestType<int, int>.Op_Implicit_ToActionArray),
Is.EqualTo("M:Jolt.Test.Types.OperatorTestType`2.op_Implicit(Jolt.Test.Types.OperatorTestType{`0,`1})~System.Action{System.Action{`1}[0:,0:][]}[][]"));
}
/// <summary>
/// Verifies the behavior of the ToParamterTypes() method.
/// </summary>
[Test]
public void ToParameterTypes()
{
ParameterInfo[] methodParams = GetType().GetMethod("__g", NonPublicInstance).GetParameters();
Type[] methodParamTypes = Convert.ToParameterTypes(methodParams);
Assert.That(methodParamTypes, Has.Length.EqualTo(4));
Assert.That(methodParamTypes, Has.Length.EqualTo(methodParams.Length));
Assert.That(methodParamTypes[0], Is.EqualTo(typeof(int)));
Assert.That(methodParamTypes[1], Is.EqualTo(typeof(int)));
Assert.That(methodParamTypes[2], Is.EqualTo(typeof(double)));
Assert.That(methodParamTypes[3], Is.EqualTo(typeof(byte)));
}
/// <summary>
/// Verifies the behavior of the ToParamterTypes() method when a
/// given method has no parameters..
/// </summary>
[Test]
public void ToParameterTypes_NoParams()
{
ParameterInfo[] methodParams = GetType().GetMethod("__f", NonPublicInstance).GetParameters();
Type[] methodParamTypes = Convert.ToParameterTypes(methodParams);
Assert.That(methodParamTypes, Is.Empty);
Assert.That(methodParamTypes, Has.Length.EqualTo(methodParams.Length));
}
/// <summary>
/// Verifies the behavior of the ToParameterTypes() method when a
/// given method has generic arguments declared at the class level.
/// </summary>
[Test]
public void ToParameterTypes_GenericTypeArguments()
{
Type[] genericTypeArguments = typeof(__GenericTestType<,,>).GetGenericArguments();
ParameterInfo[] methodParams = __GenericTestType<int, int, int>.NonGenericFunction_MixedArgs.GetParameters();
Type[] methodParamTypes = Convert.ToParameterTypes(methodParams, genericTypeArguments);
Assert.That(methodParamTypes, Has.Length.EqualTo(3));
Assert.That(methodParamTypes, Has.Length.EqualTo(methodParams.Length));
Assert.That(methodParamTypes[0], Is.EqualTo(genericTypeArguments[1]));
Assert.That(methodParamTypes[1], Is.EqualTo(genericTypeArguments[2]));
Assert.That(methodParamTypes[2], Is.EqualTo(typeof(int)));
}
/// <summary>
/// Verifies the behavior of the ToParameterTypes() method when a
/// given method has no parameters, but the declaring class has
/// generic arguments.
/// </summary>
[Test]
public void ToParameterTypes_GenericTypeArguments_NoParams()
{
MethodInfo genericMethod = __GenericTestType<int, int, int>.NoParameters;
Type[] genericTypeArguments = genericMethod.DeclaringType.GetGenericArguments();
ParameterInfo[] methodParams = genericMethod.GetParameters();
Type[] methodParamTypes = Convert.ToParameterTypes(methodParams, genericTypeArguments);
Assert.That(methodParamTypes, Is.Empty);
Assert.That(methodParamTypes, Has.Length.EqualTo(methodParams.Length));
}
/// <summary>
/// Verifies the behavior of the ToParameterTypes() method when a
/// given method has generic arguments declared at the class
/// and method level.
/// </summary>
[Test]
public void ToParameterTypes_GenericTypeAndMethodArguments()
{
MethodInfo genericMethod = __GenericTestType<int, int, int>.GenericFunction_MixedArgs;
Type[] genericTypeArguments = genericMethod.DeclaringType.GetGenericArguments();
Type[] genericMethodArguments = genericMethod.GetGenericArguments();
ParameterInfo[] methodParams = genericMethod.GetParameters();
Type[] methodParamTypes = Convert.ToParameterTypes(methodParams, genericTypeArguments, genericMethodArguments);
Assert.That(methodParamTypes, Has.Length.EqualTo(6));
Assert.That(methodParamTypes, Has.Length.EqualTo(methodParams.Length));
Assert.That(methodParamTypes[0], Is.EqualTo(genericMethodArguments[2]));
Assert.That(methodParamTypes[1], Is.EqualTo(genericMethodArguments[0]));
Assert.That(methodParamTypes[2], Is.EqualTo(genericMethodArguments[1]));
Assert.That(methodParamTypes[3], Is.EqualTo(genericTypeArguments[2]));
Assert.That(methodParamTypes[4], Is.EqualTo(genericTypeArguments[1]));
Assert.That(methodParamTypes[5], Is.EqualTo(typeof(int)));
}
/// <summary>
/// Verifies the behavior of the ToParameterTypes() method when a
/// given method has no parameters, but the method and declaring class
/// have generic arguments.
/// </summary>
[Test]
public void ToParameterTypes_GenericTypeAndMethodArguments_NoParams()
{
MethodInfo genericMethod = __GenericTestType<int, int, int>.OneGenericParameter;
Type[] genericTypeArguments = genericMethod.DeclaringType.GetGenericArguments();
Type[] genericMethodArguments = genericMethod.GetGenericArguments();
ParameterInfo[] methodParams = genericMethod.GetParameters();
Type[] methodParamTypes = Convert.ToParameterTypes(methodParams, genericTypeArguments, genericMethodArguments);
Assert.That(methodParamTypes, Is.Empty);
Assert.That(methodParamTypes, Has.Length.EqualTo(methodParams.Length));
}
/// <summary>
/// Verifies the behavior of the ToMethodSignatureType() method when
/// the given type is not generic.
/// </summary>
[Test]
public void ToMethodSignatureType()
{
Type type = Convert.ToMethodSignatureType(
__GenericTestType<int,int,int>.NoGenericParameters.GetParameters()[0].ParameterType,
Type.EmptyTypes,
Type.EmptyTypes);
Assert.That(type, Is.EqualTo(typeof(int)));
}
/// <summary>
/// Verifies the behavior of the ToMethodSignatureType() method when
/// the given type is a generic type argument.
/// </summary>
[Test]
public void ToMethodSignatureType_GenericTypeArgument()
{
MethodInfo nonGenericMethod = __GenericTestType<int, int, int>.NonGenericFunction;
Type[] genericTypeArguments = nonGenericMethod.DeclaringType.GetGenericArguments();
Type type = Convert.ToMethodSignatureType(
nonGenericMethod.GetParameters()[0].ParameterType,
genericTypeArguments,
Type.EmptyTypes);
Assert.That(type, Is.EqualTo(genericTypeArguments[1]));
}
/// <summary>
/// Verifies the behavior of the ToMethodSignatureType() method when
/// the given parameter type is a generic method argument.
/// </summary>
[Test]
public void ToMethodSignatureType_GenericMethodArgument()
{
MethodInfo genericMethod = __GenericTestType<int, int, int>.GenericFunction;
Type[] genericMethodArguments = genericMethod.GetGenericArguments();
Type type = Convert.ToMethodSignatureType(
genericMethod.GetParameters()[0].ParameterType,
genericMethodArguments,
Type.EmptyTypes);
Assert.That(type, Is.EqualTo(genericMethodArguments[0]));
}
/// <summary>
/// Verifies the behavior of the ToTypeNames() method.
/// </summary>
[Test]
public void ToTypeNames()
{
Type[] types = { typeof(int), typeof(int), typeof(double), typeof(byte) };
string[] typeNames = Convert.ToTypeNames(types);
Assert.That(typeNames, Has.Length.EqualTo(4));
Assert.That(typeNames, Has.Length.EqualTo(types.Length));
Assert.That(typeNames[0], Is.EqualTo("Int32"));
Assert.That(typeNames[1], Is.EqualTo("Int32"));
Assert.That(typeNames[2], Is.EqualTo("Double"));
Assert.That(typeNames[3], Is.EqualTo("Byte"));
}
/// <summary>
/// Verifies the behavior o fhte ToTypeNames() method when a
/// given type list has no items.
/// </summary>
[Test]
public void ToTypeNames_NoTypes()
{
Assert.That(Convert.ToTypeNames(Type.EmptyTypes), Is.Empty);
}
#endregion
#region private methods -------------------------------------------------------------------
private void __f() { }
private void __g(int x, int y, double z, byte b) { }
#endregion
#region private fields --------------------------------------------------------------------
private static readonly BindingFlags NonPublicInstance = BindingFlags.Instance | BindingFlags.NonPublic;
private static readonly BindingFlags NonPublicStatic = BindingFlags.Static | BindingFlags.NonPublic;
#endregion
}
}
| |
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using NUnit.Framework;
using UnityEngine;
namespace Mujoco {
[TestFixture]
public class MjGeomSettingsGenerationTests {
private MjGeomSettings _settings;
private XmlDocument _doc;
private XmlElement _mjcf;
[SetUp]
public void SetUp() {
_settings = new MjGeomSettings();
_doc = new XmlDocument();
_mjcf = (XmlElement)_doc.AppendChild(_doc.CreateElement("geom"));
}
[Test]
public void ContactFilteringTypeMjcf() {
_settings.Filtering.Contype = 5;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"contype=""5"""));
}
[Test]
public void ContactFilteringAffinityMjcf() {
_settings.Filtering.Conaffinity = 5;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"conaffinity=""5"""));
}
[Test]
public void ContactFilteringGroupMjcf() {
_settings.Filtering.Group = 5;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"group=""5"""));
}
[Test]
public void SolverContactDimensionalityMjcf() {
_settings.Solver.ConDim = 5;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"condim=""5"""));
}
[Test]
public void SolverMixMjcf() {
_settings.Solver.SolMix = 5;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"solmix=""5"""));
}
[Test]
public void SolverReferenceMjcf() {
_settings.Solver.SolRef.TimeConst = 5;
_settings.Solver.SolRef.DampRatio = 6;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"solref=""5 6"""));
}
[Test]
public void SolverImpendanceMjcf() {
_settings.Solver.SolImp.DMin = 5;
_settings.Solver.SolImp.DMax = 6;
_settings.Solver.SolImp.Width = 7;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"solimp=""5 6 7"""));
}
[Test]
public void SolverMarginMjcf() {
_settings.Solver.Margin = 5;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"margin=""5"""));
}
[Test]
public void SolverGapMjcf() {
_settings.Solver.Gap = 5;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"gap=""5"""));
}
[Test]
public void MaterialFrictionMjcf() {
_settings.Friction.Sliding = 5;
_settings.Friction.Torsional = 6;
_settings.Friction.Rolling = 7;
_settings.ToMjcf(_mjcf);
Assert.That(_doc.OuterXml, Does.Contain(@"friction=""5 6 7"""));
}
}
[TestFixture]
public class MjGeomSettingsParsingTests {
private MjGeomSettings _settings;
private XmlDocument _doc;
private XmlElement _mjcf;
[SetUp]
public void SetUp() {
_doc = new XmlDocument();
_mjcf = (XmlElement)_doc.AppendChild(_doc.CreateElement("geom"));
_settings = new MjGeomSettings();
}
[Test]
public void ContactFilteringTypeMjcf() {
_mjcf.SetAttribute("contype", "5");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Filtering.Contype, Is.EqualTo(5));
}
[Test]
public void ContactFilteringAffinityMjcf() {
_mjcf.SetAttribute("conaffinity", "5");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Filtering.Conaffinity, Is.EqualTo(5));
}
[Test]
public void ContactFilteringGroupMjcf() {
_mjcf.SetAttribute("group", "5");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Filtering.Group, Is.EqualTo(5));
}
[Test]
public void SolverContactDimensionalityMjcf() {
_mjcf.SetAttribute("condim", "5");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Solver.ConDim, Is.EqualTo(5));
}
[Test]
public void SolverMixMjcf() {
_mjcf.SetAttribute("solmix", "5");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Solver.SolMix, Is.EqualTo(5));
}
[Test]
public void SolverReferenceMjcf() {
_mjcf.SetAttribute("solref", "5 6");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Solver.SolRef.TimeConst, Is.EqualTo(5));
Assert.That(_settings.Solver.SolRef.DampRatio, Is.EqualTo(6));
}
[Test]
public void SolverImpendanceMjcf() {
_mjcf.SetAttribute("solimp", "5 6 7");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Solver.SolImp.DMin, Is.EqualTo(5));
Assert.That(_settings.Solver.SolImp.DMax, Is.EqualTo(6));
Assert.That(_settings.Solver.SolImp.Width, Is.EqualTo(7));
}
[Test]
public void SolverMarginMjcf() {
_mjcf.SetAttribute("margin", "5");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Solver.Margin, Is.EqualTo(5));
}
[Test]
public void SolverGapMjcf() {
_mjcf.SetAttribute("gap", "5");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Solver.Gap, Is.EqualTo(5));
}
[Test]
public void MaterialFrictionMjcf() {
_mjcf.SetAttribute("friction", "5 6 7");
_settings.FromMjcf(_mjcf);
Assert.That(_settings.Friction.Sliding, Is.EqualTo(5));
Assert.That(_settings.Friction.Torsional, Is.EqualTo(6));
Assert.That(_settings.Friction.Rolling, Is.EqualTo(7));
}
}
}
| |
/* ====================================================================
Copyright 2002-2004 Apache Software Foundation
Licensed Under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using NPOI.SS.Util;
using NPOI.Util;
using NPOI.SS.Formula.PTG;
using NPOI.SS.Formula;
/**
* Title: DATAVALIDATION Record (0x01BE)<p/>
* Description: This record stores data validation Settings and a list of cell ranges
* which contain these Settings. The data validation Settings of a sheet
* are stored in a sequential list of DV records. This list Is followed by
* DVAL record(s)
* @author Dragos Buleandra ([email protected])
* @version 2.0-pre
*/
public class DVRecord : StandardRecord
{
private static readonly UnicodeString NULL_TEXT_STRING = new UnicodeString("\0");
public const short sid = 0x01BE;
/** Option flags */
private int _option_flags;
/** Title of the prompt box */
private UnicodeString _promptTitle;
/** Title of the error box */
private UnicodeString _errorTitle;
/** Text of the prompt box */
private UnicodeString _promptText;
/** Text of the error box */
private UnicodeString _errorText;
/** Not used - Excel seems to always write 0x3FE0 */
private short _not_used_1 = 0x3FE0;
/** Formula data for first condition (RPN token array without size field) */
private NPOI.SS.Formula.Formula _formula1;
/** Not used - Excel seems to always write 0x0000 */
private short _not_used_2 = 0x0000;
/** Formula data for second condition (RPN token array without size field) */
private NPOI.SS.Formula.Formula _formula2;
/** Cell range address list with all affected ranges */
private CellRangeAddressList _regions;
public const int STRING_PROMPT_TITLE = 0;
public const int STRING_ERROR_TITLE = 1;
public const int STRING_PROMPT_TEXT = 2;
public const int STRING_ERROR_TEXT = 3;
/**
* Option flags field
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
private BitField opt_data_type = new BitField(0x0000000F);
private BitField opt_error_style = new BitField(0x00000070);
private BitField opt_string_list_formula = new BitField(0x00000080);
private BitField opt_empty_cell_allowed = new BitField(0x00000100);
private BitField opt_suppress_dropdown_arrow = new BitField(0x00000200);
private BitField opt_show_prompt_on_cell_selected = new BitField(0x00040000);
private BitField opt_show_error_on_invalid_value = new BitField(0x00080000);
private BitField opt_condition_operator = new BitField(0x00F00000);
public DVRecord()
{
}
public DVRecord(int validationType, int operator1, int errorStyle, bool emptyCellAllowed,
bool suppressDropDownArrow, bool isExplicitList,
bool showPromptBox, String promptTitle, String promptText,
bool showErrorBox, String errorTitle, String errorText,
Ptg[] formula1, Ptg[] formula2,
CellRangeAddressList regions)
{
int flags = 0;
flags = opt_data_type.SetValue(flags, validationType);
flags = opt_condition_operator.SetValue(flags, operator1);
flags = opt_error_style.SetValue(flags, errorStyle);
flags = opt_empty_cell_allowed.SetBoolean(flags, emptyCellAllowed);
flags = opt_suppress_dropdown_arrow.SetBoolean(flags, suppressDropDownArrow);
flags = opt_string_list_formula.SetBoolean(flags, isExplicitList);
flags = opt_show_prompt_on_cell_selected.SetBoolean(flags, showPromptBox);
flags = opt_show_error_on_invalid_value.SetBoolean(flags, showErrorBox);
_option_flags = flags;
_promptTitle = ResolveTitleText(promptTitle);
_promptText = ResolveTitleText(promptText);
_errorTitle = ResolveTitleText(errorTitle);
_errorText = ResolveTitleText(errorText);
_formula1 = NPOI.SS.Formula.Formula.Create(formula1);
_formula2 = NPOI.SS.Formula.Formula.Create(formula2);
_regions = regions;
}
/**
* Constructs a DV record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public DVRecord(RecordInputStream in1)
{
_option_flags = in1.ReadInt();
_promptTitle = ReadUnicodeString(in1);
_errorTitle = ReadUnicodeString(in1);
_promptText = ReadUnicodeString(in1);
_errorText = ReadUnicodeString(in1);
int field_size_first_formula = in1.ReadUShort();
_not_used_1 = in1.ReadShort();
//read first formula data condition
_formula1 = NPOI.SS.Formula.Formula.Read(field_size_first_formula, in1);
int field_size_sec_formula = in1.ReadUShort();
_not_used_2 = in1.ReadShort();
//read sec formula data condition
_formula2 = NPOI.SS.Formula.Formula.Read(field_size_sec_formula, in1);
//read cell range address list with all affected ranges
_regions = new CellRangeAddressList(in1);
}
/**
* When entered via the UI, Excel translates empty string into "\0"
* While it is possible to encode the title/text as empty string (Excel doesn't exactly crash),
* the resulting tool-tip text / message box looks wrong. It is best to do the same as the
* Excel UI and encode 'not present' as "\0".
*/
private static UnicodeString ResolveTitleText(String str)
{
if (str == null || str.Length < 1)
{
return NULL_TEXT_STRING;
}
return new UnicodeString(str);
}
private static String ResolveTitleString(UnicodeString us)
{
if (us == null || us.Equals(NULL_TEXT_STRING))
{
return null;
}
return us.String;
}
private static UnicodeString ReadUnicodeString(RecordInputStream in1)
{
return new UnicodeString(in1);
}
/**
* Get the condition data type
* @return the condition data type
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public int DataType
{
get
{
return this.opt_data_type.GetValue(this._option_flags);
}
set { this._option_flags = this.opt_data_type.SetValue(this._option_flags, value); }
}
/**
* Get the condition error style
* @return the condition error style
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public int ErrorStyle
{
get
{
return this.opt_error_style.GetValue(this._option_flags);
}
set { this._option_flags = this.opt_error_style.SetValue(this._option_flags, value); }
}
/**
* return true if in list validations the string list Is explicitly given in the formula, false otherwise
* @return true if in list validations the string list Is explicitly given in the formula, false otherwise
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public bool ListExplicitFormula
{
get
{
return (this.opt_string_list_formula.IsSet(this._option_flags));
}
set { this._option_flags = this.opt_string_list_formula.SetBoolean(this._option_flags, value); }
}
/**
* return true if empty values are allowed in cells, false otherwise
* @return if empty values are allowed in cells, false otherwise
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public bool EmptyCellAllowed
{
get
{
return (this.opt_empty_cell_allowed.IsSet(this._option_flags));
}
set { this._option_flags = this.opt_empty_cell_allowed.SetBoolean(this._option_flags, value); }
}
/**
* @return <code>true</code> if drop down arrow should be suppressed when list validation is
* used, <code>false</code> otherwise
*/
public bool SuppressDropdownArrow
{
get
{
return (opt_suppress_dropdown_arrow.IsSet(_option_flags));
}
}
/**
* return true if a prompt window should appear when cell Is selected, false otherwise
* @return if a prompt window should appear when cell Is selected, false otherwise
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public bool ShowPromptOnCellSelected
{
get
{
return (this.opt_show_prompt_on_cell_selected.IsSet(this._option_flags));
}
}
/**
* return true if an error window should appear when an invalid value Is entered in the cell, false otherwise
* @return if an error window should appear when an invalid value Is entered in the cell, false otherwise
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public bool ShowErrorOnInvalidValue
{
get
{
return (this.opt_show_error_on_invalid_value.IsSet(this._option_flags));
}
set { this._option_flags = this.opt_show_error_on_invalid_value.SetBoolean(this._option_flags, value); }
}
/**
* Get the condition operator
* @return the condition operator
* @see org.apache.poi.hssf.util.HSSFDataValidation utility class
*/
public int ConditionOperator
{
get
{
return this.opt_condition_operator.GetValue(this._option_flags);
}
set
{
this._option_flags = this.opt_condition_operator.SetValue(this._option_flags, value);
}
}
public String PromptTitle
{
get
{
return ResolveTitleString(_promptTitle);
}
}
public String ErrorTitle
{
get
{
return ResolveTitleString(_errorTitle);
}
}
public String PromptText
{
get
{
return ResolveTitleString(_promptText);
}
}
public String ErrorText
{
get
{
return ResolveTitleString(_errorText);
}
}
public Ptg[] Formula1
{
get
{
return Formula.GetTokens(_formula1);
}
}
public Ptg[] Formula2
{
get
{
return Formula.GetTokens(_formula2);
}
}
public CellRangeAddressList CellRangeAddress
{
get
{
return this._regions;
}
set { this._regions = value; }
}
/**
* Gets the option flags field.
* @return options - the option flags field
*/
public int OptionFlags
{
get
{
return this._option_flags;
}
}
public override String ToString()
{
/* @todo DVRecord string representation */
StringBuilder buffer = new StringBuilder();
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteInt(_option_flags);
SerializeUnicodeString(_promptTitle, out1);
SerializeUnicodeString(_errorTitle, out1);
SerializeUnicodeString(_promptText, out1);
SerializeUnicodeString(_errorText, out1);
out1.WriteShort(_formula1.EncodedTokenSize);
out1.WriteShort(_not_used_1);
_formula1.SerializeTokens(out1);
out1.WriteShort(_formula2.EncodedTokenSize);
out1.WriteShort(_not_used_2);
_formula2.SerializeTokens(out1);
_regions.Serialize(out1);
}
private static void SerializeUnicodeString(UnicodeString us, ILittleEndianOutput out1)
{
StringUtil.WriteUnicodeString(out1, us.String);
}
private static int GetUnicodeStringSize(UnicodeString us)
{
String str = us.String;
return 3 + str.Length * (StringUtil.HasMultibyte(str) ? 2 : 1);
}
protected override int DataSize
{
get
{
int size = 4 + 2 + 2 + 2 + 2;//header+options_field+first_formula_size+first_unused+sec_formula_size+sec+unused;
size += GetUnicodeStringSize(_promptTitle);
size += GetUnicodeStringSize(_errorTitle);
size += GetUnicodeStringSize(_promptText);
size += GetUnicodeStringSize(_errorText);
size += _formula1.EncodedTokenSize;
size += _formula2.EncodedTokenSize;
size += _regions.Size;
return size;
}
}
public override short Sid
{
get { return DVRecord.sid; }
}
/**
* Clones the object. Uses serialisation, as the
* contents are somewhat complex
*/
public override Object Clone()
{
return CloneViaReserialise();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using MICore;
namespace Microsoft.MIDebugEngine
{
// This class implements IDebugThread2 which represents a thread running in a program.
internal class AD7Thread : IDebugThread2
{
private readonly AD7Engine _engine;
private readonly DebuggedThread _debuggedThread;
public int Id
{
get
{
return _debuggedThread.Id;
}
}
public AD7Thread(AD7Engine engine, DebuggedThread debuggedThread)
{
_engine = engine;
_debuggedThread = debuggedThread;
}
private ThreadContext GetThreadContext()
{
ThreadContext threadContext = null;
_engine.DebuggedProcess.WorkerThread.RunOperation(async () => threadContext = await _engine.DebuggedProcess.ThreadCache.GetThreadContext(_debuggedThread));
return threadContext;
}
private string GetCurrentLocation(bool fIncludeModuleName)
{
ThreadContext cxt = GetThreadContext();
string location = null;
if (cxt != null)
{
location = "";
if (fIncludeModuleName)
{
if (cxt.From != null)
{
location = cxt.From + '!';
}
else
{
DebuggedModule module = cxt.FindModule(_engine.DebuggedProcess);
if (module != null)
{
location = module.Name + '!';
}
}
}
if (cxt.Function == null)
{
location += _engine.GetAddressDescription(cxt.pc.Value);
}
else
{
location += cxt.Function;
}
}
return location;
}
internal DebuggedThread GetDebuggedThread()
{
return _debuggedThread;
}
#region IDebugThread2 Members
// Determines whether the next statement can be set to the given stack frame and code context.
int IDebugThread2.CanSetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext)
{
// CLRDBG TODO: This implementation should be changed to compare the method token
ulong addr = ((AD7MemoryAddress)codeContext).Address;
AD7StackFrame frame = ((AD7StackFrame)stackFrame);
if (frame.ThreadContext.Level != 0 || frame.Thread != this || !frame.ThreadContext.pc.HasValue || _engine.DebuggedProcess.MICommandFactory.Mode == MIMode.Clrdbg)
{
return Constants.S_FALSE;
}
if (addr == frame.ThreadContext.pc)
{
return Constants.S_OK;
}
string toFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, addr);
string fromFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, frame.ThreadContext.pc.Value);
if (toFunc != fromFunc)
{
return Constants.S_FALSE;
}
return Constants.S_OK;
}
// Retrieves a list of the stack frames for this thread.
// For the sample engine, enumerating the stack frames requires walking the callstack in the debuggee for this thread
// and coverting that to an implementation of IEnumDebugFrameInfo2.
// Real engines will most likely want to cache this information to avoid recomputing it each time it is asked for,
// and or construct it on demand instead of walking the entire stack.
int IDebugThread2.EnumFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, out IEnumDebugFrameInfo2 enumObject)
{
enumObject = null;
try
{
// get the thread's stack frames
System.Collections.Generic.List<ThreadContext> stackFrames = null;
_engine.DebuggedProcess.WorkerThread.RunOperation(async () => stackFrames = await _engine.DebuggedProcess.ThreadCache.StackFrames(_debuggedThread));
int numStackFrames = stackFrames != null ? stackFrames.Count : 0;
FRAMEINFO[] frameInfoArray;
if (numStackFrames == 0)
{
// failed to walk any frames. Return an empty stack.
frameInfoArray = new FRAMEINFO[0];
}
else
{
uint low = stackFrames[0].Level;
uint high = stackFrames[stackFrames.Count - 1].Level;
FilterUnknownFrames(stackFrames);
numStackFrames = stackFrames.Count;
frameInfoArray = new FRAMEINFO[numStackFrames];
List<ArgumentList> parameters = null;
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS) != 0 && !_engine.DebuggedProcess.MICommandFactory.SupportsFrameFormatting)
{
_engine.DebuggedProcess.WorkerThread.RunOperation(async () => parameters = await _engine.DebuggedProcess.GetParameterInfoOnly(this, (dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_VALUES) != 0,
(dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_TYPES) != 0, low, high));
}
for (int i = 0; i < numStackFrames; i++)
{
var p = parameters != null ? parameters.Find((ArgumentList t) => t.Item1 == stackFrames[i].Level) : null;
AD7StackFrame frame = new AD7StackFrame(_engine, this, stackFrames[i]);
frame.SetFrameInfo(dwFieldSpec, out frameInfoArray[i], p != null ? p.Item2 : null);
}
}
enumObject = new AD7FrameInfoEnum(frameInfoArray);
return Constants.S_OK;
}
catch (MIException e)
{
return e.HResult;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
private void FilterUnknownFrames(System.Collections.Generic.List<ThreadContext> stackFrames)
{
bool lastWasQuestion = false;
for (int i = 0; i < stackFrames.Count;)
{
// replace sequences of "??" with one UnknownCode frame
if (stackFrames[i].Function == null || stackFrames[i].Function.Equals("??", StringComparison.Ordinal))
{
if (lastWasQuestion)
{
stackFrames.RemoveAt(i);
continue;
}
lastWasQuestion = true;
stackFrames[i] = new ThreadContext(stackFrames[i].pc, stackFrames[i].TextPosition, ResourceStrings.UnknownCode, stackFrames[i].Level, null);
}
else
{
lastWasQuestion = false;
}
i++;
}
}
// Get the name of the thread. For the sample engine, the name of the thread is always "Sample Engine Thread"
int IDebugThread2.GetName(out string threadName)
{
threadName = _debuggedThread.Name;
return Constants.S_OK;
}
// Return the program that this thread belongs to.
int IDebugThread2.GetProgram(out IDebugProgram2 program)
{
program = _engine;
return Constants.S_OK;
}
// Gets the system thread identifier.
int IDebugThread2.GetThreadId(out uint threadId)
{
threadId = _debuggedThread.TargetId;
return Constants.S_OK;
}
// Gets properties that describe a thread.
int IDebugThread2.GetThreadProperties(enum_THREADPROPERTY_FIELDS dwFields, THREADPROPERTIES[] ptp)
{
try
{
THREADPROPERTIES props = new THREADPROPERTIES();
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_ID) != 0)
{
props.dwThreadId = _debuggedThread.TargetId;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_ID;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT) != 0)
{
// sample debug engine doesn't support suspending threads
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_STATE) != 0)
{
props.dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_RUNNING;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_PRIORITY) != 0)
{
props.bstrPriority = "Normal";
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_PRIORITY;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_NAME) != 0)
{
props.bstrName = _debuggedThread.Name;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_NAME;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_LOCATION) != 0)
{
props.bstrLocation = GetCurrentLocation(true);
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_LOCATION;
if (props.bstrLocation == null)
{
// Thread deletion events may be delayed, in which case the thread object may still be present in the cache
// but the engine is unable to retrieve new data for it. So handle failure to get info for a dead thread.
props.dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_DEAD;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE;
props.bstrLocation = ResourceStrings.ThreadExited;
}
}
ptp[0] = props;
return Constants.S_OK;
}
catch (MIException e)
{
return e.HResult;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
// Resume a thread.
// This is called when the user chooses "Unfreeze" from the threads window when a thread has previously been frozen.
int IDebugThread2.Resume(out uint suspendCount)
{
// The sample debug engine doesn't support suspending/resuming threads
suspendCount = 0;
return Constants.E_NOTIMPL;
}
// Sets the next statement to the given stack frame and code context.
int IDebugThread2.SetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext)
{
// CLRDBG TODO: This implementation should be changed to call an MI command
ulong addr = ((AD7MemoryAddress)codeContext).Address;
AD7StackFrame frame = ((AD7StackFrame)stackFrame);
if (frame.ThreadContext.Level != 0 || frame.Thread != this || !frame.ThreadContext.pc.HasValue || _engine.DebuggedProcess.MICommandFactory.Mode == MIMode.Clrdbg)
{
return Constants.S_FALSE;
}
string toFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, addr);
string fromFunc = EngineUtils.GetAddressDescription(_engine.DebuggedProcess, frame.ThreadContext.pc.Value);
if (toFunc != fromFunc)
{
return Constants.S_FALSE;
}
string result = frame.EvaluateExpression("$pc=" + EngineUtils.AsAddr(addr));
if (result != null)
{
_engine.DebuggedProcess.ThreadCache.MarkDirty();
return Constants.S_OK;
}
return Constants.S_FALSE;
}
// suspend a thread.
// This is called when the user chooses "Freeze" from the threads window
int IDebugThread2.Suspend(out uint suspendCount)
{
// The sample debug engine doesn't support suspending/resuming threads
suspendCount = 0;
return Constants.E_NOTIMPL;
}
#endregion
#region Uncalled interface methods
// These methods are not currently called by the Visual Studio debugger, so they don't need to be implemented
int IDebugThread2.GetLogicalThread(IDebugStackFrame2 stackFrame, out IDebugLogicalThread2 logicalThread)
{
Debug.Fail("This function is not called by the debugger");
logicalThread = null;
return Constants.E_NOTIMPL;
}
int IDebugThread2.SetThreadName(string name)
{
Debug.Fail("This function is not called by the debugger");
return Constants.E_NOTIMPL;
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using WebsitePanel.Providers.Web.Iis.Common;
using Microsoft.Web.Administration;
namespace WebsitePanel.Providers.Web.Delegation
{
internal sealed class DelegationRulesModuleService : ConfigurationModuleService
{
public void RestrictRuleToUser(string providers, string path, string accountName)
{
var rulePredicate = new Predicate<ConfigurationElement>(x => { return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path); });
//
var userPredicate = new Predicate<ConfigurationElement>(x => { return x.Attributes["name"].Value.Equals(accountName); });
//
using (var srvman = new ServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
// return if system.webServer/management/delegation section is not exist in config file
if (!HasDelegationSection(adminConfig))
return;
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Update rule if exists
foreach (var rule in rulesCollection)
{
if (rulePredicate.Invoke(rule) == true)
{
var permissions = rule.GetCollection("permissions");
//
var user = default(ConfigurationElement);
//
foreach (var item in permissions)
{
if (userPredicate.Invoke(item))
{
user = item;
//
break;
}
}
//
if (user == null)
{
user = permissions.CreateElement("user");
//
user.SetAttributeValue("name", accountName);
user.SetAttributeValue("isRole", false);
//
permissions.Add(user);
}
//
if (user != null)
{
user.SetAttributeValue("accessType", "Deny");
//
srvman.CommitChanges();
}
}
}
}
}
public void AllowRuleToUser(string providers, string path, string accountName)
{
RemoveUserFromRule(providers, path, accountName);
}
public void RemoveUserFromRule(string providers, string path, string accountName)
{
var rulePredicate = new Predicate<ConfigurationElement>(x => { return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path); });
//
var userPredicate = new Predicate<ConfigurationElement>(x => { return x.Attributes["name"].Value.Equals(accountName); });
//
using (var srvman = new ServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
// return if system.webServer/management/delegation section is not exist in config file
if (!HasDelegationSection(adminConfig))
return;
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Update rule if exists
foreach (var rule in rulesCollection)
{
if (rulePredicate.Invoke(rule) == true)
{
var permissions = rule.GetCollection("permissions");
//
foreach (var user in permissions)
{
if (userPredicate.Invoke(user))
{
permissions.Remove(user);
//
srvman.CommitChanges();
//
break;
}
}
}
}
}
}
public bool DelegationRuleExists(string providers, string path)
{
var exists = false;
//
var predicate = new Predicate<ConfigurationElement>(x =>
{
return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path);
});
//
using (var srvman = new ServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
// return if system.webServer/management/delegation section is not exist in config file
if (!HasDelegationSection(adminConfig))
return false;
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Update rule if exists
foreach (var rule in rulesCollection)
{
if (predicate.Invoke(rule) == true)
{
exists = true;
//
break;
}
}
}
//
return exists;
}
public void AddDelegationRule(string providers, string path, string pathType, string identityType, string userName, string userPassword)
{
var predicate = new Predicate<ConfigurationElement>(x =>
{
return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path);
});
//
using (var srvman = GetServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
// return if system.webServer/management/delegation section is not exist in config file
if (!HasDelegationSection(adminConfig))
return;
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Update rule if exists
foreach (var rule in rulesCollection)
{
//
if (predicate.Invoke(rule) == true)
{
if (identityType.Equals("SpecificUser"))
{
var runAsElement = rule.ChildElements["runAs"];
//
runAsElement.SetAttributeValue("userName", userName);
runAsElement.SetAttributeValue("password", userPassword);
// Ensure the rules is enabled
if (rule.Attributes["enabled"].Equals(false))
{
rule.SetAttributeValue("enabled", true);
}
//
srvman.CommitChanges();
}
//
return; // Exit
}
}
// Create new rule if none exists
var newRule = rulesCollection.CreateElement("rule");
newRule.SetAttributeValue("providers", providers);
newRule.SetAttributeValue("actions", "*"); // Any
newRule.SetAttributeValue("path", path);
newRule.SetAttributeValue("pathType", pathType);
newRule.SetAttributeValue("enabled", true);
// Run rule as SpecificUser
if (identityType.Equals("SpecificUser"))
{
var runAs = newRule.GetChildElement("runAs");
//
runAs.SetAttributeValue("identityType", "SpecificUser");
runAs.SetAttributeValue("userName", userName);
runAs.SetAttributeValue("password", userPassword);
}
else // Run rule as CurrentUser
{
var runAs = newRule.GetChildElement("runAs");
//
runAs.SetAttributeValue("identityType", "CurrentUser");
}
// Establish permissions
var permissions = newRule.GetCollection("permissions");
var user = permissions.CreateElement("user");
user.SetAttributeValue("name", "*");
user.SetAttributeValue("accessType", "Allow");
user.SetAttributeValue("isRole", false);
permissions.Add(user);
//
rulesCollection.Add(newRule);
//
srvman.CommitChanges();
}
}
public void RemoveDelegationRule(string providers, string path)
{
var predicate = new Predicate<ConfigurationElement>(x =>
{
return x.Attributes["providers"].Value.Equals(providers) && x.Attributes["path"].Value.Equals(path);
});
//
using (var srvman = GetServerManager())
{
var adminConfig = srvman.GetAdministrationConfiguration();
// return if system.webServer/management/delegation section is not exist in config file
if (!HasDelegationSection(adminConfig))
return;
var delegationSection = adminConfig.GetSection("system.webServer/management/delegation");
//
var rulesCollection = delegationSection.GetCollection();
// Remove rule if exists
foreach (var rule in rulesCollection)
{
// Match rule against predicate
if (predicate.Invoke(rule) == true)
{
rulesCollection.Remove(rule);
//
srvman.CommitChanges();
//
return; // Exit
}
}
}
}
private bool HasDelegationSection(Configuration adminConfig)
{
// try to get delegation section in config file (C:\Windows\system32\inetsrv\config\administration.config)
try
{
adminConfig.GetSection("system.webServer/management/delegation");
}
catch (Exception ex)
{
/* skip */
return false;
}
return true;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using FFmpeg.AutoGen;
using osuTK;
using osu.Framework.Graphics.Textures;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Threading;
using AGffmpeg = FFmpeg.AutoGen.ffmpeg;
namespace osu.Framework.Graphics.Video
{
/// <summary>
/// Represents a video decoder that can be used convert video streams and files into textures.
/// </summary>
public unsafe class VideoDecoder : IDisposable
{
/// <summary>
/// The duration of the video that is being decoded. Can only be queried after the decoder has started decoding has loaded. This value may be an estimate by FFmpeg, depending on the video loaded.
/// </summary>
public double Duration => stream == null ? 0 : duration * timeBaseInSeconds * 1000;
/// <summary>
/// True if the decoder currently does not decode any more frames, false otherwise.
/// </summary>
public bool IsRunning => state == DecoderState.Running;
/// <summary>
/// True if the decoder has faulted after starting to decode. You can try to restart a failed decoder by invoking <see cref="StartDecoding"/> again.
/// </summary>
public bool IsFaulted => state == DecoderState.Faulted;
/// <summary>
/// The timestamp of the last frame that was decoded by this video decoder, or 0 if no frames have been decoded.
/// </summary>
public float LastDecodedFrameTime => lastDecodedFrameTime;
/// <summary>
/// The frame rate of the video stream this decoder is decoding.
/// </summary>
public double FrameRate => stream == null ? 0 : stream->avg_frame_rate.GetValue();
/// <summary>
/// True if the decoder can seek, false otherwise. Determined by the stream this decoder was created with.
/// </summary>
public bool CanSeek => videoStream?.CanSeek == true;
/// <summary>
/// The current state of the <see cref="VideoDecoder"/>, as a bindable.
/// </summary>
public IBindable<DecoderState> State => bindableState;
private readonly Bindable<DecoderState> bindableState = new Bindable<DecoderState>();
private volatile DecoderState volatileState;
private DecoderState state
{
get => volatileState;
set
{
if (volatileState == value) return;
scheduler?.Add(() => bindableState.Value = value);
volatileState = value;
}
}
private readonly Scheduler scheduler;
// libav-context-related
private AVFormatContext* formatContext;
private AVStream* stream;
private AVCodecParameters codecParams;
private byte* contextBuffer;
private byte[] managedContextBuffer;
private avio_alloc_context_read_packet readPacketCallback;
private avio_alloc_context_seek seekCallback;
private bool inputOpened;
private bool isDisposed;
private Stream videoStream;
private double timeBaseInSeconds;
private long duration;
private SwsContext* convCtx;
private bool convert = true;
// active decoder state
private volatile float lastDecodedFrameTime;
private Task decodingTask;
private CancellationTokenSource decodingTaskCancellationTokenSource;
private double? skipOutputUntilTime;
private readonly ConcurrentQueue<DecodedFrame> decodedFrames;
private readonly ConcurrentQueue<Action> decoderCommands;
private readonly ConcurrentQueue<Texture> availableTextures;
private ObjectHandle<VideoDecoder> handle;
private readonly FFmpegFuncs ffmpeg;
internal bool Looping;
/// <summary>
/// Creates a new video decoder that decodes the given video file.
/// </summary>
/// <param name="filename">The path to the file that should be decoded.</param>
/// <param name="scheduler">The <see cref="Scheduler"/> to use when scheduling tasks from the decoder thread.</param>
public VideoDecoder(string filename, Scheduler scheduler)
: this(File.OpenRead(filename), scheduler)
{
}
/// <summary>
/// Creates a new video decoder that decodes the given video stream.
/// </summary>
/// <param name="videoStream">The stream that should be decoded.</param>
/// <param name="scheduler">The <see cref="Scheduler"/> to use when scheduling tasks from the decoder thread.</param>
public VideoDecoder(Stream videoStream, Scheduler scheduler)
{
ffmpeg = CreateFuncs();
this.scheduler = scheduler;
this.videoStream = videoStream;
if (!videoStream.CanRead)
throw new InvalidOperationException($"The given stream does not support reading. A stream used for a {nameof(VideoDecoder)} must support reading.");
state = DecoderState.Ready;
decodedFrames = new ConcurrentQueue<DecodedFrame>();
decoderCommands = new ConcurrentQueue<Action>();
availableTextures = new ConcurrentQueue<Texture>(); // TODO: use "real" object pool when there's some public pool supporting disposables
handle = new ObjectHandle<VideoDecoder>(this, GCHandleType.Normal);
}
/// <summary>
/// Seek the decoder to the given timestamp. This will fail if <see cref="CanSeek"/> is false.
/// </summary>
/// <param name="targetTimestamp">The timestamp to seek to.</param>
public void Seek(double targetTimestamp)
{
if (!CanSeek)
throw new InvalidOperationException("This decoder cannot seek because the underlying stream used to decode the video does not support seeking.");
decoderCommands.Enqueue(() =>
{
ffmpeg.av_seek_frame(formatContext, stream->index, (long)(targetTimestamp / timeBaseInSeconds / 1000.0), AGffmpeg.AVSEEK_FLAG_BACKWARD);
skipOutputUntilTime = targetTimestamp;
});
}
/// <summary>
/// Returns the given frames back to the decoder, allowing the decoder to reuse the textures contained in the frames to draw new frames.
/// </summary>
/// <param name="frames">The frames that should be returned to the decoder.</param>
public void ReturnFrames(IEnumerable<DecodedFrame> frames)
{
foreach (var f in frames)
{
((VideoTexture)f.Texture.TextureGL).FlushUploads();
availableTextures.Enqueue(f.Texture);
}
}
/// <summary>
/// Starts the decoding process. The decoding will happen asynchronously in a separate thread. The decoded frames can be retrieved by using <see cref="GetDecodedFrames"/>.
/// </summary>
public void StartDecoding()
{
// only prepare for decoding if this is our first time starting the decoding process
if (formatContext == null)
{
try
{
prepareDecoding();
}
catch (Exception e)
{
Logger.Log($"VideoDecoder faulted: {e}");
state = DecoderState.Faulted;
return;
}
}
decodingTaskCancellationTokenSource = new CancellationTokenSource();
decodingTask = Task.Factory.StartNew(() => decodingLoop(decodingTaskCancellationTokenSource.Token), decodingTaskCancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
/// <summary>
/// Stops the decoding process. Optionally waits for the decoder thread to terminate.
/// </summary>
/// <param name="waitForDecoderExit">True if this method should wait for the decoder thread to terminate, false otherwise.</param>
public void StopDecoding(bool waitForDecoderExit)
{
if (decodingTask == null)
return;
decodingTaskCancellationTokenSource.Cancel();
if (waitForDecoderExit)
decodingTask.Wait();
decodingTask = null;
decodingTaskCancellationTokenSource.Dispose();
decodingTaskCancellationTokenSource = null;
state = DecoderState.Ready;
}
/// <summary>
/// Gets all frames that have been decoded by the decoder up until the point in time when this method was called.
/// Retrieving decoded frames using this method consumes them, ie calling this method again will never retrieve the same frame twice.
/// </summary>
/// <returns>The frames that have been decoded up until the point in time this method was called.</returns>
public IEnumerable<DecodedFrame> GetDecodedFrames()
{
var frames = new List<DecodedFrame>(decodedFrames.Count);
while (decodedFrames.TryDequeue(out var df))
frames.Add(df);
return frames;
}
// https://en.wikipedia.org/wiki/YCbCr
public Matrix3 GetConversionMatrix()
{
if (stream == null)
return Matrix3.Zero;
switch (stream->codec->colorspace)
{
case AVColorSpace.AVCOL_SPC_BT709:
return new Matrix3(1.164f, 1.164f, 1.164f,
0.000f, -0.213f, 2.112f,
1.793f, -0.533f, 0.000f);
case AVColorSpace.AVCOL_SPC_UNSPECIFIED:
case AVColorSpace.AVCOL_SPC_SMPTE170M:
case AVColorSpace.AVCOL_SPC_SMPTE240M:
default:
return new Matrix3(1.164f, 1.164f, 1.164f,
0.000f, -0.392f, 2.017f,
1.596f, -0.813f, 0.000f);
}
}
[MonoPInvokeCallback(typeof(avio_alloc_context_read_packet))]
private static int readPacket(void* opaque, byte* bufferPtr, int bufferSize)
{
var handle = new ObjectHandle<VideoDecoder>((IntPtr)opaque);
if (!handle.GetTarget(out VideoDecoder decoder))
return 0;
if (bufferSize != decoder.managedContextBuffer.Length)
decoder.managedContextBuffer = new byte[bufferSize];
var bytesRead = decoder.videoStream.Read(decoder.managedContextBuffer, 0, bufferSize);
Marshal.Copy(decoder.managedContextBuffer, 0, (IntPtr)bufferPtr, bytesRead);
return bytesRead;
}
[MonoPInvokeCallback(typeof(avio_alloc_context_seek))]
private static long seek(void* opaque, long offset, int whence)
{
var handle = new ObjectHandle<VideoDecoder>((IntPtr)opaque);
if (!handle.GetTarget(out VideoDecoder decoder))
return -1;
if (!decoder.videoStream.CanSeek)
throw new InvalidOperationException("Tried seeking on a video sourced by a non-seekable stream.");
switch (whence)
{
case StdIo.SEEK_CUR:
decoder.videoStream.Seek(offset, SeekOrigin.Current);
break;
case StdIo.SEEK_END:
decoder.videoStream.Seek(offset, SeekOrigin.End);
break;
case StdIo.SEEK_SET:
decoder.videoStream.Seek(offset, SeekOrigin.Begin);
break;
case AGffmpeg.AVSEEK_SIZE:
return decoder.videoStream.Length;
default:
return -1;
}
return decoder.videoStream.Position;
}
private void prepareFilters()
{
// only convert if needed
if (stream->codec->pix_fmt == AVPixelFormat.AV_PIX_FMT_YUV420P)
{
convert = false;
return;
}
// 1 = SWS_FAST_BILINEAR
// https://www.ffmpeg.org/doxygen/3.1/swscale_8h_source.html#l00056
convCtx = ffmpeg.sws_getContext(stream->codec->width, stream->codec->height, stream->codec->pix_fmt, stream->codec->width, stream->codec->height,
AVPixelFormat.AV_PIX_FMT_YUV420P, 1, null, null, null);
}
// sets up libavformat state: creates the AVFormatContext, the frames, etc. to start decoding, but does not actually start the decodingLoop
private void prepareDecoding()
{
const int context_buffer_size = 4096;
// the first call to FFmpeg will throw an exception if the libraries cannot be found
// this will be safely handled in StartDecoding()
var fcPtr = ffmpeg.avformat_alloc_context();
formatContext = fcPtr;
contextBuffer = (byte*)ffmpeg.av_malloc(context_buffer_size);
managedContextBuffer = new byte[context_buffer_size];
readPacketCallback = readPacket;
seekCallback = seek;
formatContext->pb = ffmpeg.avio_alloc_context(contextBuffer, context_buffer_size, 0, (void*)handle.Handle, readPacketCallback, null, seekCallback);
int openInputResult = ffmpeg.avformat_open_input(&fcPtr, "dummy", null, null);
inputOpened = openInputResult >= 0;
if (!inputOpened)
throw new InvalidOperationException($"Error opening file or stream: {getErrorMessage(openInputResult)}");
int findStreamInfoResult = ffmpeg.avformat_find_stream_info(formatContext, null);
if (findStreamInfoResult < 0)
throw new InvalidOperationException($"Error finding stream info: {getErrorMessage(findStreamInfoResult)}");
var nStreams = formatContext->nb_streams;
for (var i = 0; i < nStreams; ++i)
{
stream = formatContext->streams[i];
codecParams = *stream->codecpar;
if (codecParams.codec_type == AVMediaType.AVMEDIA_TYPE_VIDEO)
{
duration = stream->duration <= 0 ? formatContext->duration : stream->duration;
timeBaseInSeconds = stream->time_base.GetValue();
var codecPtr = ffmpeg.avcodec_find_decoder(codecParams.codec_id);
if (codecPtr == null)
throw new InvalidOperationException($"Couldn't find codec with id: {codecParams.codec_id}");
int openCodecResult = ffmpeg.avcodec_open2(stream->codec, codecPtr, null);
if (openCodecResult < 0)
throw new InvalidOperationException($"Error trying to open codec with id {codecParams.codec_id}: {getErrorMessage(openCodecResult)}");
break;
}
}
prepareFilters();
}
private void decodingLoop(CancellationToken cancellationToken)
{
var packet = ffmpeg.av_packet_alloc();
const int max_pending_frames = 3;
try
{
while (true)
{
if (cancellationToken.IsCancellationRequested)
return;
if (decodedFrames.Count < max_pending_frames)
{
int readFrameResult = ffmpeg.av_read_frame(formatContext, packet);
if (readFrameResult >= 0)
{
state = DecoderState.Running;
if (packet->stream_index == stream->index)
{
int sendPacketResult = ffmpeg.avcodec_send_packet(stream->codec, packet);
if (sendPacketResult == 0)
{
AVFrame* frame = ffmpeg.av_frame_alloc();
var result = ffmpeg.avcodec_receive_frame(stream->codec, frame);
if (result == 0)
{
var frameTime = (frame->best_effort_timestamp - stream->start_time) * timeBaseInSeconds * 1000;
if (!skipOutputUntilTime.HasValue || skipOutputUntilTime.Value < frameTime)
{
skipOutputUntilTime = null;
AVFrame* outFrame;
if (convert)
{
outFrame = ffmpeg.av_frame_alloc();
outFrame->format = (int)AVPixelFormat.AV_PIX_FMT_YUV420P;
outFrame->width = stream->codec->width;
outFrame->height = stream->codec->height;
var ret = ffmpeg.av_frame_get_buffer(outFrame, 32);
if (ret < 0)
throw new InvalidOperationException($"Error allocating video frame: {getErrorMessage(ret)}");
ffmpeg.sws_scale(convCtx, frame->data, frame->linesize, 0, stream->codec->height,
outFrame->data, outFrame->linesize);
ffmpeg.av_frame_free(&frame);
}
else
outFrame = frame;
if (!availableTextures.TryDequeue(out var tex))
tex = new Texture(new VideoTexture(codecParams.width, codecParams.height));
var upload = new VideoTextureUpload(outFrame, ffmpeg.av_frame_free);
tex.SetData(upload);
decodedFrames.Enqueue(new DecodedFrame { Time = frameTime, Texture = tex });
}
lastDecodedFrameTime = (float)frameTime;
}
}
else
Logger.Log($"Error {sendPacketResult} sending packet in VideoDecoder");
}
ffmpeg.av_packet_unref(packet);
}
else if (readFrameResult == AGffmpeg.AVERROR_EOF)
{
if (Looping)
Seek(0);
else
state = DecoderState.EndOfStream;
}
else
{
state = DecoderState.Ready;
Thread.Sleep(1);
}
}
else
{
// wait until existing buffers are consumed.
state = DecoderState.Ready;
Thread.Sleep(1);
}
while (!decoderCommands.IsEmpty)
{
if (cancellationToken.IsCancellationRequested)
return;
if (decoderCommands.TryDequeue(out var cmd))
cmd();
}
}
}
catch (Exception e)
{
Logger.Log($"VideoDecoder faulted: {e}");
state = DecoderState.Faulted;
}
finally
{
ffmpeg.av_packet_free(&packet);
if (state != DecoderState.Faulted)
state = DecoderState.Stopped;
}
}
private string getErrorMessage(int errorCode)
{
const ulong buffer_size = 256;
byte[] buffer = new byte[buffer_size];
int strErrorCode;
fixed (byte* bufPtr = buffer)
{
strErrorCode = ffmpeg.av_strerror(errorCode, bufPtr, buffer_size);
}
if (strErrorCode < 0)
return $"{errorCode} (av_strerror failed with code {strErrorCode})";
var messageLength = Math.Max(0, Array.IndexOf(buffer, (byte)0));
return Encoding.ASCII.GetString(buffer[..messageLength]);
}
protected virtual FFmpegFuncs CreateFuncs()
{
// other frameworks should handle native libraries themselves
#if NETCOREAPP
AGffmpeg.GetOrLoadLibrary = name =>
{
int version = AGffmpeg.LibraryVersionMap[name];
string libraryName = null;
// "lib" prefix and extensions are resolved by .net core
switch (RuntimeInfo.OS)
{
case RuntimeInfo.Platform.MacOsx:
libraryName = $"{name}.{version}";
break;
case RuntimeInfo.Platform.Windows:
libraryName = $"{name}-{version}";
break;
case RuntimeInfo.Platform.Linux:
libraryName = name;
break;
}
return NativeLibrary.Load(libraryName, System.Reflection.Assembly.GetEntryAssembly(), DllImportSearchPath.UseDllDirectoryForDependencies | DllImportSearchPath.SafeDirectories);
};
#endif
return new FFmpegFuncs
{
av_frame_alloc = AGffmpeg.av_frame_alloc,
av_frame_free = AGffmpeg.av_frame_free,
av_frame_unref = AGffmpeg.av_frame_unref,
av_frame_get_buffer = AGffmpeg.av_frame_get_buffer,
av_strdup = AGffmpeg.av_strdup,
av_strerror = AGffmpeg.av_strerror,
av_malloc = AGffmpeg.av_malloc,
av_packet_alloc = AGffmpeg.av_packet_alloc,
av_packet_unref = AGffmpeg.av_packet_unref,
av_packet_free = AGffmpeg.av_packet_free,
av_read_frame = AGffmpeg.av_read_frame,
av_seek_frame = AGffmpeg.av_seek_frame,
avcodec_find_decoder = AGffmpeg.avcodec_find_decoder,
avcodec_open2 = AGffmpeg.avcodec_open2,
avcodec_receive_frame = AGffmpeg.avcodec_receive_frame,
avcodec_send_packet = AGffmpeg.avcodec_send_packet,
avformat_alloc_context = AGffmpeg.avformat_alloc_context,
avformat_close_input = AGffmpeg.avformat_close_input,
avformat_find_stream_info = AGffmpeg.avformat_find_stream_info,
avformat_open_input = AGffmpeg.avformat_open_input,
avio_alloc_context = AGffmpeg.avio_alloc_context,
sws_freeContext = AGffmpeg.sws_freeContext,
sws_getContext = AGffmpeg.sws_getContext,
sws_scale = AGffmpeg.sws_scale
};
}
#region Disposal
~VideoDecoder()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (isDisposed)
return;
isDisposed = true;
decoderCommands.Clear();
StopDecoding(true);
if (formatContext != null && inputOpened)
{
fixed (AVFormatContext** ptr = &formatContext)
ffmpeg.avformat_close_input(ptr);
}
seekCallback = null;
readPacketCallback = null;
managedContextBuffer = null;
videoStream.Dispose();
videoStream = null;
// gets freed by libavformat when closing the input
contextBuffer = null;
if (convCtx != null)
ffmpeg.sws_freeContext(convCtx);
while (decodedFrames.TryDequeue(out var f))
f.Texture.Dispose();
while (availableTextures.TryDequeue(out var t))
t.Dispose();
handle.Dispose();
}
#endregion
/// <summary>
/// Represents the possible states the decoder can be in.
/// </summary>
public enum DecoderState
{
/// <summary>
/// The decoder is ready to begin decoding. This is the default state before the decoder starts operations.
/// </summary>
Ready = 0,
/// <summary>
/// The decoder is currently running and decoding frames.
/// </summary>
Running = 1,
/// <summary>
/// The decoder has faulted with an exception.
/// </summary>
Faulted = 2,
/// <summary>
/// The decoder has reached the end of the video data.
/// </summary>
EndOfStream = 3,
/// <summary>
/// The decoder has been completely stopped and cannot be resumed.
/// </summary>
Stopped = 4,
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System {
using System;
using System.Threading;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
// DateTimeOffset is a value type that consists of a DateTime and a time zone offset,
// ie. how far away the time is from GMT. The DateTime is stored whole, and the offset
// is stored as an Int16 internally to save space, but presented as a TimeSpan.
//
// The range is constrained so that both the represented clock time and the represented
// UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime
// for actual UTC times, and a slightly constrained range on one end when an offset is
// present.
//
// This class should be substitutable for date time in most cases; so most operations
// effectively work on the clock time. However, the underlying UTC time is what counts
// for the purposes of identity, sorting and subtracting two instances.
//
//
// There are theoretically two date times stored, the UTC and the relative local representation
// or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable
// for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this
// out and for internal readability.
[StructLayout(LayoutKind.Auto)]
[Serializable]
public struct DateTimeOffset : IComparable, IFormattable, ISerializable, IDeserializationCallback,
IComparable<DateTimeOffset>, IEquatable<DateTimeOffset> {
// Constants
internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14;
internal const Int64 MinOffset = -MaxOffset;
private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000
private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800
private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000
// Static Fields
public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero);
public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero);
// Instance Fields
private DateTime m_dateTime;
private Int16 m_offsetMinutes;
// Constructors
// Constructs a DateTimeOffset from a tick count and offset
public DateTimeOffset(long ticks, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
// Let the DateTime constructor do the range checks
DateTime dateTime = new DateTime(ticks);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds,
// extracts the local offset. For UTC, creates a UTC instance with a zero offset.
public DateTimeOffset(DateTime dateTime) {
TimeSpan offset;
//if (dateTime.Kind != DateTimeKind.Utc) {
// // Local and Unspecified are both treated as Local
// offset = DateTime.Now - DateTime.UtcNow;
// // TODO: Revised [TimeZoneInfo not supported]
// //offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
//}
//else {
offset = new TimeSpan(0);
//}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time
// consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that
// the offset corresponds to the local.
public DateTimeOffset(DateTime dateTime, TimeSpan offset) {
//if (dateTime.Kind == DateTimeKind.Local) {
// // TODO: Revised [TimeZoneInfo not supported]
// //if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) {
// if (offset != (DateTime.Now - DateTime.UtcNow)) {
// throw new ArgumentException(Environment.GetResourceString("Argument_OffsetLocalMismatch"), "offset");
// }
//}
//else if (dateTime.Kind == DateTimeKind.Utc) {
// if (offset != TimeSpan.Zero) {
// throw new ArgumentException(Environment.GetResourceString("Argument_OffsetUtcMismatch"), "offset");
// }
//}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond and offset
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond, Calendar and offset.
// TODO: NotSupported [DateTime constructor with Calendar parameter not supported]
//public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) {
// m_offsetMinutes = ValidateOffset(offset);
// m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset);
//}
// Returns a DateTimeOffset representing the current date and time. The
// resolution of the returned value depends on the system timer. For
// Windows NT 3.5 and later the timer resolution is approximately 10ms,
// for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98
// it is approximately 55ms.
//
public static DateTimeOffset Now {
get {
return new DateTimeOffset(DateTime.Now);
}
}
public static DateTimeOffset UtcNow {
get {
return new DateTimeOffset(DateTime.UtcNow);
}
}
public DateTime DateTime {
get {
return ClockDateTime;
}
}
public DateTime UtcDateTime {
[Pure]
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc);
}
}
public DateTime LocalDateTime {
[Pure]
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
return UtcDateTime.ToLocalTime();
}
}
// Adjust to a given offset with the same UTC time. Can throw ArgumentException
//
public DateTimeOffset ToOffset(TimeSpan offset) {
return new DateTimeOffset((m_dateTime + offset).Ticks, offset);
}
// Instance Properties
// The clock or visible time represented. This is just a wrapper around the internal date because this is
// the chosen storage mechanism. Going through this helper is good for readability and maintainability.
// This should be used for display but not identity.
private DateTime ClockDateTime {
get {
return new DateTime((m_dateTime + Offset).Ticks, DateTimeKind.Unspecified);
}
}
// Returns the date part of this DateTimeOffset. The resulting value
// corresponds to this DateTimeOffset with the time-of-day part set to
// zero (midnight).
//
public DateTime Date {
get {
return ClockDateTime.Date;
}
}
// Returns the day-of-month part of this DateTimeOffset. The returned
// value is an integer between 1 and 31.
//
public int Day {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 31);
return ClockDateTime.Day;
}
}
// Returns the day-of-week part of this DateTimeOffset. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public DayOfWeek DayOfWeek {
get {
Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
return ClockDateTime.DayOfWeek;
}
}
// Returns the day-of-year part of this DateTimeOffset. The returned value
// is an integer between 1 and 366.
//
public int DayOfYear {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 366); // leap year
return ClockDateTime.DayOfYear;
}
}
// Returns the hour part of this DateTimeOffset. The returned value is an
// integer between 0 and 23.
//
public int Hour {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 24);
return ClockDateTime.Hour;
}
}
// Returns the millisecond part of this DateTimeOffset. The returned value
// is an integer between 0 and 999.
//
public int Millisecond {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 1000);
return ClockDateTime.Millisecond;
}
}
// Returns the minute part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Minute {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
return ClockDateTime.Minute;
}
}
// Returns the month part of this DateTimeOffset. The returned value is an
// integer between 1 and 12.
//
public int Month {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
return ClockDateTime.Month;
}
}
public TimeSpan Offset {
get {
return new TimeSpan(0, m_offsetMinutes, 0);
}
}
// Returns the second part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Second {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
return ClockDateTime.Second;
}
}
// Returns the tick count for this DateTimeOffset. The returned value is
// the number of 100-nanosecond intervals that have elapsed since 1/1/0001
// 12:00am.
//
public long Ticks {
get {
return ClockDateTime.Ticks;
}
}
public long UtcTicks {
get {
return UtcDateTime.Ticks;
}
}
// Returns the time-of-day part of this DateTimeOffset. The returned value
// is a TimeSpan that indicates the time elapsed since midnight.
//
public TimeSpan TimeOfDay {
get {
return ClockDateTime.TimeOfDay;
}
}
// Returns the year part of this DateTimeOffset. The returned value is an
// integer between 1 and 9999.
//
public int Year {
get {
Contract.Ensures(Contract.Result<int>() >= 1 && Contract.Result<int>() <= 9999);
return ClockDateTime.Year;
}
}
// Returns the DateTimeOffset resulting from adding the given
// TimeSpan to this DateTimeOffset.
//
public DateTimeOffset Add(TimeSpan timeSpan) {
return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// days to this DateTimeOffset. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddDays(double days) {
return new DateTimeOffset(ClockDateTime.AddDays(days), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// hours to this DateTimeOffset. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddHours(double hours) {
return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset);
}
// Returns the DateTimeOffset resulting from the given number of
// milliseconds to this DateTimeOffset. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to this DateTimeOffset. The value
// argument is permitted to be negative.
//
public DateTimeOffset AddMilliseconds(double milliseconds) {
return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// minutes to this DateTimeOffset. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddMinutes(double minutes) {
return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset);
}
public DateTimeOffset AddMonths(int months) {
return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// seconds to this DateTimeOffset. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddSeconds(double seconds) {
return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// 100-nanosecond ticks to this DateTimeOffset. The value argument
// is permitted to be negative.
//
public DateTimeOffset AddTicks(long ticks) {
return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// years to this DateTimeOffset. The result is computed by incrementing
// (or decrementing) the year part of this DateTimeOffset by value
// years. If the month and day of this DateTimeOffset is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of this DateTimeOffset.
//
public DateTimeOffset AddYears(int years) {
return new DateTimeOffset(ClockDateTime.AddYears(years), Offset);
}
// Compares two DateTimeOffset values, returning an integer that indicates
// their relationship.
//
public static int Compare(DateTimeOffset first, DateTimeOffset second) {
return DateTime.Compare(first.UtcDateTime, second.UtcDateTime);
}
// Compares this DateTimeOffset to a given object. This method provides an
// implementation of the IComparable interface. The object
// argument must be another DateTimeOffset, or otherwise an exception
// occurs. Null is considered less than any instance.
//
int IComparable.CompareTo(Object obj) {
if (obj == null) return 1;
if (!(obj is DateTimeOffset)) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTimeOffset"));
}
DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > objUtc) return 1;
if (utc < objUtc) return -1;
return 0;
}
public int CompareTo(DateTimeOffset other) {
DateTime otherUtc = other.UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > otherUtc) return 1;
if (utc < otherUtc) return -1;
return 0;
}
// Checks if this DateTimeOffset is equal to a given object. Returns
// true if the given object is a boxed DateTimeOffset and its value
// is equal to the value of this DateTimeOffset. Returns false
// otherwise.
//
[Bridge.Convention(Notation = Bridge.Notation.CamelCase)]
public override bool Equals(Object obj) {
if (obj is DateTimeOffset) {
return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime);
}
return false;
}
public bool Equals(DateTimeOffset other) {
return UtcDateTime.Equals(other.UtcDateTime);
}
public bool EqualsExact(DateTimeOffset other) {
//
// returns true when the ClockDateTime, Kind, and Offset match
//
// currently the Kind should always be Unspecified, but there is always the possibility that a future version
// of DateTimeOffset overloads the Kind field
//
return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind);
}
// Compares two DateTimeOffset values for equality. Returns true if
// the two DateTimeOffset values are equal, or false if they are
// not equal.
//
public static bool Equals(DateTimeOffset first, DateTimeOffset second) {
return DateTime.Equals(first.UtcDateTime, second.UtcDateTime);
}
// Creates a DateTimeOffset from a Windows filetime. A Windows filetime is
// a long representing the date and time as the number of
// 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
//
public static DateTimeOffset FromFileTime(long fileTime)
{
return new DateTimeOffset(DateTime.FromFileTime(fileTime));
}
public static DateTimeOffset FromUnixTimeSeconds(long seconds) {
const long MinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
const long MaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
if (seconds < MinSeconds || seconds > MaxSeconds) {
throw new ArgumentOutOfRangeException("seconds",
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinSeconds, MaxSeconds));
}
long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) {
const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) {
throw new ArgumentOutOfRangeException("milliseconds",
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinMilliseconds, MaxMilliseconds));
}
long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
// ----- SECTION: private serialization instance methods ----------------*
void IDeserializationCallback.OnDeserialization(Object sender) {
try {
m_offsetMinutes = ValidateOffset(Offset);
m_dateTime = ValidateDate(ClockDateTime, Offset);
}
catch (ArgumentException e) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
}
}
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
info.AddValue("DateTime", m_dateTime);
info.AddValue("OffsetMinutes", m_offsetMinutes);
}
DateTimeOffset(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException("info");
}
m_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime));
m_offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16));
}
#endif
// Returns the hash code for this DateTimeOffset.
//
[Bridge.Convention(Notation = Bridge.Notation.CamelCase)]
public override int GetHashCode() {
return UtcDateTime.GetHashCode();
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input) {
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) {
return Parse(input, formatProvider, DateTimeStyles.None);
}
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) {
throw NotImplemented.ByDesign;
// TODO: NotSupported [DateTimeFormatInfo]
//styles = ValidateStyles(styles, "styles");
//TimeSpan offset;
//DateTime dateResult = DateTimeParse.Parse(input,
// DateTimeFormatInfo.GetInstance(formatProvider),
// styles,
// out offset);
//return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) {
return ParseExact(input, format, formatProvider, DateTimeStyles.None);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) {
throw NotImplemented.ByDesign;
//TODO: NotSupported [DateTimeFormatInfo]
//styles = ValidateStyles(styles, "styles");
//TimeSpan offset;
//DateTime dateResult = DateTimeParse.ParseExact(input,
// format,
// DateTimeFormatInfo.GetInstance(formatProvider),
// styles,
// out offset);
//return new DateTimeOffset(dateResult.Ticks, offset);
}
// TODO: NotSupported [DateTimeFormatInfo]
//public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) {
// styles = ValidateStyles(styles, "styles");
// TimeSpan offset;
// DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
// formats,
// DateTimeFormatInfo.GetInstance(formatProvider),
// styles,
// out offset);
// return new DateTimeOffset(dateResult.Ticks, offset);
//}
public TimeSpan Subtract(DateTimeOffset value) {
return UtcDateTime.Subtract(value.UtcDateTime);
}
public DateTimeOffset Subtract(TimeSpan value) {
return new DateTimeOffset(ClockDateTime.Subtract(value), Offset);
}
public long ToFileTime()
{
return UtcDateTime.ToFileTime();
}
public long ToUnixTimeSeconds() {
// Truncate sub-second precision before offsetting by the Unix Epoch to avoid
// the last digit being off by one for dates that result in negative Unix times.
//
// For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0
// ticks = 621355967990010000
// ticksFromEpoch = ticks - UnixEpochTicks = -9990000
// secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0
//
// Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division,
// whereas we actually always want to round *down* when converting to Unix time. This happens
// automatically for positive Unix time values. Now the example becomes:
// seconds = ticks / TimeSpan.TicksPerSecond = 62135596799
// secondsFromEpoch = seconds - UnixEpochSeconds = -1
//
// In other words, we want to consistently round toward the time 1/1/0001 00:00:00,
// rather than toward the Unix Epoch (1/1/1970 00:00:00).
long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond;
return seconds - UnixEpochSeconds;
}
public long ToUnixTimeMilliseconds() {
// Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid
// the last digit being off by one for dates that result in negative Unix times
long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond;
return milliseconds - UnixEpochMilliseconds;
}
public DateTimeOffset ToLocalTime() {
return ToLocalTime(false);
}
internal DateTimeOffset ToLocalTime(bool throwOnOverflow)
{
return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow));
}
[Bridge.Convention(Notation = Bridge.Notation.CamelCase)]
public override String ToString()
{
return DateTime.SpecifyKind(ClockDateTime, DateTimeKind.Local).ToString();
// TODO: NotSupported [DateTimeFormatInfo]
//return DateTimeFormat.Format(ClockDateTime, null, null, Offset);
}
public String ToString(String format)
{
return DateTime.SpecifyKind(ClockDateTime, DateTimeKind.Local).ToString(format);
// TODO: NotSupported [DateTimeFormatInfo]
//return DateTimeFormat.Format(ClockDateTime, format, null, Offset);
}
public String ToString(IFormatProvider formatProvider)
{
return DateTime.SpecifyKind(ClockDateTime, DateTimeKind.Local).ToString(null, formatProvider);
// TODO: NotSupported [DateTimeFormatInfo]
//return DateTimeFormat.Format(ClockDateTime, null, formatProvider, Offset);
}
public String ToString(String format, IFormatProvider formatProvider)
{
return DateTime.SpecifyKind(ClockDateTime, DateTimeKind.Local).ToString(format, formatProvider);
// TODO: NotSupported [DateTimeFormatInfo]
//return DateTimeFormat.Format(ClockDateTime, format, formatProvider, Offset);
}
public DateTimeOffset ToUniversalTime() {
return new DateTimeOffset(UtcDateTime);
}
public static Boolean TryParse(String input, out DateTimeOffset result) {
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
// TODO: NotSupported [DateTimeFormatInfo]
//public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) {
// styles = ValidateStyles(styles, "styles");
// TimeSpan offset;
// DateTime dateResult;
// Boolean parsed = DateTimeParse.TryParse(input,
// DateTimeFormatInfo.GetInstance(formatProvider),
// styles,
// out dateResult,
// out offset);
// result = new DateTimeOffset(dateResult.Ticks, offset);
// return parsed;
//}
// TODO: NotSupported [DateTimeFormatInfo]
//public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles,
// out DateTimeOffset result) {
// styles = ValidateStyles(styles, "styles");
// TimeSpan offset;
// DateTime dateResult;
// Boolean parsed = DateTimeParse.TryParseExact(input,
// format,
// DateTimeFormatInfo.GetInstance(formatProvider),
// styles,
// out dateResult,
// out offset);
// result = new DateTimeOffset(dateResult.Ticks, offset);
// return parsed;
//}
// TODO: NotSupported [DateTimeFormatInfo]
//public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles,
// out DateTimeOffset result) {
// styles = ValidateStyles(styles, "styles");
// TimeSpan offset;
// DateTime dateResult;
// Boolean parsed = DateTimeParse.TryParseExactMultiple(input,
// formats,
// DateTimeFormatInfo.GetInstance(formatProvider),
// styles,
// out dateResult,
// out offset);
// result = new DateTimeOffset(dateResult.Ticks, offset);
// return parsed;
//}
// Ensures the TimeSpan is valid to go in a DateTimeOffset.
private static Int16 ValidateOffset(TimeSpan offset) {
Int64 ticks = offset.Ticks;
if (ticks % TimeSpan.TicksPerMinute != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), "offset");
}
if (ticks < MinOffset || ticks > MaxOffset) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_OffsetOutOfRange"));
}
return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute);
}
// Ensures that the time and offset are in range.
private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) {
// The key validation is that both the UTC and clock times fit. The clock time is validated
// by the DateTime constructor.
Contract.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
// This operation cannot overflow because offset should have already been validated to be within
// 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
Int64 utcTicks = dateTime.Ticks - offset.Ticks;
if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_UTCOutOfRange"));
}
// make sure the Kind is set to Unspecified
//
return new DateTime(utcTicks, DateTimeKind.Unspecified);
}
// TODO: NotSupported [DateTimeFormatInfo]
//private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) {
// if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) {
// throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeStyles"), parameterName);
// }
// if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) {
// throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName);
// }
// if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
// throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetInvalidDateTimeStyles"), parameterName);
// }
// Contract.EndContractBlock();
// // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatability with DateTime
// style &= ~DateTimeStyles.RoundtripKind;
// // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse
// style &= ~DateTimeStyles.AssumeLocal;
// return style;
//}
// Operators
public static implicit operator DateTimeOffset (DateTime dateTime) {
return new DateTimeOffset(dateTime);
}
public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset);
}
public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset);
}
public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime - right.UtcDateTime;
}
public static bool operator ==(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime == right.UtcDateTime;
}
public static bool operator !=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime != right.UtcDateTime;
}
public static bool operator <(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime < right.UtcDateTime;
}
public static bool operator <=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime <= right.UtcDateTime;
}
public static bool operator >(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime > right.UtcDateTime;
}
public static bool operator >=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime >= right.UtcDateTime;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(SgtAurora))]
public class SgtAurora_Editor : SgtEditor<SgtAurora>
{
protected override void OnInspector()
{
var updateMaterial = false;
var updateMeshesAndModels = false;
DrawDefault("Color", ref updateMaterial);
DrawDefault("Brightness", ref updateMaterial);
DrawDefault("RenderQueue", ref updateMaterial);
DrawDefault("RenderQueueOffset", ref updateMaterial);
DrawDefault("CameraOffset"); // Updated automatically
Separator();
BeginError(Any(t => t.MainTex == null));
DrawDefault("MainTex", ref updateMaterial);
EndError();
DrawDefault("Seed", ref updateMeshesAndModels);
BeginError(Any(t => t.RadiusMin >= t.RadiusMax));
DrawDefault("RadiusMin", ref updateMaterial);
DrawDefault("RadiusMax", ref updateMaterial);
EndError();
Separator();
BeginError(Any(t => t.PathCount < 1));
DrawDefault("PathCount", ref updateMeshesAndModels);
EndError();
BeginError(Any(t => t.PathDetail < 1));
DrawDefault("PathDetail", ref updateMeshesAndModels);
EndError();
BeginError(Any(t => t.PathLengthMin > t.PathLengthMax));
DrawDefault("PathLengthMin", ref updateMeshesAndModels);
DrawDefault("PathLengthMax", ref updateMeshesAndModels);
EndError();
Separator();
BeginError(Any(t => t.StartMin > t.StartMax));
DrawDefault("StartMin", ref updateMeshesAndModels);
DrawDefault("StartMax", ref updateMeshesAndModels);
EndError();
BeginError(Any(t => t.StartBias < 1.0f));
DrawDefault("StartBias", ref updateMeshesAndModels);
EndError();
DrawDefault("StartTop", ref updateMeshesAndModels);
Separator();
DrawDefault("PointDetail", ref updateMeshesAndModels);
DrawDefault("PointSpiral", ref updateMeshesAndModels);
DrawDefault("PointJitter", ref updateMeshesAndModels);
Separator();
DrawDefault("TrailTile", ref updateMeshesAndModels);
BeginError(Any(t => t.TrailEdgeFade < 1.0f));
DrawDefault("TrailEdgeFade", ref updateMeshesAndModels);
EndError();
DrawDefault("TrailHeights", ref updateMeshesAndModels);
BeginError(Any(t => t.TrailHeightsDetail < 1));
DrawDefault("TrailHeightsDetail", ref updateMeshesAndModels);
EndError();
Separator();
DrawDefault("Colors", ref updateMeshesAndModels);
BeginError(Any(t => t.ColorsDetail < 1));
DrawDefault("ColorsDetail", ref updateMeshesAndModels);
EndError();
DrawDefault("ColorsAlpha", ref updateMeshesAndModels);
DrawDefault("ColorsAlphaBias", ref updateMeshesAndModels);
Separator();
DrawDefault("FadeNear", ref updateMaterial);
if (Any(t => t.FadeNear == true))
{
BeginIndent();
BeginError(Any(t => t.FadeNearTex == null));
DrawDefault("FadeNearTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.FadeNearRadius < 0.0f));
DrawDefault("FadeNearRadius", ref updateMaterial);
EndError();
BeginError(Any(t => t.FadeNearThickness <= 0.0f));
DrawDefault("FadeNearThickness", ref updateMaterial);
EndError();
EndIndent();
}
Separator();
DrawDefault("Anim", ref updateMaterial);
if (Any(t => t.Anim == true))
{
BeginIndent();
DrawDefault("AnimOffset"); // Updated automatically
BeginError(Any(t => t.AnimSpeed == 0.0f));
DrawDefault("AnimSpeed"); // Updated automatically
EndError();
DrawDefault("AnimStrength", ref updateMeshesAndModels);
BeginError(Any(t => t.AnimStrengthDetail < 1));
DrawDefault("AnimStrengthDetail", ref updateMeshesAndModels);
EndError();
DrawDefault("AnimAngle", ref updateMeshesAndModels);
BeginError(Any(t => t.AnimAngleDetail < 1));
DrawDefault("AnimAngleDetail", ref updateMeshesAndModels);
EndError();
EndIndent();
}
if (updateMaterial == true) DirtyEach(t => t.UpdateMaterial ());
if (updateMeshesAndModels == true) DirtyEach(t => t.UpdateMeshesAndModels());
if (Any(t => t.MainTex == null && t.GetComponent<SgtAuroraMainTex>() == null))
{
Separator();
if (Button("Add Main Tex") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtAuroraMainTex>(t.gameObject));
}
}
if (Any(t => t.FadeNear == true && t.FadeNearTex == null && t.GetComponent<SgtAuroraFadeNear>() == null))
{
Separator();
if (Button("Add Fade Near") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtAuroraFadeNear>(t.gameObject));
}
}
}
}
#endif
[ExecuteInEditMode]
[AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Aurora")]
public class SgtAurora : MonoBehaviour
{
[Tooltip("The main texture")]
public Texture MainTex;
[Tooltip("The color tint")]
public Color Color = Color.white;
[Tooltip("The Color.rgb values are multiplied by this")]
public float Brightness = 1.0f;
[Tooltip("The render queue group of the aurora material")]
public SgtRenderQueue RenderQueue = SgtRenderQueue.Transparent;
[Tooltip("The render queue offset of the aurora material")]
public int RenderQueueOffset;
[Tooltip("The distance the aurora mesh is moved toward the rendering camera in world space")]
public float CameraOffset;
[Tooltip("The random seed used when generating the aurora mesh")]
[SgtSeed]
public int Seed;
[Tooltip("The inner radius of the aurora mesh in local space")]
public float RadiusMin = 1.0f;
[Tooltip("The outer radius of the aurora mesh in local space")]
public float RadiusMax = 1.1f;
[Tooltip("The amount of aurora paths")]
public int PathCount = 8;
[Tooltip("The detail of each aurora path")]
public int PathDetail = 100;
[Tooltip("The sharpness of the fading at the start and ends of the aurora paths")]
public float TrailEdgeFade = 1.0f;
[Tooltip("The minimum length of each aurora path")]
[Range(0.0f, 1.0f)]
public float PathLengthMin = 0.1f;
[Tooltip("The maximum length of each aurora path")]
[Range(0.0f, 1.0f)]
public float PathLengthMax = 0.1f;
[Tooltip("The minimum distance between the pole at the aurora path start point")]
[Range(0.0f, 1.0f)]
public float StartMin = 0.1f;
[Tooltip("The maximum distance between the pole at the aurora path start point")]
[Range(0.0f, 1.0f)]
public float StartMax = 0.5f;
[Tooltip("The probability that the aurora path will begin closer to the pole")]
public float StartBias = 1.0f;
[Tooltip("The probability that the aurora path will start on the northern pole")]
[Range(0.0f, 1.0f)]
public float StartTop = 0.5f;
[Tooltip("The amount of waypoints the aurora path will follow based on its length")]
[Range(1, 100)]
public int PointDetail = 10;
[Tooltip("The strength of the aurora waypoint twisting")]
public float PointSpiral = 1.0f;
[Tooltip("The strength of the aurora waypoint random displacement")]
[Range(0.0f, 1.0f)]
public float PointJitter = 1.0f;
[Tooltip("The amount of times the main texture is tiled based on its length")]
public float TrailTile = 10.0f;
[Tooltip("The flatness of the aurora path")]
[Range(0.1f, 1.0f)]
public float TrailHeights = 1.0f;
[Tooltip("The amount of height changes in the aurora path")]
public int TrailHeightsDetail = 10;
[Tooltip("The possible colors given to the top half of the aurora path")]
public Gradient Colors;
[Tooltip("The amount of color changes an aurora path can have based on its length")]
public int ColorsDetail = 10;
[Tooltip("The minimum opacity multiplier of the aurora path colors")]
[Range(0.0f, 1.0f)]
public float ColorsAlpha = 0.5f;
[Tooltip("The amount of alpha changes in the aurora path")]
public float ColorsAlphaBias = 2.0f;
[Tooltip("Should the aurora fade out when the camera gets near?")]
public bool FadeNear;
[Tooltip("The lookup table used to calculate the fading amount based on the distance")]
public Texture FadeNearTex;
[Tooltip("The radius of the fading effect in world space")]
public float FadeNearRadius = 2.0f;
[Tooltip("The thickness of the fading effect in world space")]
public float FadeNearThickness = 2.0f;
[Tooltip("Enabled aurora path animation")]
public bool Anim;
[Tooltip("The current age/offset of the animation")]
public float AnimOffset;
[Tooltip("The speed of the animation")]
public float AnimSpeed = 1.0f;
[Tooltip("The strength of the aurora path position changes in local space")]
public float AnimStrength = 0.01f;
[Tooltip("The amount of the animation strength changes along the aurora path based on its length")]
public int AnimStrengthDetail = 10;
[Tooltip("The maximum angle step between sections of the aurora path")]
public float AnimAngle = 0.01f;
[Tooltip("The amount of the animation angle changes along the aurora path based on its length")]
public int AnimAngleDetail = 10;
// The models used to render this
public List<SgtAuroraModel> Models;
// The material applied to all segments
[System.NonSerialized]
public Material Material;
// The meshes applied to the models
[System.NonSerialized]
public List<Mesh> Meshes;
[SerializeField]
private bool startCalled;
[System.NonSerialized]
private bool updateMaterialCalled;
[System.NonSerialized]
protected bool updateMeshesAndModelsCalled;
private static List<Vector3> positions = new List<Vector3>();
private static List<Vector4> coords0 = new List<Vector4>();
private static List<Color> colors = new List<Color>();
private static List<Vector3> normals = new List<Vector3>();
private static List<int> indices = new List<int>();
public void UpdateMainTex()
{
if (Material != null)
{
Material.SetTexture("_MainTex", MainTex);
}
}
public void UpdateFadeNearTex()
{
if (Material != null)
{
Material.SetTexture("_FadeNearTex", FadeNearTex);
}
}
[ContextMenu("Update Material")]
public void UpdateMaterial()
{
updateMaterialCalled = true;
if (Material == null)
{
Material = SgtHelper.CreateTempMaterial("Aurora (Generated)", SgtHelper.ShaderNamePrefix + "Aurora");
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.SetMaterial(Material);
}
}
}
}
var color = SgtHelper.Premultiply(SgtHelper.Brighten(Color, Brightness));
var renderQueue = (int)RenderQueue + RenderQueueOffset;
if (Material.renderQueue != renderQueue)
{
Material.renderQueue = renderQueue;
}
Material.SetColor("_Color", color);
Material.SetTexture("_MainTex", MainTex);
Material.SetFloat("_RadiusMin", RadiusMin);
Material.SetFloat("_RadiusSize", RadiusMax - RadiusMin);
SgtHelper.SetTempMaterial(Material);
if (FadeNear == true)
{
SgtHelper.EnableKeyword("SGT_A"); // FadeNear
Material.SetTexture("_FadeNearTex", FadeNearTex);
Material.SetFloat("_FadeNearRadius", FadeNearRadius);
Material.SetFloat("_FadeNearScale", SgtHelper.Reciprocal(FadeNearThickness));
}
else
{
SgtHelper.DisableKeyword("SGT_A"); // FadeNear
}
if (Anim == true)
{
SgtHelper.EnableKeyword("SGT_B"); // Anim
Material.SetFloat("_AnimOffset", AnimOffset);
}
else
{
SgtHelper.DisableKeyword("SGT_B"); // Anim
}
}
private void BakeMesh(Mesh mesh)
{
mesh.Clear(false);
mesh.SetVertices(positions);
mesh.SetUVs(0, coords0);
mesh.SetColors(colors);
mesh.SetNormals(normals);
mesh.SetTriangles(indices, 0);
mesh.bounds = new Bounds(Vector3.zero, Vector3.one * RadiusMax * 2.0f);
}
private Mesh GetMesh(int index)
{
SgtHelper.ClearCapacity(positions, 1024);
SgtHelper.ClearCapacity(coords0, 1024);
SgtHelper.ClearCapacity(indices, 1024);
SgtHelper.ClearCapacity(colors, 1024);
SgtHelper.ClearCapacity(normals, 1024);
if (index >= Meshes.Count)
{
var newMesh = SgtHelper.CreateTempMesh("Aurora Mesh (Generated)");
Meshes.Add(newMesh);
return newMesh;
}
var mesh = Meshes[index];
if (mesh == null)
{
mesh = Meshes[index] = SgtHelper.CreateTempMesh("Aurora Mesh (Generated)");
}
return mesh;
}
private Vector3 GetStart(float angle)
{
var distance = Mathf.Lerp(StartMin, StartMax, Mathf.Pow(Random.value, StartBias));
if (Random.value < StartTop)
{
return new Vector3(Mathf.Sin(angle) * distance, 1.0f, Mathf.Cos(angle) * distance);
}
else
{
return new Vector3(Mathf.Sin(angle) * distance, -1.0f, Mathf.Cos(angle) * distance);
}
}
private Vector3 GetNext(Vector3 point, float angle, float speed)
{
var noise = Random.insideUnitCircle;
point.x += Mathf.Sin(angle) * speed;
point.z += Mathf.Cos(angle) * speed;
point.x += noise.x * PointJitter;
point.z += noise.y * PointJitter;
return Quaternion.Euler(0.0f, PointSpiral, 0.0f) * point;
}
private float GetNextAngle(float angle)
{
return angle + Random.Range(0.0f, AnimAngle);
}
private float GetNextStrength()
{
return Random.Range(-AnimStrength, AnimStrength);
}
private Color GetNextColor()
{
var color = Color.white;
if (Colors != null)
{
color = Colors.Evaluate(Random.value);
}
color.a *= Mathf.LerpUnclamped(ColorsAlpha, 1.0f, Mathf.Pow(Random.value, ColorsAlphaBias));
return color;
}
private float GetNextHeight()
{
return Random.Range(0.0f, TrailHeights);
}
private void Shift<T>(ref T a, ref T b, ref T c, T d, ref float f)
{
a = b;
b = c;
c = d;
f -= 1.0f;
}
private void AddPath(ref Mesh mesh, ref int meshCount, ref int vertexCount)
{
var pathLength = Random.Range(PathLengthMin, PathLengthMax);
var lineCount = 2 + (int)(pathLength * PathDetail);
var quadCount = lineCount - 1;
var vertices = quadCount * 2 + 2;
if (vertexCount + vertices > 65000)
{
BakeMesh(mesh);
mesh = GetMesh(meshCount);
meshCount += 1;
vertexCount = 0;
}
var angle = Random.Range(-Mathf.PI, Mathf.PI);
var speed = 1.0f / PointDetail;
var detailStep = 1.0f / PathDetail;
var pointStep = detailStep * PointDetail;
var pointFrac = 0.0f;
var pointA = GetStart(angle + Mathf.PI);
var pointB = GetNext(pointA, angle, speed);
var pointC = GetNext(pointB, angle, speed);
var pointD = GetNext(pointC, angle, speed);
var coordFrac = 0.0f;
var edgeFrac = -1.0f;
var edgeStep = 2.0f / lineCount;
var coordStep = detailStep * TrailTile;
var angleA = angle;
var angleB = GetNextAngle(angleA);
var angleC = GetNextAngle(angleB);
var angleD = GetNextAngle(angleC);
var angleFrac = 0.0f;
var angleStep = detailStep * AnimAngleDetail;
var strengthA = 0.0f;
var strengthB = GetNextStrength();
var strengthC = GetNextStrength();
var strengthD = GetNextStrength();
var strengthFrac = 0.0f;
var strengthStep = detailStep * AnimStrengthDetail;
var colorA = GetNextColor();
var colorB = GetNextColor();
var colorC = GetNextColor();
var colorD = GetNextColor();
var colorFrac = 0.0f;
var colorStep = detailStep * ColorsDetail;
var heightA = GetNextHeight();
var heightB = GetNextHeight();
var heightC = GetNextHeight();
var heightD = GetNextHeight();
var heightFrac = 0.0f;
var heightStep = detailStep * TrailHeightsDetail;
for (var i = 0; i < lineCount; i++)
{
while (pointFrac >= 1.0f)
{
Shift(ref pointA, ref pointB, ref pointC, pointD, ref pointFrac); pointD = GetNext(pointC, angle, speed);
}
while (angleFrac >= 1.0f)
{
Shift(ref angleA, ref angleB, ref angleC, angleD, ref angleFrac); angleD = GetNextAngle(angleC);
}
while (strengthFrac >= 1.0f)
{
Shift(ref strengthA, ref strengthB, ref strengthC, strengthD, ref strengthFrac); strengthD = GetNextStrength();
}
while (colorFrac >= 1.0f)
{
Shift(ref colorA, ref colorB, ref colorC, colorD, ref colorFrac); colorD = GetNextColor();
}
while (heightFrac >= 1.0f)
{
Shift(ref heightA, ref heightB, ref heightC, heightD, ref heightFrac); heightD = GetNextHeight();
}
var point = SgtHelper.HermiteInterpolate3(pointA, pointB, pointC, pointD, pointFrac);
var animAng = SgtHelper.HermiteInterpolate(angleA, angleB, angleC, angleD, angleFrac);
var animStr = SgtHelper.HermiteInterpolate(strengthA, strengthB, strengthC, strengthD, strengthFrac);
var color = SgtHelper.HermiteInterpolate(colorA, colorB, colorC, colorD, colorFrac);
var height = SgtHelper.HermiteInterpolate(heightA, heightB, heightC, heightD, heightFrac);
// Fade edges
color.a *= Mathf.SmoothStep(1.0f, 0.0f, Mathf.Pow(Mathf.Abs(edgeFrac), TrailEdgeFade));
coords0.Add(new Vector4(coordFrac, 0.0f, animAng, animStr));
coords0.Add(new Vector4(coordFrac, height, animAng, animStr));
positions.Add(point);
positions.Add(point);
colors.Add(color);
colors.Add(color);
pointFrac += pointStep;
edgeFrac += edgeStep;
coordFrac += coordStep;
angleFrac += angleStep;
strengthFrac += strengthStep;
colorFrac += colorStep;
heightFrac += heightStep;
}
var vector = positions[1] - positions[0];
normals.Add(GetNormal(vector, vector));
normals.Add(GetNormal(vector, vector));
for (var i = 2; i < lineCount; i++)
{
var nextVector = positions[i] - positions[i - 1];
normals.Add(GetNormal(vector, nextVector));
normals.Add(GetNormal(vector, nextVector));
vector = nextVector;
}
normals.Add(GetNormal(vector, vector));
normals.Add(GetNormal(vector, vector));
for (var i = 0; i < quadCount; i++)
{
var offset = vertexCount + i * 2;
indices.Add(offset + 0);
indices.Add(offset + 1);
indices.Add(offset + 2);
indices.Add(offset + 3);
indices.Add(offset + 2);
indices.Add(offset + 1);
}
vertexCount += vertices;
}
private Vector3 GetNormal(Vector3 a, Vector3 b)
{
return Vector3.Cross(a.normalized, b.normalized);
}
[ContextMenu("Update Meshes And Models")]
public void UpdateMeshesAndModels()
{
updateMeshesAndModelsCalled = true;
if (Meshes == null)
{
Meshes = new List<Mesh>();
}
if (Models == null)
{
Models = new List<SgtAuroraModel>();
}
if (PathDetail > 0 && PathLengthMin > 0.0f && PathLengthMax > 0.0f)
{
var meshCount = 1;
var mesh = GetMesh(0);
var vertexCount = 0;
SgtHelper.BeginRandomSeed(Seed);
{
for (var i = 0; i < PathCount; i++)
{
AddPath(ref mesh, ref meshCount, ref vertexCount);
}
}
SgtHelper.EndRandomSeed();
BakeMesh(mesh);
for (var i = Meshes.Count - 1; i >= meshCount; i--)
{
var extraMesh = Meshes[i];
if (extraMesh != null)
{
extraMesh.Clear(false);
SgtObjectPool<Mesh>.Add(extraMesh);
}
Meshes.RemoveAt(i);
}
}
for (var i = 0; i < Meshes.Count; i++)
{
var model = GetOrAddModel(i);
model.SetMesh(Meshes[i]);
}
// Remove any excess
if (Models != null)
{
var min = Mathf.Max(0, Meshes.Count);
for (var i = Models.Count - 1; i >= min; i--)
{
SgtAuroraModel.Pool(Models[i]);
Models.RemoveAt(i);
}
}
}
public static SgtAurora CreateAurora(int layer = 0, Transform parent = null)
{
return CreateAurora(layer, parent, Vector3.zero, Quaternion.identity, Vector3.one);
}
public static SgtAurora CreateAurora(int layer, Transform parent, Vector3 localPosition, Quaternion localRotation, Vector3 localScale)
{
var gameObject = SgtHelper.CreateGameObject("Aurora", layer, parent, localPosition, localRotation, localScale);
var aurora = gameObject.AddComponent<SgtAurora>();
return aurora;
}
#if UNITY_EDITOR
[MenuItem(SgtHelper.GameObjectMenuPrefix + "Aurora", false, 10)]
public static void CreateAuroraMenuItem()
{
var parent = SgtHelper.GetSelectedParent();
var aurora = CreateAurora(parent != null ? parent.gameObject.layer : 0, parent);
SgtHelper.SelectAndPing(aurora);
}
#endif
#if UNITY_EDITOR
protected virtual void Reset()
{
if (Colors == null)
{
Colors = new Gradient();
Colors.colorKeys = new GradientColorKey[] { new GradientColorKey(Color.blue, 0.0f), new GradientColorKey(Color.magenta, 1.0f) };
}
}
#endif
protected virtual void OnEnable()
{
Camera.onPreCull += CameraPreCull;
Camera.onPreRender += CameraPreRender;
Camera.onPostRender += CameraPostRender;
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var plane = Models[i];
if (plane != null)
{
plane.gameObject.SetActive(true);
}
}
}
if (startCalled == true)
{
CheckUpdateCalls();
}
}
protected virtual void Start()
{
if (startCalled == false)
{
startCalled = true;
CheckUpdateCalls();
}
}
protected virtual void Update()
{
if (Anim == true)
{
if (Application.isPlaying == true)
{
AnimOffset += Time.deltaTime * AnimSpeed;
}
if (Material != null)
{
Material.SetFloat("_AnimOffset", AnimOffset);
}
}
}
protected virtual void OnDisable()
{
Camera.onPreCull -= CameraPreCull;
Camera.onPreRender -= CameraPreRender;
Camera.onPostRender -= CameraPostRender;
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var plane = Models[i];
if (plane != null)
{
plane.gameObject.SetActive(false);
}
}
}
}
protected virtual void OnDestroy()
{
if (Meshes != null)
{
for (var i = Meshes.Count - 1; i >= 0; i--)
{
var mesh = Meshes[i];
if (mesh != null)
{
mesh.Clear(false);
SgtObjectPool<Mesh>.Add(Meshes[i]);
}
}
}
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
SgtAuroraModel.MarkForDestruction(Models[i]);
}
}
SgtHelper.Destroy(Material);
}
#if UNITY_EDITOR
protected virtual void OnDrawGizmosSelected()
{
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireSphere(Vector3.zero, RadiusMin);
Gizmos.DrawWireSphere(Vector3.zero, RadiusMax);
}
#endif
private void CameraPreCull(Camera camera)
{
if (CameraOffset != 0.0f && Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var plane = Models[i];
if (plane != null)
{
plane.Revert();
{
var planeTransform = plane.transform;
var observerDir = (planeTransform.position - camera.transform.position).normalized;
planeTransform.position += observerDir * CameraOffset;
}
plane.Save(camera);
}
}
}
}
private void CameraPreRender(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var plane = Models[i];
if (plane != null)
{
plane.Restore(camera);
}
}
}
}
private void CameraPostRender(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var plane = Models[i];
if (plane != null)
{
plane.Revert();
}
}
}
}
private SgtAuroraModel GetOrAddModel(int index)
{
var model = default(SgtAuroraModel);
if (Models == null)
{
Models = new List<SgtAuroraModel>();
}
if (index < Models.Count)
{
model = Models[index];
}
else
{
Models.Add(model);
}
if (model == null)
{
model = Models[index] = SgtAuroraModel.Create(this);
model.SetMaterial(Material);
}
return model;
}
private void CheckUpdateCalls()
{
if (updateMaterialCalled == false)
{
UpdateMaterial();
}
if (updateMeshesAndModelsCalled == false)
{
UpdateMeshesAndModels();
}
}
}
| |
using UnityEngine;
/// <summary>
/// Functionality common to both NGUI and 2D sprites brought out into a single common parent.
/// Mostly contains everything related to drawing the sprite.
/// </summary>
public abstract class UIBasicSprite : UIWidget
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled,
Advanced,
}
public enum FillDirection
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum AdvancedType
{
Invisible,
Sliced,
Tiled,
}
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
[HideInInspector][SerializeField] protected Type mType = Type.Simple;
[HideInInspector][SerializeField] protected FillDirection mFillDirection = FillDirection.Radial360;
[Range(0f, 1f)]
[HideInInspector][SerializeField] protected float mFillAmount = 1.0f;
[HideInInspector][SerializeField] protected bool mInvert = false;
[HideInInspector][SerializeField] protected Flip mFlip = Flip.Nothing;
// Cached to avoid allocations
[System.NonSerialized] Rect mInnerUV = new Rect();
[System.NonSerialized] Rect mOuterUV = new Rect();
/// <summary>
/// When the sprite type is advanced, this determines whether the center is tiled or sliced.
/// </summary>
public AdvancedType centerType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the left edge is tiled or sliced.
/// </summary>
public AdvancedType leftType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the right edge is tiled or sliced.
/// </summary>
public AdvancedType rightType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the bottom edge is tiled or sliced.
/// </summary>
public AdvancedType bottomType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the top edge is tiled or sliced.
/// </summary>
public AdvancedType topType = AdvancedType.Sliced;
/// <summary>
/// How the sprite is drawn. It's virtual for legacy reasons (UISlicedSprite, UITiledSprite, UIFilledSprite).
/// </summary>
public virtual Type type
{
get
{
return mType;
}
set
{
if (mType != value)
{
mType = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite flip setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Direction of the cut procedure.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFillDirection;
}
set
{
if (mFillDirection != value)
{
mFillDirection = value;
mChanged = true;
}
}
}
/// <summary>
/// Amount of the sprite shown. 0-1 range with 0 being nothing shown, and 1 being the full sprite.
/// </summary>
public float fillAmount
{
get
{
return mFillAmount;
}
set
{
float val = Mathf.Clamp01(value);
if (mFillAmount != val)
{
mFillAmount = val;
mChanged = true;
}
}
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
override public int minWidth
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.x + b.z);
return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min);
}
return base.minWidth;
}
}
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
override public int minHeight
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.y + b.w);
return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min);
}
return base.minHeight;
}
}
/// <summary>
/// Whether the sprite should be filled in the opposite direction.
/// </summary>
public bool invert
{
get
{
return mInvert;
}
set
{
if (mInvert != value)
{
mInvert = value;
mChanged = true;
}
}
}
/// <summary>
/// Whether the widget has a border for 9-slicing.
/// </summary>
public bool hasBorder
{
get
{
Vector4 br = border;
return (br.x != 0f || br.y != 0f || br.z != 0f || br.w != 0f);
}
}
/// <summary>
/// Whether the sprite's material is using a pre-multiplied alpha shader.
/// </summary>
public virtual bool premultipliedAlpha { get { return false; } }
/// <summary>
/// Size of the pixel. Overwritten in the NGUI sprite to pull a value from the atlas.
/// </summary>
public virtual float pixelSize { get { return 1f; } }
#if UNITY_EDITOR
/// <summary>
/// Keep sane values.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
mFillAmount = Mathf.Clamp01(mFillAmount);
}
#endif
#region Fill Functions
// Static variables to reduce garbage collection
static protected Vector2[] mTempPos = new Vector2[4];
static protected Vector2[] mTempUVs = new Vector2[4];
/// <summary>
/// Convenience function that returns the drawn UVs after flipping gets considered.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
Vector4 drawingUVs
{
get
{
switch (mFlip)
{
case Flip.Horizontally: return new Vector4(mOuterUV.xMax, mOuterUV.yMin, mOuterUV.xMin, mOuterUV.yMax);
case Flip.Vertically: return new Vector4(mOuterUV.xMin, mOuterUV.yMax, mOuterUV.xMax, mOuterUV.yMin);
case Flip.Both: return new Vector4(mOuterUV.xMax, mOuterUV.yMax, mOuterUV.xMin, mOuterUV.yMin);
default: return new Vector4(mOuterUV.xMin, mOuterUV.yMin, mOuterUV.xMax, mOuterUV.yMax);
}
}
}
/// <summary>
/// Final widget's color passed to the draw buffer.
/// </summary>
Color32 drawingColor
{
get
{
Color colF = color;
colF.a = finalAlpha;
if (premultipliedAlpha) colF = NGUITools.ApplyPMA(colF);
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
colF.r = Mathf.Pow(colF.r, 2.2f);
colF.g = Mathf.Pow(colF.g, 2.2f);
colF.b = Mathf.Pow(colF.b, 2.2f);
}
return colF;
}
}
/// <summary>
/// Fill the draw buffers.
/// </summary>
protected void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Rect outer, Rect inner)
{
mOuterUV = outer;
mInnerUV = inner;
switch (type)
{
case Type.Simple:
SimpleFill(verts, uvs, cols);
break;
case Type.Sliced:
SlicedFill(verts, uvs, cols);
break;
case Type.Filled:
FilledFill(verts, uvs, cols);
break;
case Type.Tiled:
TiledFill(verts, uvs, cols);
break;
case Type.Advanced:
AdvancedFill(verts, uvs, cols);
break;
}
}
/// <summary>
/// Regular sprite fill function is quite simple.
/// </summary>
void SimpleFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(u.x, u.y));
uvs.Add(new Vector2(u.x, u.w));
uvs.Add(new Vector2(u.z, u.w));
uvs.Add(new Vector2(u.z, u.y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
/// <summary>
/// Sliced sprite fill function is more complicated as it generates 9 quads instead of 1.
/// </summary>
void SlicedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y].y));
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
}
}
/// <summary>
/// Tiled sprite fill function.
/// </summary>
void TiledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= pixelSize;
if (tex == null || size.x < 2f || size.y < 2f) return;
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector4 u;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
u.x = mInnerUV.xMax;
u.z = mInnerUV.xMin;
}
else
{
u.x = mInnerUV.xMin;
u.z = mInnerUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
u.y = mInnerUV.yMax;
u.w = mInnerUV.yMin;
}
else
{
u.y = mInnerUV.yMin;
u.w = mInnerUV.yMax;
}
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
verts.Add(new Vector3(x0, y0));
verts.Add(new Vector3(x0, y1));
verts.Add(new Vector3(x1, y1));
verts.Add(new Vector3(x1, y0));
uvs.Add(new Vector2(u0, v0));
uvs.Add(new Vector2(u0, v1));
uvs.Add(new Vector2(u1, v1));
uvs.Add(new Vector2(u1, v0));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
x0 += size.x;
}
y0 += size.y;
}
}
/// <summary>
/// Filled sprite fill function.
/// </summary>
void FilledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (mFillAmount < 0.001f) return;
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
// Horizontal and vertical filled sprites are simple -- just end the sprite prematurely
if (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical)
{
if (mFillDirection == FillDirection.Horizontal)
{
float fill = (u.z - u.x) * mFillAmount;
if (mInvert)
{
v.x = v.z - (v.z - v.x) * mFillAmount;
u.x = u.z - fill;
}
else
{
v.z = v.x + (v.z - v.x) * mFillAmount;
u.z = u.x + fill;
}
}
else if (mFillDirection == FillDirection.Vertical)
{
float fill = (u.w - u.y) * mFillAmount;
if (mInvert)
{
v.y = v.w - (v.w - v.y) * mFillAmount;
u.y = u.w - fill;
}
else
{
v.w = v.y + (v.w - v.y) * mFillAmount;
u.w = u.y + fill;
}
}
}
mTempPos[0] = new Vector2(v.x, v.y);
mTempPos[1] = new Vector2(v.x, v.w);
mTempPos[2] = new Vector2(v.z, v.w);
mTempPos[3] = new Vector2(v.z, v.y);
mTempUVs[0] = new Vector2(u.x, u.y);
mTempUVs[1] = new Vector2(u.x, u.w);
mTempUVs[2] = new Vector2(u.z, u.w);
mTempUVs[3] = new Vector2(u.z, u.y);
if (mFillAmount < 1f)
{
if (mFillDirection == FillDirection.Radial90)
{
if (RadialCut(mTempPos, mTempUVs, mFillAmount, mInvert, 0))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
return;
}
if (mFillDirection == FillDirection.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
fy0 = 0f;
fy1 = 1f;
if (side == 0) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = !mInvert ? fillAmount * 2f - side : mFillAmount * 2f - (1 - side);
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), !mInvert, NGUIMath.RepeatIndex(side + 3, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
if (mFillDirection == FillDirection.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = mInvert ?
mFillAmount * 4f - NGUIMath.RepeatIndex(corner + 2, 4) :
mFillAmount * 4f - (3 - NGUIMath.RepeatIndex(corner + 2, 4));
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), mInvert, NGUIMath.RepeatIndex(corner + 2, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
}
// Fill the buffer with the quad for the sprite
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
/// <summary>
/// Advanced sprite fill function. Contributed by Nicki Hansen.
/// </summary>
void AdvancedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector2 tileSize = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
tileSize *= pixelSize;
if (tileSize.x < 1f) tileSize.x = 1f;
if (tileSize.y < 1f) tileSize.y = 1f;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
if (x == 1 && y == 1) // Center
{
if (centerType == AdvancedType.Tiled)
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float tileStartX = startPositionX;
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
tileStartY += tileSize.y;
}
}
else if (centerType == AdvancedType.Sliced)
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (x == 1) // Top or bottom
{
if ((y == 0 && bottomType == AdvancedType.Tiled) || (y == 2 && topType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float textureEndY = mTempUVs[y2].y;
float tileStartX = startPositionX;
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
startPositionY, endPositionY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
}
else if ((y == 0 && bottomType != AdvancedType.Invisible) || (y == 2 && topType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (y == 1) // Left or right
{
if ((x == 0 && leftType == AdvancedType.Tiled) || (x == 2 && rightType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureEndX = mTempUVs[x2].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
Fill(verts, uvs, cols,
startPositionX, endPositionX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartY += tileSize.y;
}
}
else if ((x == 0 && leftType != AdvancedType.Invisible) || (x == 2 && rightType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else // Corner
{
if ((y == 0 && bottomType != AdvancedType.Invisible) || (y == 2 && topType != AdvancedType.Invisible) ||
(x == 0 && leftType != AdvancedType.Invisible) || (x == 2 && rightType != AdvancedType.Invisible))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
}
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut (Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut (Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = NGUIMath.RepeatIndex(corner + 1, 4);
int i2 = NGUIMath.RepeatIndex(corner + 2, 4);
int i3 = NGUIMath.RepeatIndex(corner + 3, 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
/// <summary>
/// Helper function that adds the specified values to the buffers.
/// </summary>
static void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols,
float v0x, float v1x, float v0y, float v1y, float u0x, float u1x, float u0y, float u1y, Color col)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
#endregion // Fill functions
}
| |
// 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\Arm\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LoadVector128_Int32()
{
var test = new LoadUnaryOpTest__LoadVector128_Int32();
if (test.IsSupported)
{
// Validates basic functionality works
test.RunBasicScenario_Load();
// Validates calling via reflection works
test.RunReflectionScenario_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 LoadUnaryOpTest__LoadVector128_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private DataTable _dataTable;
public LoadUnaryOpTest__LoadVector128_Int32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LoadVector128(
(Int32*)(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector128), new Type[] { typeof(Int32*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArray1Ptr, typeof(Int32*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_Load();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (firstOp[0] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (firstOp[i] != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector128)}<Int32>(Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
#if !SILVERLIGHT
#if !CLR2
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Language;
//using Microsoft.Scripting.Utils;
using System.Dynamic;
using System.Linq;
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Dynamic")]
namespace System.Management.Automation.ComInterop
{
/// <summary>
/// Provides helper methods to bind COM objects dynamically.
/// </summary>
internal static class ComBinder
{
/// <summary>
/// Determines if an object is a COM object.
/// </summary>
/// <param name="value">The object to test.</param>
/// <returns>true if the object is a COM object, false otherwise.</returns>
public static bool IsComObject(object value)
{
return
(value != null) &&
(!WinRTHelper.IsWinRTType(value.GetType())) &&
ComObject.IsComObject(value);
}
public static bool CanComBind(object value)
{
return IsComObject(value) || value is IPseudoComObject;
}
/// <summary>
/// Tries to perform binding of the dynamic get member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="instance">The target of the dynamic operation. </param>
/// <param name="result">The new <see cref="DynamicMetaObject"/> representing the result of the binding.</param>
/// <param name="delayInvocation">true if member evaluation may be delayed.</param>
/// <returns>true if operation was bound successfully; otherwise, false.</returns>
public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result, bool delayInvocation)
{
if (TryGetMetaObject(ref instance))
{
var comGetMember = new ComGetMemberBinder(binder, delayInvocation);
result = instance.BindGetMember(comGetMember);
if (result.Expression.Type.IsValueType)
{
result = new DynamicMetaObject(
Expression.Convert(result.Expression, typeof(object)),
result.Restrictions
);
}
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Tries to perform binding of the dynamic get member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="instance">The target of the dynamic operation. </param>
/// <param name="result">The new <see cref="DynamicMetaObject"/> representing the result of the binding.</param>
/// <returns>true if operation was bound successfully; otherwise, false.</returns>
public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result)
{
return TryBindGetMember(binder, instance, out result, false);
}
/// <summary>
/// Tries to perform binding of the dynamic set member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="instance">The target of the dynamic operation.</param>
/// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param>
/// <param name="result">The new <see cref="DynamicMetaObject"/> representing the result of the binding.</param>
/// <returns>true if operation was bound successfully; otherwise, false.</returns>
public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject value, out DynamicMetaObject result)
{
if (TryGetMetaObject(ref instance))
{
result = instance.BindSetMember(binder, value);
result = new DynamicMetaObject(result.Expression, result.Restrictions.Merge(value.PSGetMethodArgumentRestriction()));
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Tries to perform binding of the dynamic invoke operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="InvokeBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="instance">The target of the dynamic operation. </param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param>
/// <param name="result">The new <see cref="DynamicMetaObject"/> representing the result of the binding.</param>
/// <returns>true if operation was bound successfully; otherwise, false.</returns>
public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result)
{
if (TryGetMetaObjectInvoke(ref instance))
{
result = instance.BindInvoke(binder, args);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Tries to perform binding of the dynamic invoke member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="InvokeMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="isSetProperty">True if this is for setting a property, false otherwise..</param>
/// <param name="instance">The target of the dynamic operation. </param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param>
/// <param name="result">The new <see cref="DynamicMetaObject"/> representing the result of the binding.</param>
/// <returns>true if operation was bound successfully; otherwise, false.</returns>
public static bool TryBindInvokeMember(InvokeMemberBinder binder, bool isSetProperty, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result)
{
if (TryGetMetaObject(ref instance))
{
var comInvokeMember = new ComInvokeMemberBinder(binder, isSetProperty);
result = instance.BindInvokeMember(comInvokeMember, args);
BindingRestrictions argRestrictions = args.Aggregate(
BindingRestrictions.Empty, (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction()));
var newRestrictions = result.Restrictions.Merge(argRestrictions);
if (result.Expression.Type.IsValueType)
{
result = new DynamicMetaObject(
Expression.Convert(result.Expression, typeof(object)),
newRestrictions
);
}
else
{
result = new DynamicMetaObject(result.Expression, newRestrictions);
}
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Tries to perform binding of the dynamic get index operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="instance">The target of the dynamic operation. </param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param>
/// <param name="result">The new <see cref="DynamicMetaObject"/> representing the result of the binding.</param>
/// <returns>true if operation was bound successfully; otherwise, false.</returns>
public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result)
{
if (TryGetMetaObjectInvoke(ref instance))
{
result = instance.BindGetIndex(binder, args);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Tries to perform binding of the dynamic set index operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="instance">The target of the dynamic operation. </param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param>
/// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param>
/// <param name="result">The new <see cref="DynamicMetaObject"/> representing the result of the binding.</param>
/// <returns>true if operation was bound successfully; otherwise, false.</returns>
public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, DynamicMetaObject value, out DynamicMetaObject result)
{
if (TryGetMetaObjectInvoke(ref instance))
{
result = instance.BindSetIndex(binder, args, value);
result = new DynamicMetaObject(result.Expression, result.Restrictions.Merge(value.PSGetMethodArgumentRestriction()));
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Tries to perform binding of the dynamic Convert operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="instance">The target of the dynamic operation.</param>
/// <param name="result">The new <see cref="DynamicMetaObject"/> representing the result of the binding.</param>
/// <returns>true if operation was bound successfully; otherwise, false.</returns>
public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, out DynamicMetaObject result)
{
if (IsComObject(instance.Value))
{
// Converting a COM object to any interface is always considered possible - it will result in
// a QueryInterface at runtime
if (binder.Type.IsInterface)
{
result = new DynamicMetaObject(
Expression.Convert(
instance.Expression,
binder.Type
),
BindingRestrictions.GetExpressionRestriction(
Expression.Call(
typeof(ComObject).GetMethod("IsComObject", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic),
Helpers.Convert(instance.Expression, typeof(object))
)
)
);
return true;
}
}
result = null;
return false;
}
/// <summary>
/// Gets the member names associated with the object.
/// This function can operate only with objects for which <see cref="IsComObject"/> returns true.
/// </summary>
/// <param name="value">The object for which member names are requested.</param>
/// <returns>The collection of member names.</returns>
public static IEnumerable<string> GetDynamicMemberNames(object value)
{
return ComObject.ObjectToComObject(value).GetMemberNames(false);
}
/// <summary>
/// Gets the member names of the data-like members associated with the object.
/// This function can operate only with objects for which <see cref="IsComObject"/> returns true.
/// </summary>
/// <param name="value">The object for which member names are requested.</param>
/// <returns>The collection of member names.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static IList<string> GetDynamicDataMemberNames(object value)
{
return ComObject.ObjectToComObject(value).GetMemberNames(true);
}
/// <summary>
/// Gets the data-like members and associated data for an object.
/// This function can operate only with objects for which <see cref="IsComObject"/> returns true.
/// </summary>
/// <param name="value">The object for which data members are requested.</param>
/// <param name="names">The enumeration of names of data members for which to retrieve values.</param>
/// <returns>The collection of pairs that represent data member's names and their data.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static IList<KeyValuePair<string, object>> GetDynamicDataMembers(object value, IEnumerable<string> names)
{
return ComObject.ObjectToComObject(value).GetMembers(names);
}
private static bool TryGetMetaObject(ref DynamicMetaObject instance)
{
// If we're already a COM MO don't make a new one
// (we do this to prevent recursion if we call Fallback from COM)
if (instance is ComUnwrappedMetaObject)
{
return false;
}
if (IsComObject(instance.Value))
{
instance = new ComMetaObject(instance.Expression, instance.Restrictions, instance.Value);
return true;
}
return false;
}
private static bool TryGetMetaObjectInvoke(ref DynamicMetaObject instance)
{
// If we're already a COM MO don't make a new one
// (we do this to prevent recursion if we call Fallback from COM)
if (TryGetMetaObject(ref instance))
{
return true;
}
if (instance.Value is IPseudoComObject)
{
instance = ((IPseudoComObject)instance.Value).GetMetaObject(instance.Expression);
return true;
}
return false;
}
/// <summary>
/// Special binder that indicates special semantics for COM GetMember operation.
/// </summary>
internal class ComGetMemberBinder : GetMemberBinder
{
private readonly GetMemberBinder _originalBinder;
internal bool _CanReturnCallables;
internal ComGetMemberBinder(GetMemberBinder originalBinder, bool CanReturnCallables) :
base(originalBinder.Name, originalBinder.IgnoreCase)
{
_originalBinder = originalBinder;
_CanReturnCallables = CanReturnCallables;
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
return _originalBinder.FallbackGetMember(target, errorSuggestion);
}
public override int GetHashCode()
{
return _originalBinder.GetHashCode() ^ (_CanReturnCallables ? 1 : 0);
}
public override bool Equals(object obj)
{
ComGetMemberBinder other = obj as ComGetMemberBinder;
return other != null &&
_CanReturnCallables == other._CanReturnCallables &&
_originalBinder.Equals(other._originalBinder);
}
}
/// <summary>
/// Special binder that indicates special semantics for COM InvokeMember operation.
/// </summary>
internal class ComInvokeMemberBinder : InvokeMemberBinder
{
private readonly InvokeMemberBinder _originalBinder;
internal bool IsPropertySet;
internal ComInvokeMemberBinder(InvokeMemberBinder originalBinder, bool isPropertySet) :
base(originalBinder.Name, originalBinder.IgnoreCase, originalBinder.CallInfo)
{
_originalBinder = originalBinder;
this.IsPropertySet = isPropertySet;
}
public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
{
return _originalBinder.FallbackInvoke(target, args, errorSuggestion);
}
public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
{
return _originalBinder.FallbackInvokeMember(target, args, errorSuggestion);
}
public override int GetHashCode()
{
return _originalBinder.GetHashCode() ^ (IsPropertySet ? 1 : 0);
}
public override bool Equals(object obj)
{
ComInvokeMemberBinder other = obj as ComInvokeMemberBinder;
return other != null &&
IsPropertySet == other.IsPropertySet &&
_originalBinder.Equals(other._originalBinder);
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementSingle1()
{
var test = new VectorGetAndWithElement__GetAndWithElementSingle1();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementSingle1
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector256<Single> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
Single result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
Vector256<Single> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector256<Single> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Single)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<Single>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Single result, Single[] values, [CallerMemberName] string method = "")
{
if (result != values[1])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<Single.GetElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<Single> result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Single[] result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 1) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[1] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Single.WithElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// UnionQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Operator that yields the union of two data sources.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
internal sealed class UnionQueryOperator<TInputOutput> :
BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput>
{
private readonly IEqualityComparer<TInputOutput>? _comparer; // An equality comparer.
//---------------------------------------------------------------------------------------
// Constructs a new union operator.
//
internal UnionQueryOperator(ParallelQuery<TInputOutput> left, ParallelQuery<TInputOutput> right, IEqualityComparer<TInputOutput>? comparer)
: base(left, right)
{
Debug.Assert(left != null && right != null, "child data sources cannot be null");
_comparer = comparer;
_outputOrdered = LeftChild.OutputOrdered || RightChild.OutputOrdered;
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TInputOutput> Open(
QuerySettings settings, bool preferStriping)
{
// We just open our child operators, left and then right. Do not propagate the preferStriping value, but
// instead explicitly set it to false. Regardless of whether the parent prefers striping or range
// partitioning, the output will be hash-partitioned.
QueryResults<TInputOutput> leftChildResults = LeftChild.Open(settings, false);
QueryResults<TInputOutput> rightChildResults = RightChild.Open(settings, false);
return new BinaryQueryOperatorResults(leftChildResults, rightChildResults, this, settings, false);
}
public override void WrapPartitionedStream<TLeftKey, TRightKey>(
PartitionedStream<TInputOutput, TLeftKey> leftStream, PartitionedStream<TInputOutput, TRightKey> rightStream,
IPartitionedStreamRecipient<TInputOutput> outputRecipient, bool preferStriping, QuerySettings settings)
{
Debug.Assert(leftStream.PartitionCount == rightStream.PartitionCount);
int partitionCount = leftStream.PartitionCount;
// Wrap both child streams with hash repartition
if (LeftChild.OutputOrdered)
{
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftHashStream =
ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TLeftKey>(
leftStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken);
WrapPartitionedStreamFixedLeftType<TLeftKey, TRightKey>(
leftHashStream, rightStream, outputRecipient, partitionCount, settings.CancellationState.MergedCancellationToken);
}
else
{
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, int> leftHashStream =
ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TLeftKey>(
leftStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken);
WrapPartitionedStreamFixedLeftType<int, TRightKey>(
leftHashStream, rightStream, outputRecipient, partitionCount, settings.CancellationState.MergedCancellationToken);
}
}
//---------------------------------------------------------------------------------------
// A helper method that allows WrapPartitionedStream to fix the TLeftKey type parameter.
//
private void WrapPartitionedStreamFixedLeftType<TLeftKey, TRightKey>(
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftHashStream, PartitionedStream<TInputOutput, TRightKey> rightStream,
IPartitionedStreamRecipient<TInputOutput> outputRecipient, int partitionCount, CancellationToken cancellationToken)
{
if (RightChild.OutputOrdered)
{
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> rightHashStream =
ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TRightKey>(
rightStream, null, null, _comparer, cancellationToken);
WrapPartitionedStreamFixedBothTypes<TLeftKey, TRightKey>(
leftHashStream, rightHashStream, outputRecipient, partitionCount, cancellationToken);
}
else
{
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, int> rightHashStream =
ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TRightKey>(
rightStream, null, null, _comparer, cancellationToken);
WrapPartitionedStreamFixedBothTypes<TLeftKey, int>(
leftHashStream, rightHashStream, outputRecipient, partitionCount, cancellationToken);
}
}
//---------------------------------------------------------------------------------------
// A helper method that allows WrapPartitionedStreamHelper to fix the TRightKey type parameter.
//
private void WrapPartitionedStreamFixedBothTypes<TLeftKey, TRightKey>(
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftHashStream,
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> rightHashStream,
IPartitionedStreamRecipient<TInputOutput> outputRecipient, int partitionCount,
CancellationToken cancellationToken)
{
if (LeftChild.OutputOrdered || RightChild.OutputOrdered)
{
IComparer<ConcatKey<TLeftKey, TRightKey>> compoundKeyComparer =
ConcatKey<TLeftKey, TRightKey>.MakeComparer(leftHashStream.KeyComparer, rightHashStream.KeyComparer);
PartitionedStream<TInputOutput, ConcatKey<TLeftKey, TRightKey>> outputStream =
new PartitionedStream<TInputOutput, ConcatKey<TLeftKey, TRightKey>>(partitionCount, compoundKeyComparer, OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new OrderedUnionQueryOperatorEnumerator<TLeftKey, TRightKey>(
leftHashStream[i], rightHashStream[i], LeftChild.OutputOrdered, RightChild.OutputOrdered,
_comparer, compoundKeyComparer, cancellationToken);
}
outputRecipient.Receive(outputStream);
}
else
{
PartitionedStream<TInputOutput, int> outputStream =
new PartitionedStream<TInputOutput, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new UnionQueryOperatorEnumerator<TLeftKey, TRightKey>(
leftHashStream[i], rightHashStream[i], _comparer, cancellationToken);
}
outputRecipient.Receive(outputStream);
}
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TInputOutput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token);
IEnumerable<TInputOutput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token);
return wrappedLeftChild.Union(wrappedRightChild, _comparer);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// This enumerator performs the union operation incrementally. It does this by maintaining
// a history -- in the form of a set -- of all data already seen. It is careful not to
// return any duplicates.
//
private class UnionQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TInputOutput, int>
{
private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey>? _leftSource; // Left data source.
private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey>? _rightSource; // Right data source.
private Set<TInputOutput>? _hashLookup; // The hash lookup, used to produce the union.
private readonly CancellationToken _cancellationToken;
private Shared<int>? _outputLoopCount;
private readonly IEqualityComparer<TInputOutput>? _comparer;
//---------------------------------------------------------------------------------------
// Instantiates a new union operator.
//
internal UnionQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftSource,
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> rightSource,
IEqualityComparer<TInputOutput>? comparer,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(rightSource != null);
_leftSource = leftSource;
_rightSource = rightSource;
_comparer = comparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the two data sources, left and then right, to produce the union.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TInputOutput currentElement, ref int currentKey)
{
if (_hashLookup == null)
{
_hashLookup = new Set<TInputOutput>(_comparer);
_outputLoopCount = new Shared<int>(0);
}
Debug.Assert(_hashLookup != null);
// Enumerate the left and then right data source. When each is done, we set the
// field to null so we will skip it upon subsequent calls to MoveNext.
if (_leftSource != null)
{
// Iterate over this set's elements until we find a unique element.
TLeftKey keyUnused = default(TLeftKey)!;
Pair<TInputOutput, NoKeyMemoizationRequired> currentLeftElement = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
int i = 0;
while (_leftSource.MoveNext(ref currentLeftElement, ref keyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We ensure we never return duplicates by tracking them in our set.
if (_hashLookup.Add(currentLeftElement.First))
{
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
currentElement = currentLeftElement.First;
return true;
}
}
_leftSource.Dispose();
_leftSource = null;
}
if (_rightSource != null)
{
// Iterate over this set's elements until we find a unique element.
TRightKey keyUnused = default(TRightKey)!;
Pair<TInputOutput, NoKeyMemoizationRequired> currentRightElement = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
while (_rightSource.MoveNext(ref currentRightElement, ref keyUnused))
{
Debug.Assert(_outputLoopCount != null);
if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We ensure we never return duplicates by tracking them in our set.
if (_hashLookup.Add(currentRightElement.First))
{
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
currentElement = currentRightElement.First;
return true;
}
}
_rightSource.Dispose();
_rightSource = null;
}
return false;
}
protected override void Dispose(bool disposing)
{
if (_leftSource != null)
{
_leftSource.Dispose();
}
if (_rightSource != null)
{
_rightSource.Dispose();
}
}
}
private class OrderedUnionQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TInputOutput, ConcatKey<TLeftKey, TRightKey>>
{
private readonly QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> _leftSource; // Left data source.
private readonly QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> _rightSource; // Right data source.
private readonly IComparer<ConcatKey<TLeftKey, TRightKey>> _keyComparer; // Comparer for compound order keys.
private IEnumerator<KeyValuePair<Wrapper<TInputOutput>, Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>>>? _outputEnumerator; // Enumerator over the output of the union.
private readonly bool _leftOrdered; // Whether the left data source is ordered.
private readonly bool _rightOrdered; // Whether the right data source is ordered.
private readonly IEqualityComparer<TInputOutput>? _comparer; // Comparer for the elements.
private readonly CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new union operator.
//
internal OrderedUnionQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftSource,
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> rightSource,
bool leftOrdered, bool rightOrdered, IEqualityComparer<TInputOutput>? comparer, IComparer<ConcatKey<TLeftKey, TRightKey>> keyComparer,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(rightSource != null);
_leftSource = leftSource;
_rightSource = rightSource;
_keyComparer = keyComparer;
_leftOrdered = leftOrdered;
_rightOrdered = rightOrdered;
_comparer = comparer;
if (_comparer == null)
{
_comparer = EqualityComparer<TInputOutput>.Default;
}
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the two data sources, left and then right, to produce the union.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TInputOutput currentElement, ref ConcatKey<TLeftKey, TRightKey> currentKey)
{
Debug.Assert(_leftSource != null);
Debug.Assert(_rightSource != null);
if (_outputEnumerator == null)
{
IEqualityComparer<Wrapper<TInputOutput>> wrapperComparer = new WrapperEqualityComparer<TInputOutput>(_comparer);
Dictionary<Wrapper<TInputOutput>, Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>> union =
new Dictionary<Wrapper<TInputOutput>, Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>>(wrapperComparer);
Pair<TInputOutput, NoKeyMemoizationRequired> elem = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
TLeftKey leftKey = default(TLeftKey)!;
int i = 0;
while (_leftSource.MoveNext(ref elem, ref leftKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
ConcatKey<TLeftKey, TRightKey> key =
ConcatKey<TLeftKey, TRightKey>.MakeLeft(_leftOrdered ? leftKey : default);
Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>> oldEntry;
Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>(elem.First);
if (!union.TryGetValue(wrappedElem, out oldEntry) || _keyComparer.Compare(key, oldEntry.Second) < 0)
{
union[wrappedElem] = new Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>(elem.First, key);
}
}
TRightKey rightKey = default(TRightKey)!;
while (_rightSource.MoveNext(ref elem, ref rightKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
ConcatKey<TLeftKey, TRightKey> key =
ConcatKey<TLeftKey, TRightKey>.MakeRight(_rightOrdered ? rightKey : default);
Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>> oldEntry;
Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>(elem.First);
if (!union.TryGetValue(wrappedElem, out oldEntry) || _keyComparer.Compare(key, oldEntry.Second) < 0)
{
union[wrappedElem] = new Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>(elem.First, key);
}
}
_outputEnumerator = union.GetEnumerator();
}
if (_outputEnumerator.MoveNext())
{
Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>> current = _outputEnumerator.Current.Value;
currentElement = current.First;
currentKey = current.Second;
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_leftSource != null && _rightSource != null);
_leftSource.Dispose();
_rightSource.Dispose();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Text
{
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
internal class DecoderNLS : Decoder, ISerializable
{
// Remember our encoding
protected EncodingNLS m_encoding;
protected bool m_mustFlush;
internal bool m_throwOnOverflow;
internal int m_bytesUsed;
internal DecoderFallback m_fallback;
internal DecoderFallbackBuffer m_fallbackBuffer;
internal DecoderNLS(EncodingNLS encoding)
{
m_encoding = encoding;
m_fallback = m_encoding.DecoderFallback;
Reset();
}
// This is used by our child deserializers
internal DecoderNLS()
{
m_encoding = null;
Reset();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(DecoderNLSSurrogate.EncodingKey, m_encoding);
info.AddValue(DecoderNLSSurrogate.DecoderFallbackKey, m_fallback);
info.SetType(typeof(DecoderNLSSurrogate));
}
internal sealed class DecoderNLSSurrogate : IObjectReference, ISerializable
{
internal const string EncodingKey = "Encoding";
internal const string DecoderFallbackKey = "DecoderFallback";
private readonly Encoding _encoding;
private readonly DecoderFallback _fallback;
internal DecoderNLSSurrogate(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
_encoding = (Encoding)info.GetValue(EncodingKey, typeof(Encoding));
_fallback = (DecoderFallback)info.GetValue(DecoderFallbackKey, typeof(DecoderFallback));
}
public object GetRealObject(StreamingContext context)
{
Decoder decoder = _encoding.GetDecoder();
if (_fallback != null)
{
decoder.Fallback = _fallback;
}
return decoder;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// This should never be called. If it is, there's a bug in the formatter being used.
throw new NotSupportedException();
}
}
internal new DecoderFallback Fallback
{
get { return m_fallback; }
}
internal bool InternalHasFallbackBuffer
{
get
{
return m_fallbackBuffer != null;
}
}
public new DecoderFallbackBuffer FallbackBuffer
{
get
{
if (m_fallbackBuffer == null)
{
if (m_fallback != null)
m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
else
m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return m_fallbackBuffer;
}
}
public override void Reset()
{
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid null fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (byte* pBytes = &bytes[0])
return GetCharCount(pBytes + index, count, flush);
}
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember the flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
return m_encoding.GetCharCount(bytes, count, this);
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes): nameof(chars), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
// Avoid empty input fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
int charCount = chars.Length - charIndex;
if (chars.Length == 0)
chars = new char[1];
// Just call pointer version
fixed (byte* pBytes = &bytes[0])
fixed (char* pChars = &chars[0])
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, flush);
}
[System.Security.SecurityCritical] // auto-generated
public override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars): nameof(bytes)), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember our flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding's version
return m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? nameof(bytes): nameof(chars)), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex): nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (bytes.Length == 0)
bytes = new byte[1];
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version (public overrides can't do this)
fixed (byte* pBytes = &bytes[0])
{
fixed (char* pChars = &chars[0])
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush,
out bytesUsed, out charsUsed, out completed);
}
}
}
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
[System.Security.SecurityCritical] // auto-generated
public override unsafe void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars): nameof(bytes), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount): nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
m_mustFlush = flush;
m_throwOnOverflow = false;
m_bytesUsed = 0;
// Do conversion
charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = m_bytesUsed;
// It's completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (bytesUsed == byteCount) && (!flush || !HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingies are now full, we can return
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our decoder?
internal virtual bool HasState
{
get
{
return false;
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Markup;
using System.Diagnostics;
using System.Xml;
using MS.Internal;
namespace System.Windows.Controls
{
/// <summary>
/// AccessText Element - Register an accesskey specified after the underscore character in the text.
/// </summary>
[ContentProperty("Text")]
public class AccessText : FrameworkElement, IAddChild
{
//-------------------------------------------------------------------
//
// IContentHost Members
//
//-------------------------------------------------------------------
#region IAddChild members
///<summary>
/// Called to Add the object as a Child.
///</summary>
///<param name="value">
/// Object to add as a child
///</param>
void IAddChild.AddChild(Object value)
{
((IAddChild)TextBlock).AddChild(value);
}
///<summary>
/// Called when text appears under the tag in markup.
///</summary>
///<param name="text">
/// Text to Add to the Object
///</param>
void IAddChild.AddText(string text)
{
((IAddChild)TextBlock).AddText(text);
}
#endregion IAddChild members
//-------------------------------------------------------------------
//
// LogicalTree
//
//-------------------------------------------------------------------
#region LogicalTree
/// <summary>
/// Returns enumerator to logical children.
/// </summary>
protected internal override IEnumerator LogicalChildren
{
get
{
return new RangeContentEnumerator(TextContainer.Start, TextContainer.End);
}
}
#endregion LogicalTree
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// AccessText constructor.
/// </summary>
public AccessText() : base()
{
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Read only access to the key after the first underline character
/// </summary>
public char AccessKey
{
get
{
//
return (_accessKey != null && _accessKey.Text.Length > 0) ? _accessKey.Text[0] : (char)0;
}
}
#endregion Public Properties
//-------------------------------------------------------------------
//
// Public Dynamic Properties
//
//-------------------------------------------------------------------
#region Public Dynamic Properties
/// <summary>
/// DependencyProperty for <see cref="Text" /> property.
/// </summary>
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(
"Text",
typeof(string),
typeof(AccessText),
new FrameworkPropertyMetadata(
string.Empty,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnTextChanged)));
/// <summary>
/// The Text property defines the text to be displayed.
/// </summary>
[DefaultValue("")]
public string Text
{
get { return (string) GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="FontFamily" /> property.
/// </summary>
public static readonly DependencyProperty FontFamilyProperty =
TextElement.FontFamilyProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The FontFamily property specifies the name of font family.
/// </summary>
[Localizability(
LocalizationCategory.Font,
Modifiability = Modifiability.Unmodifiable
)]
public FontFamily FontFamily
{
get { return (FontFamily) GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="FontStyle" /> property.
/// </summary>
public static readonly DependencyProperty FontStyleProperty =
TextElement.FontStyleProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The FontStyle property requests normal, italic, and oblique faces within a font family.
/// </summary>
public FontStyle FontStyle
{
get { return (FontStyle) GetValue(FontStyleProperty); }
set { SetValue(FontStyleProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="FontWeight" /> property.
/// </summary>
public static readonly DependencyProperty FontWeightProperty =
TextElement.FontWeightProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The FontWeight property specifies the weight of the font.
/// </summary>
public FontWeight FontWeight
{
get { return (FontWeight) GetValue(FontWeightProperty); }
set { SetValue(FontWeightProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="FontStretch" /> property.
/// </summary>
public static readonly DependencyProperty FontStretchProperty =
TextElement.FontStretchProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The FontStretch property selects a normal, condensed, or extended face from a font family.
/// </summary>
public FontStretch FontStretch
{
get { return (FontStretch) GetValue(FontStretchProperty); }
set { SetValue(FontStretchProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="FontSize" /> property.
/// </summary>
public static readonly DependencyProperty FontSizeProperty =
TextElement.FontSizeProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The FontSize property specifies the size of the font.
/// </summary>
[TypeConverter(typeof(FontSizeConverter))]
[Localizability(LocalizationCategory.None)]
public double FontSize
{
get { return (double) GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="Foreground" /> property.
/// </summary>
public static readonly DependencyProperty ForegroundProperty =
TextElement.ForegroundProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The Foreground property specifies the foreground brush of an element's text content.
/// </summary>
public Brush Foreground
{
get { return (Brush) GetValue(ForegroundProperty); }
set { SetValue(ForegroundProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="Background" /> property.
/// </summary>
public static readonly DependencyProperty BackgroundProperty =
TextElement.BackgroundProperty.AddOwner(
typeof(AccessText),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPropertyChanged)));
/// <summary>
/// The Background property defines the brush used to fill the content area.
/// </summary>
public Brush Background
{
get { return (Brush) GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="TextDecorations" /> property.
/// </summary>
public static readonly DependencyProperty TextDecorationsProperty =
Inline.TextDecorationsProperty.AddOwner(
typeof(AccessText),
new FrameworkPropertyMetadata(
new FreezableDefaultValueFactory(TextDecorationCollection.Empty),
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPropertyChanged)));
/// <summary>
/// The TextDecorations property specifies decorations that are added to the text of an element.
/// </summary>
public TextDecorationCollection TextDecorations
{
get { return (TextDecorationCollection) GetValue(TextDecorationsProperty); }
set { SetValue(TextDecorationsProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="TextEffects" /> property.
/// </summary>
public static readonly DependencyProperty TextEffectsProperty =
TextElement.TextEffectsProperty.AddOwner(
typeof(AccessText),
new FrameworkPropertyMetadata(
new FreezableDefaultValueFactory(TextEffectCollection.Empty),
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPropertyChanged)));
/// <summary>
/// The TextEffects property specifies effects that are added to the text of an element.
/// </summary>
public TextEffectCollection TextEffects
{
get { return (TextEffectCollection) GetValue(TextEffectsProperty); }
set { SetValue(TextEffectsProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="LineHeight" /> property.
/// </summary>
public static readonly DependencyProperty LineHeightProperty =
Block.LineHeightProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The LineHeight property specifies the height of each generated line box.
/// </summary>
[TypeConverter(typeof(LengthConverter))]
public double LineHeight
{
get { return (double) GetValue(LineHeightProperty); }
set { SetValue(LineHeightProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="LineStackingStrategy" /> property.
/// </summary>
public static readonly DependencyProperty LineStackingStrategyProperty =
Block.LineStackingStrategyProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The LineStackingStrategy property specifies how lines are placed
/// </summary>
public LineStackingStrategy LineStackingStrategy
{
get { return (LineStackingStrategy)GetValue(LineStackingStrategyProperty); }
set { SetValue(LineStackingStrategyProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="TextAlignment" /> property.
/// </summary>
public static readonly DependencyProperty TextAlignmentProperty =
Block.TextAlignmentProperty.AddOwner(typeof(AccessText));
/// <summary>
/// The TextAlignment property specifies horizontal alignment of the content.
/// </summary>
public TextAlignment TextAlignment
{
get { return (TextAlignment) GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="TextTrimming" /> property.
/// </summary>
public static readonly DependencyProperty TextTrimmingProperty =
TextBlock.TextTrimmingProperty.AddOwner(
typeof(AccessText),
new FrameworkPropertyMetadata(
TextTrimming.None,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPropertyChanged)));
/// <summary>
/// The TextTrimming property specifies the trimming behavior situation
/// in case of clipping some textual content caused by overflowing the line's box.
/// </summary>
public TextTrimming TextTrimming
{
get { return (TextTrimming) GetValue(TextTrimmingProperty); }
set { SetValue(TextTrimmingProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="TextWrapping" /> property.
/// </summary>
public static readonly DependencyProperty TextWrappingProperty =
TextBlock.TextWrappingProperty.AddOwner(
typeof(AccessText),
new FrameworkPropertyMetadata(
TextWrapping.NoWrap,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPropertyChanged)));
/// <summary>
/// The TextWrapping property controls whether or not text wraps
/// when it reaches the flow edge of its containing block box.
/// </summary>
public TextWrapping TextWrapping
{
get { return (TextWrapping) GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="BaselineOffset" /> property.
/// </summary>
public static readonly DependencyProperty BaselineOffsetProperty =
TextBlock.BaselineOffsetProperty.AddOwner(typeof(AccessText), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnPropertyChanged)));
/// <summary>
/// The BaselineOffset property provides an adjustment to baseline offset
/// </summary>
public double BaselineOffset
{
get { return (double) GetValue(BaselineOffsetProperty); }
set { SetValue(BaselineOffsetProperty, value); }
}
#endregion Public Dynamic Properties
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// Content measurement.
/// </summary>
/// <param name="constraint">Constraint size.</param>
/// <returns>Computed desired size.</returns>
protected sealed override Size MeasureOverride(Size constraint)
{
TextBlock.Measure(constraint);
return TextBlock.DesiredSize;
}
/// <summary>
/// Content arrangement.
/// </summary>
/// <param name="arrangeSize">Size that element should use to arrange itself and its children.</param>
protected sealed override Size ArrangeOverride(Size arrangeSize)
{
TextBlock.Arrange(new Rect(arrangeSize));
return arrangeSize;
}
#endregion Protected Methods
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
internal static bool HasCustomSerialization(object o)
{
Run accessKey = o as Run;
return accessKey != null && HasCustomSerializationStorage.GetValue(accessKey);
}
#endregion Internal methods
//-------------------------------------------------------------------
//
// Internal Properties
//
//-------------------------------------------------------------------
#region Internal Properties
internal TextBlock TextBlock
{
get
{
if (_textBlock == null)
CreateTextBlock();
return _textBlock;
}
}
internal static char AccessKeyMarker
{
get { return _accessKeyMarker; }
}
#endregion Internal Properties
//-------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------
#region Private Methods
private TextContainer TextContainer
{
get
{
if (_textContainer == null)
CreateTextBlock();
return _textContainer;
}
}
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((AccessText)d).TextBlock.SetValue(e.Property, e.NewValue);
}
/// <summary>
/// CreateTextBlock - Creates a text block, adds as visual child, databinds properties and sets up appropriate event listener.
/// </summary>
private void CreateTextBlock()
{
_textContainer = new TextContainer(this, false /* plainTextOnly */);
_textBlock = new TextBlock();
AddVisualChild(_textBlock);
_textBlock.IsContentPresenterContainer = true;
_textBlock.SetTextContainer(_textContainer);
InitializeTextContainerListener();
}
/// <summary>
/// Gets the Visual children count of the AccessText control.
/// </summary>
protected override int VisualChildrenCount
{
get { return 1; }
}
/// <summary>
/// Gets the Visual child at the specified index.
/// </summary>
protected override Visual GetVisualChild(int index)
{
if (index != 0)
{
throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange));
}
return TextBlock;
}
// Provides custom serialization for this element
internal static void SerializeCustom(XmlWriter xmlWriter, object o)
{
Run inlineScope = o as Run;
if (inlineScope != null)
{
xmlWriter.WriteString(AccessKeyMarker + inlineScope.Text);
}
}
private static Style AccessKeyStyle
{
get
{
if (_accessKeyStyle == null)
{
Style accessKeyStyle = new Style(typeof(Run));
Trigger trigger = new Trigger();
trigger.Property = KeyboardNavigation.ShowKeyboardCuesProperty;
trigger.Value = true;
trigger.Setters.Add(new Setter(TextDecorationsProperty, System.Windows.TextDecorations.Underline));
accessKeyStyle.Triggers.Add(trigger);
accessKeyStyle.Seal();
_accessKeyStyle = accessKeyStyle;
}
return _accessKeyStyle;
}
}
/// <summary>
/// UpdateAccessKey - Scans forward in the tree looking for the access key marker, replacing it with access key element. We only support one find.
/// </summary>
private void UpdateAccessKey()
{
TextPointer navigator = new TextPointer(TextContainer.Start);
while (!_accessKeyLocated && navigator.CompareTo(TextContainer.End) < 0 )
{
TextPointerContext symbolType = navigator.GetPointerContext(LogicalDirection.Forward);
switch (symbolType)
{
case TextPointerContext.Text:
string text = navigator.GetTextInRun(LogicalDirection.Forward);
int index = FindAccessKeyMarker(text);
if(index != -1 && index < text.Length - 1)
{
string keyText = StringInfo.GetNextTextElement(text, index + 1);
TextPointer keyEnd = navigator.GetPositionAtOffset(index + 1 + keyText.Length);
_accessKey = new Run(keyText);
_accessKey.Style = AccessKeyStyle;
RegisterAccessKey();
HasCustomSerializationStorage.SetValue(_accessKey, true);
_accessKeyLocated = true;
UninitializeTextContainerListener();
TextContainer.BeginChange();
try
{
TextPointer underlineStart = new TextPointer(navigator, index);
TextRangeEdit.DeleteInlineContent(underlineStart, keyEnd);
_accessKey.RepositionWithContent(underlineStart);
}
finally
{
TextContainer.EndChange();
InitializeTextContainerListener();
}
}
break;
}
navigator.MoveToNextContextPosition(LogicalDirection.Forward);
}
// Convert double _ to single _
navigator = new TextPointer(TextContainer.Start);
string accessKeyMarker = AccessKeyMarker.ToString();
string doubleAccessKeyMarker = accessKeyMarker + accessKeyMarker;
while (navigator.CompareTo(TextContainer.End) < 0)
{
TextPointerContext symbolType = navigator.GetPointerContext(LogicalDirection.Forward);
switch (symbolType)
{
case TextPointerContext.Text:
string text = navigator.GetTextInRun(LogicalDirection.Forward);
string nexText = text.Replace(doubleAccessKeyMarker, accessKeyMarker);
if (text != nexText)
{
TextPointer keyStart = new TextPointer(navigator, 0);
TextPointer keyEnd = new TextPointer(navigator, text.Length);
UninitializeTextContainerListener();
TextContainer.BeginChange();
try
{
keyEnd.InsertTextInRun(nexText);
TextRangeEdit.DeleteInlineContent(keyStart, keyEnd);
}
finally
{
TextContainer.EndChange();
InitializeTextContainerListener();
}
}
break;
}
navigator.MoveToNextContextPosition(LogicalDirection.Forward);
}
}
// Returns the index of _ marker.
// _ can be escaped by double _
private static int FindAccessKeyMarker(string text)
{
int lenght = text.Length;
int startIndex = 0;
while (startIndex < lenght)
{
int index = text.IndexOf(AccessKeyMarker, startIndex);
if (index == -1)
return -1;
// If next char exist and different from _
if (index + 1 < lenght && text[index + 1] != AccessKeyMarker)
return index;
startIndex = index + 2;
}
return -1;
}
internal static string RemoveAccessKeyMarker(string text)
{
if (!string.IsNullOrEmpty(text))
{
string accessKeyMarker = AccessKeyMarker.ToString();
string doubleAccessKeyMarker = accessKeyMarker + accessKeyMarker;
int index = FindAccessKeyMarker(text);
if (index >=0 && index < text.Length - 1)
text = text.Remove(index, 1);
// Replace double _ with single _
text = text.Replace(doubleAccessKeyMarker, accessKeyMarker);
}
return text;
}
private void RegisterAccessKey()
{
if (_currentlyRegistered != null)
{
AccessKeyManager.Unregister(_currentlyRegistered, this);
_currentlyRegistered = null;
}
string key = _accessKey.Text;
if (!string.IsNullOrEmpty(key))
{
AccessKeyManager.Register(key, this);
_currentlyRegistered = key;
}
}
//-------------------------------------------------------------------
// Text helpers
//-------------------------------------------------------------------
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((AccessText) d).UpdateText((string) e.NewValue);
}
private void UpdateText(string text)
{
if (text == null)
text = string.Empty;
_accessKeyLocated = false;
_accessKey = null;
TextContainer.BeginChange();
try
{
TextContainer.DeleteContentInternal((TextPointer)TextContainer.Start, TextContainer.End);
Run run = Inline.CreateImplicitRun(this);
((TextPointer)TextContainer.End).InsertTextElement(run);
run.Text = text;
}
finally
{
TextContainer.EndChange();
}
}
// ------------------------------------------------------------------
// Setup event handler.
// ------------------------------------------------------------------
private void InitializeTextContainerListener()
{
TextContainer.Changed += new TextContainerChangedEventHandler(OnTextContainerChanged);
}
// ------------------------------------------------------------------
// Clear event handler.
// ------------------------------------------------------------------
private void UninitializeTextContainerListener()
{
TextContainer.Changed -= new TextContainerChangedEventHandler(OnTextContainerChanged);
}
// ------------------------------------------------------------------
// Handler for TextContainer.Changed notification.
// ------------------------------------------------------------------
private void OnTextContainerChanged(object sender, TextContainerChangedEventArgs args)
{
// Skip changes that only affect properties.
if (args.HasContentAddedOrRemoved)
{
UpdateAccessKey();
}
}
#endregion Private methods
//-------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------
#region Private Fields
//---------------------------------------------------------------
// Text container for actual content
//---------------------------------------------------------------
private TextContainer _textContainer;
//---------------------------------------------------------------
// Visual tree text block
//---------------------------------------------------------------
private TextBlock _textBlock;
//---------------------------------------------------------------
// Visual tree Run - created internally if _ is found
//---------------------------------------------------------------
private Run _accessKey;
//---------------------------------------------------------------
// Flag indicating whether the access key element has been located
//---------------------------------------------------------------
private bool _accessKeyLocated;
//---------------------------------------------------------------
// Defines the charecter to be used in fron of the access key
//---------------------------------------------------------------
private const char _accessKeyMarker = '_';
//---------------------------------------------------------------
// Stores the default Style applied on the internal Run
//---------------------------------------------------------------
private static Style _accessKeyStyle;
//---------------------------------------------------------------
// Flag that indicates if access key is registered with this AccessText
//---------------------------------------------------------------
private string _currentlyRegistered;
//---------------------------------------------------------------
// Flag that indicates that internal Run should have a custom serialization
//---------------------------------------------------------------
private static readonly UncommonField<bool> HasCustomSerializationStorage = new UncommonField<bool>();
#endregion Private Fields
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder
// File : NewFromOtherFormatDlg.cs
// Author : Eric Woodruff ([email protected])
// Updated : 10/12/2008
// Note : Copyright 2008, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains the form used to convert a project in a different format
// to the new MSBuild format used by SHFB 1.8.0.0 and later.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.8.0.0 08/04/2008 EFW Created the code
//=============================================================================
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.Conversion;
namespace SandcastleBuilder.Gui
{
/// <summary>
/// This form is used to convert a project in a different format to the new
/// MSBuild format used by SHFB 1.8.0.0 and later.
/// </summary>
public partial class NewFromOtherFormatDlg : Form
{
#region Private data members
//=====================================================================
private string newProjectFilename;
#endregion
#region Properties
//=====================================================================
/// <summary>
/// Upon successful conversion, this will return the name of the
/// new project file.
/// </summary>
public string NewProjectFilename
{
get { return newProjectFilename; }
}
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
public NewFromOtherFormatDlg()
{
InitializeComponent();
cboProjectFormat.SelectedIndex = 0;
}
#endregion
#region Event handlers
//=====================================================================
/// <summary>
/// Close the dialog without converting a project
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Select the project to convert
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnSelectProject_Click(object sender, EventArgs e)
{
using(OpenFileDialog dlg = new OpenFileDialog())
{
switch(cboProjectFormat.SelectedIndex)
{
case 1:
dlg.Title = "Select the NDoc project to convert";
dlg.Filter = "NDoc Project files (*.ndoc)|*.ndoc|" +
"All files (*.*)|*.*";
dlg.DefaultExt = "ndoc";
break;
case 2:
dlg.Title = "Select the DocProject project to convert";
dlg.Filter = "DocProject files (*.csproj, *.vbproj)|" +
"*.csproj;*.vbproj|All files (*.*)|*.*";
dlg.DefaultExt = "csproj";
break;
case 3:
dlg.Title = "Select the SandcastleGUI project to convert";
dlg.Filter = "SandcastleGUI Project files (*.SandcastleGUI)|" +
"*.SandcastleGUI|All files (*.*)|*.*";
dlg.DefaultExt = "SandcastleGUI";
break;
case 4:
dlg.Title = "Select the Microsoft Example GUI " +
"project to convert";
dlg.Filter = "Example GUI Project files (*.scproj)|" +
"*.scproj|All files (*.*)|*.*";
dlg.DefaultExt = "scproj";
break;
default:
dlg.Title = "Select the old SHFB project to convert";
dlg.Filter = "Old SHFB files (*.shfb)|*.shfb|" +
"All Files (*.*)|*.*";
dlg.DefaultExt = "shfb";
break;
}
dlg.InitialDirectory = Directory.GetCurrentDirectory();
// If selected, set the filename
if(dlg.ShowDialog() == DialogResult.OK)
txtProjectFile.Text = dlg.FileName;
}
}
/// <summary>
/// Select the folder for the new project
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnSelectNewFolder_Click(object sender, EventArgs e)
{
using(FolderBrowserDialog dlg = new FolderBrowserDialog())
{
dlg.Description = "Select the folder for the new project";
dlg.SelectedPath = Directory.GetCurrentDirectory();
// If selected, set the new folder
if(dlg.ShowDialog() == DialogResult.OK)
txtNewProjectFolder.Text = dlg.SelectedPath + @"\";
}
}
/// <summary>
/// Convert the project
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnConvert_Click(object sender, EventArgs e)
{
ConvertToMSBuildFormat converter;
string project, folder;
bool isValid = true;
epErrors.Clear();
epErrors.SetIconPadding(txtProjectFile,
btnSelectNewFolder.Width + 5);
epErrors.SetIconPadding(txtNewProjectFolder,
btnSelectNewFolder.Width + 5);
project = txtProjectFile.Text.Trim();
folder = txtNewProjectFolder.Text.Trim();
if(project.Length == 0)
{
epErrors.SetError(txtProjectFile, "A project file must " +
"be specified");
isValid = false;
}
else
if(!File.Exists(project))
{
epErrors.SetError(txtProjectFile, "The specified " +
"project file does not exist");
isValid = false;
}
if(folder.Length == 0)
{
epErrors.SetError(txtNewProjectFolder, "An output folder for " +
"the converted project must be specified");
isValid = false;
}
if(isValid)
{
project = Path.GetFullPath(project);
folder = Path.GetFullPath(folder);
if(FolderPath.TerminatePath(Path.GetDirectoryName(project)) ==
FolderPath.TerminatePath(folder))
{
epErrors.SetError(txtNewProjectFolder, "The output " +
"folder cannot match the folder of the original project");
isValid = false;
}
}
if(!isValid)
return;
try
{
this.Cursor = Cursors.WaitCursor;
switch(cboProjectFormat.SelectedIndex)
{
case 1:
converter = new ConvertFromNDoc(txtProjectFile.Text,
txtNewProjectFolder.Text);
break;
case 2:
converter = new ConvertFromDocProject(
txtProjectFile.Text, txtNewProjectFolder.Text);
break;
case 3:
converter = new ConvertFromSandcastleGui(
txtProjectFile.Text, txtNewProjectFolder.Text);
break;
case 4:
converter = new ConvertFromMSExampleGui(
txtProjectFile.Text, txtNewProjectFolder.Text);
break;
default:
converter = new ConvertFromShfbFile(txtProjectFile.Text,
txtNewProjectFolder.Text);
break;
}
newProjectFilename = converter.ConvertProject();
MessageBox.Show("The project has been converted successfully",
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Information);
this.DialogResult = DialogResult.OK;
this.Close();
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
BuilderException bex = ex as BuilderException;
if(bex != null)
MessageBox.Show("Unable to convert project. " +
"Reason: Error " + bex.ErrorCode + ":" + bex.Message,
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
else
MessageBox.Show("Unable to convert project. " +
"Reason: " + ex.Message, Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
this.Cursor = Cursors.Default;
}
}
/// <summary>
/// View help for this form
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnHelp_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
try
{
#if DEBUG
path += @"\..\..\..\Doc\Help\SandcastleBuilder.chm";
#else
path += @"\SandcastleBuilder.chm";
#endif
Form form = new Form();
form.CreateControl();
Help.ShowHelp(form, path, HelpNavigator.Topic,
"html/f68822d2-97ba-48da-a98b-46747983b4a0.htm");
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
MessageBox.Show(String.Format(CultureInfo.CurrentCulture,
"Unable to open help file '{0}'. Reason: {1}",
path, ex.Message), Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Net.Http.Headers
{
internal static class KnownHeaders
{
// If you add a new entry here, you need to add it to TryGetKnownHeader below as well.
public static readonly KnownHeader Accept = new KnownHeader("Accept", HttpHeaderType.Request, MediaTypeHeaderParser.MultipleValuesParser);
public static readonly KnownHeader AcceptCharset = new KnownHeader("Accept-Charset", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser);
public static readonly KnownHeader AcceptEncoding = new KnownHeader("Accept-Encoding", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser);
public static readonly KnownHeader AcceptLanguage = new KnownHeader("Accept-Language", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser);
public static readonly KnownHeader AcceptPatch = new KnownHeader("Accept-Patch");
public static readonly KnownHeader AcceptRanges = new KnownHeader("Accept-Ranges", HttpHeaderType.Response, GenericHeaderParser.TokenListParser);
public static readonly KnownHeader AccessControlAllowCredentials = new KnownHeader("Access-Control-Allow-Credentials");
public static readonly KnownHeader AccessControlAllowHeaders = new KnownHeader("Access-Control-Allow-Headers");
public static readonly KnownHeader AccessControlAllowMethods = new KnownHeader("Access-Control-Allow-Methods");
public static readonly KnownHeader AccessControlAllowOrigin = new KnownHeader("Access-Control-Allow-Origin");
public static readonly KnownHeader AccessControlExposeHeaders = new KnownHeader("Access-Control-Expose-Headers");
public static readonly KnownHeader AccessControlMaxAge = new KnownHeader("Access-Control-Max-Age");
public static readonly KnownHeader Age = new KnownHeader("Age", HttpHeaderType.Response, TimeSpanHeaderParser.Parser);
public static readonly KnownHeader Allow = new KnownHeader("Allow", HttpHeaderType.Content, GenericHeaderParser.TokenListParser);
public static readonly KnownHeader AltSvc = new KnownHeader("Alt-Svc");
public static readonly KnownHeader Authorization = new KnownHeader("Authorization", HttpHeaderType.Request, GenericHeaderParser.SingleValueAuthenticationParser);
public static readonly KnownHeader CacheControl = new KnownHeader("Cache-Control", HttpHeaderType.General, CacheControlHeaderParser.Parser);
public static readonly KnownHeader Connection = new KnownHeader("Connection", HttpHeaderType.General, GenericHeaderParser.TokenListParser, new string[] { "close" });
public static readonly KnownHeader ContentDisposition = new KnownHeader("Content-Disposition", HttpHeaderType.Content, GenericHeaderParser.ContentDispositionParser);
public static readonly KnownHeader ContentEncoding = new KnownHeader("Content-Encoding", HttpHeaderType.Content, GenericHeaderParser.TokenListParser, new string[] { "gzip", "deflate" });
public static readonly KnownHeader ContentLanguage = new KnownHeader("Content-Language", HttpHeaderType.Content, GenericHeaderParser.TokenListParser);
public static readonly KnownHeader ContentLength = new KnownHeader("Content-Length", HttpHeaderType.Content, Int64NumberHeaderParser.Parser);
public static readonly KnownHeader ContentLocation = new KnownHeader("Content-Location", HttpHeaderType.Content, UriHeaderParser.RelativeOrAbsoluteUriParser);
public static readonly KnownHeader ContentMD5 = new KnownHeader("Content-MD5", HttpHeaderType.Content, ByteArrayHeaderParser.Parser);
public static readonly KnownHeader ContentRange = new KnownHeader("Content-Range", HttpHeaderType.Content, GenericHeaderParser.ContentRangeParser);
public static readonly KnownHeader ContentSecurityPolicy = new KnownHeader("Content-Security-Policy");
public static readonly KnownHeader ContentType = new KnownHeader("Content-Type", HttpHeaderType.Content, MediaTypeHeaderParser.SingleValueParser);
public static readonly KnownHeader Cookie = new KnownHeader("Cookie");
public static readonly KnownHeader Cookie2 = new KnownHeader("Cookie2");
public static readonly KnownHeader Date = new KnownHeader("Date", HttpHeaderType.General, DateHeaderParser.Parser);
public static readonly KnownHeader ETag = new KnownHeader("ETag", HttpHeaderType.Response, GenericHeaderParser.SingleValueEntityTagParser);
public static readonly KnownHeader Expect = new KnownHeader("Expect", HttpHeaderType.Request, GenericHeaderParser.MultipleValueNameValueWithParametersParser, new string[] { "100-continue" });
public static readonly KnownHeader Expires = new KnownHeader("Expires", HttpHeaderType.Content, DateHeaderParser.Parser);
public static readonly KnownHeader From = new KnownHeader("From", HttpHeaderType.Request, GenericHeaderParser.MailAddressParser);
public static readonly KnownHeader Host = new KnownHeader("Host", HttpHeaderType.Request, GenericHeaderParser.HostParser);
public static readonly KnownHeader IfMatch = new KnownHeader("If-Match", HttpHeaderType.Request, GenericHeaderParser.MultipleValueEntityTagParser);
public static readonly KnownHeader IfModifiedSince = new KnownHeader("If-Modified-Since", HttpHeaderType.Request, DateHeaderParser.Parser);
public static readonly KnownHeader IfNoneMatch = new KnownHeader("If-None-Match", HttpHeaderType.Request, GenericHeaderParser.MultipleValueEntityTagParser);
public static readonly KnownHeader IfRange = new KnownHeader("If-Range", HttpHeaderType.Request, GenericHeaderParser.RangeConditionParser);
public static readonly KnownHeader IfUnmodifiedSince = new KnownHeader("If-Unmodified-Since", HttpHeaderType.Request, DateHeaderParser.Parser);
public static readonly KnownHeader KeepAlive = new KnownHeader("Keep-Alive");
public static readonly KnownHeader LastModified = new KnownHeader("Last-Modified", HttpHeaderType.Content, DateHeaderParser.Parser);
public static readonly KnownHeader Link = new KnownHeader("Link");
public static readonly KnownHeader Location = new KnownHeader("Location", HttpHeaderType.Response, UriHeaderParser.RelativeOrAbsoluteUriParser);
public static readonly KnownHeader MaxForwards = new KnownHeader("Max-Forwards", HttpHeaderType.Request, Int32NumberHeaderParser.Parser);
public static readonly KnownHeader Origin = new KnownHeader("Origin");
public static readonly KnownHeader P3P = new KnownHeader("P3P");
public static readonly KnownHeader Pragma = new KnownHeader("Pragma", HttpHeaderType.General, GenericHeaderParser.MultipleValueNameValueParser);
public static readonly KnownHeader ProxyAuthenticate = new KnownHeader("Proxy-Authenticate", HttpHeaderType.Response, GenericHeaderParser.MultipleValueAuthenticationParser);
public static readonly KnownHeader ProxyAuthorization = new KnownHeader("Proxy-Authorization", HttpHeaderType.Request, GenericHeaderParser.SingleValueAuthenticationParser);
public static readonly KnownHeader ProxyConnection = new KnownHeader("Proxy-Connection");
public static readonly KnownHeader PublicKeyPins = new KnownHeader("Public-Key-Pins");
public static readonly KnownHeader Range = new KnownHeader("Range", HttpHeaderType.Request, GenericHeaderParser.RangeParser);
public static readonly KnownHeader Referer = new KnownHeader("Referer", HttpHeaderType.Request, UriHeaderParser.RelativeOrAbsoluteUriParser); // NB: The spelling-mistake "Referer" for "Referrer" must be matched.
public static readonly KnownHeader RetryAfter = new KnownHeader("Retry-After", HttpHeaderType.Response, GenericHeaderParser.RetryConditionParser);
public static readonly KnownHeader SecWebSocketAccept = new KnownHeader("Sec-WebSocket-Accept");
public static readonly KnownHeader SecWebSocketExtensions = new KnownHeader("Sec-WebSocket-Extensions");
public static readonly KnownHeader SecWebSocketKey = new KnownHeader("Sec-WebSocket-Key");
public static readonly KnownHeader SecWebSocketProtocol = new KnownHeader("Sec-WebSocket-Protocol");
public static readonly KnownHeader SecWebSocketVersion = new KnownHeader("Sec-WebSocket-Version");
public static readonly KnownHeader Server = new KnownHeader("Server", HttpHeaderType.Response, ProductInfoHeaderParser.MultipleValueParser);
public static readonly KnownHeader SetCookie = new KnownHeader("Set-Cookie");
public static readonly KnownHeader SetCookie2 = new KnownHeader("Set-Cookie2");
public static readonly KnownHeader StrictTransportSecurity = new KnownHeader("Strict-Transport-Security");
public static readonly KnownHeader TE = new KnownHeader("TE", HttpHeaderType.Request, TransferCodingHeaderParser.MultipleValueWithQualityParser);
public static readonly KnownHeader TSV = new KnownHeader("TSV");
public static readonly KnownHeader Trailer = new KnownHeader("Trailer", HttpHeaderType.General, GenericHeaderParser.TokenListParser);
public static readonly KnownHeader TransferEncoding = new KnownHeader("Transfer-Encoding", HttpHeaderType.General, TransferCodingHeaderParser.MultipleValueParser, new string[] { "chunked" });
public static readonly KnownHeader Upgrade = new KnownHeader("Upgrade", HttpHeaderType.General, GenericHeaderParser.MultipleValueProductParser);
public static readonly KnownHeader UpgradeInsecureRequests = new KnownHeader("Upgrade-Insecure-Requests");
public static readonly KnownHeader UserAgent = new KnownHeader("User-Agent", HttpHeaderType.Request, ProductInfoHeaderParser.MultipleValueParser);
public static readonly KnownHeader Vary = new KnownHeader("Vary", HttpHeaderType.Response, GenericHeaderParser.TokenListParser);
public static readonly KnownHeader Via = new KnownHeader("Via", HttpHeaderType.General, GenericHeaderParser.MultipleValueViaParser);
public static readonly KnownHeader WWWAuthenticate = new KnownHeader("WWW-Authenticate", HttpHeaderType.Response, GenericHeaderParser.MultipleValueAuthenticationParser);
public static readonly KnownHeader Warning = new KnownHeader("Warning", HttpHeaderType.General, GenericHeaderParser.MultipleValueWarningParser);
public static readonly KnownHeader XAspNetVersion = new KnownHeader("X-AspNet-Version");
public static readonly KnownHeader XContentDuration = new KnownHeader("X-Content-Duration");
public static readonly KnownHeader XContentTypeOptions = new KnownHeader("X-Content-Type-Options");
public static readonly KnownHeader XFrameOptions = new KnownHeader("X-Frame-Options");
public static readonly KnownHeader XMSEdgeRef = new KnownHeader("X-MSEdge-Ref");
public static readonly KnownHeader XPoweredBy = new KnownHeader("X-Powered-By");
public static readonly KnownHeader XRequestID = new KnownHeader("X-Request-ID");
public static readonly KnownHeader XUACompatible = new KnownHeader("X-UA-Compatible");
// Helper interface for making GetCandidate generic over strings, utf8, etc
private interface IHeaderNameAccessor
{
int Length { get; }
char this[int index] { get; }
}
private readonly struct StringAccessor : IHeaderNameAccessor
{
private readonly string _string;
public StringAccessor(string s)
{
_string = s;
}
public int Length => _string.Length;
public char this[int index] => _string[index];
}
// Can't use Span here as it's unsupported.
private unsafe readonly struct BytePtrAccessor : IHeaderNameAccessor
{
private readonly byte* _p;
private readonly int _length;
public BytePtrAccessor(byte* p, int length)
{
_p = p;
_length = length;
}
public int Length => _length;
public char this[int index] => (char)_p[index];
}
// Find possible known header match via lookup on length and a distinguishing char for that length.
// Matching is case-insenstive.
// NOTE: Because of this, we do not preserve the case of the original header,
// whether from the wire or from the user explicitly setting a known header using a header name string.
private static KnownHeader GetCandidate<T>(T key)
where T : struct, IHeaderNameAccessor // Enforce struct for performance
{
int length = key.Length;
switch (length)
{
case 2:
return TE; // TE
case 3:
switch (key[0])
{
case 'A': case 'a': return Age; // [A]ge
case 'P': case 'p': return P3P; // [P]3P
case 'T': case 't': return TSV; // [T]SV
case 'V': case 'v': return Via; // [V]ia
}
break;
case 4:
switch (key[0])
{
case 'D': case 'd': return Date; // [D]ate
case 'E': case 'e': return ETag; // [E]Tag
case 'F': case 'f': return From; // [F]rom
case 'H': case 'h': return Host; // [H]ost
case 'L': case 'l': return Link; // [L]ink
case 'V': case 'v': return Vary; // [V]ary
}
break;
case 5:
switch (key[0])
{
case 'A': case 'a': return Allow; // [A]llow
case 'R': case 'r': return Range; // [R]ange
}
break;
case 6:
switch (key[0])
{
case 'A': case 'a': return Accept; // [A]ccept
case 'C': case 'c': return Cookie; // [C]ookie
case 'E': case 'e': return Expect; // [E]xpect
case 'O': case 'o': return Origin; // [O]rigin
case 'P': case 'p': return Pragma; // [P]ragma
case 'S': case 's': return Server; // [S]erver
}
break;
case 7:
switch (key[0])
{
case 'A': case 'a': return AltSvc; // [A]lt-Svc
case 'C': case 'c': return Cookie2; // [C]ookie2
case 'E': case 'e': return Expires; // [E]xpires
case 'R': case 'r': return Referer; // [R]eferer
case 'T': case 't': return Trailer; // [T]railer
case 'U': case 'u': return Upgrade; // [U]pgrade
case 'W': case 'w': return Warning; // [W]arning
}
break;
case 8:
switch (key[3])
{
case 'M': case 'm': return IfMatch; // If-[M]atch
case 'R': case 'r': return IfRange; // If-[R]ange
case 'A': case 'a': return Location; // Loc[a]tion
}
break;
case 10:
switch (key[0])
{
case 'C': case 'c': return Connection; // [C]onnection
case 'K': case 'k': return KeepAlive; // [K]eep-Alive
case 'S': case 's': return SetCookie; // [S]et-Cookie
case 'U': case 'u': return UserAgent; // [U]ser-Agent
}
break;
case 11:
switch (key[0])
{
case 'C': case 'c': return ContentMD5; // [C]ontent-MD5
case 'R': case 'r': return RetryAfter; // [R]etry-After
case 'S': case 's': return SetCookie2; // [S]et-Cookie2
}
break;
case 12:
switch (key[2])
{
case 'C': case 'c': return AcceptPatch; // Ac[c]ept-Patch
case 'N': case 'n': return ContentType; // Co[n]tent-Type
case 'X': case 'x': return MaxForwards; // Ma[x]-Forwards
case 'M': case 'm': return XMSEdgeRef; // X-[M]SEdge-Ref
case 'P': case 'p': return XPoweredBy; // X-[P]owered-By
case 'R': case 'r': return XRequestID; // X-[R]equest-ID
}
break;
case 13:
switch (key[6])
{
case '-': return AcceptRanges; // Accept[-]Ranges
case 'I': case 'i': return Authorization; // Author[i]zation
case 'C': case 'c': return CacheControl; // Cache-[C]ontrol
case 'T': case 't': return ContentRange; // Conten[t]-Range
case 'E': case 'e': return IfNoneMatch; // If-Non[e]-Match
case 'O': case 'o': return LastModified; // Last-M[o]dified
}
break;
case 14:
switch (key[0])
{
case 'A': case 'a': return AcceptCharset; // [A]ccept-Charset
case 'C': case 'c': return ContentLength; // [C]ontent-Length
}
break;
case 15:
switch (key[7])
{
case '-': return XFrameOptions; // X-Frame[-]Options
case 'M': case 'm': return XUACompatible; // X-UA-Co[m]patible
case 'E': case 'e': return AcceptEncoding; // Accept-[E]ncoding
case 'K': case 'k': return PublicKeyPins; // Public-[K]ey-Pins
case 'L': case 'l': return AcceptLanguage; // Accept-[L]anguage
}
break;
case 16:
switch (key[11])
{
case 'O': case 'o': return ContentEncoding; // Content-Enc[o]ding
case 'G': case 'g': return ContentLanguage; // Content-Lan[g]uage
case 'A': case 'a': return ContentLocation; // Content-Loc[a]tion
case 'C': case 'c': return ProxyConnection; // Proxy-Conne[c]tion
case 'I': case 'i': return WWWAuthenticate; // WWW-Authent[i]cate
case 'R': case 'r': return XAspNetVersion; // X-AspNet-Ve[r]sion
}
break;
case 17:
switch (key[0])
{
case 'I': case 'i': return IfModifiedSince; // [I]f-Modified-Since
case 'S': case 's': return SecWebSocketKey; // [S]ec-WebSocket-Key
case 'T': case 't': return TransferEncoding; // [T]ransfer-Encoding
}
break;
case 18:
switch (key[0])
{
case 'P': case 'p': return ProxyAuthenticate; // [P]roxy-Authenticate
case 'X': case 'x': return XContentDuration; // [X]-Content-Duration
}
break;
case 19:
switch (key[0])
{
case 'C': case 'c': return ContentDisposition; // [C]ontent-Disposition
case 'I': case 'i': return IfUnmodifiedSince; // [I]f-Unmodified-Since
case 'P': case 'p': return ProxyAuthorization; // [P]roxy-Authorization
}
break;
case 20:
return SecWebSocketAccept; // Sec-WebSocket-Accept
case 21:
return SecWebSocketVersion; // Sec-WebSocket-Version
case 22:
switch (key[0])
{
case 'A': case 'a': return AccessControlMaxAge; // [A]ccess-Control-Max-Age
case 'S': case 's': return SecWebSocketProtocol; // [S]ec-WebSocket-Protocol
case 'X': case 'x': return XContentTypeOptions; // [X]-Content-Type-Options
}
break;
case 23:
return ContentSecurityPolicy; // Content-Security-Policy
case 24:
return SecWebSocketExtensions; // Sec-WebSocket-Extensions
case 25:
switch (key[0])
{
case 'S': case 's': return StrictTransportSecurity; // [S]trict-Transport-Security
case 'U': case 'u': return UpgradeInsecureRequests; // [U]pgrade-Insecure-Requests
}
break;
case 27:
return AccessControlAllowOrigin; // Access-Control-Allow-Origin
case 28:
switch (key[21])
{
case 'H': case 'h': return AccessControlAllowHeaders; // Access-Control-Allow-[H]eaders
case 'M': case 'm': return AccessControlAllowMethods; // Access-Control-Allow-[M]ethods
}
break;
case 29:
return AccessControlExposeHeaders; // Access-Control-Expose-Headers
case 32:
return AccessControlAllowCredentials; // Access-Control-Allow-Credentials
}
return null;
}
internal static KnownHeader TryGetKnownHeader(string name)
{
KnownHeader candidate = GetCandidate(new StringAccessor(name));
if (candidate != null && StringComparer.OrdinalIgnoreCase.Equals(name, candidate.Name))
{
return candidate;
}
return null;
}
internal unsafe static KnownHeader TryGetKnownHeader(ReadOnlySpan<byte> name)
{
fixed (byte* p = &name.DangerousGetPinnableReference())
{
KnownHeader candidate = GetCandidate(new BytePtrAccessor(p, name.Length));
if (candidate != null && ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(candidate.Name, name))
{
return candidate;
}
}
return null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ReplicationStorageClassificationMappingsOperations.
/// </summary>
public static partial class ReplicationStorageClassificationMappingsOperationsExtensions
{
/// <summary>
/// Gets the details of a storage classification mapping.
/// </summary>
/// <remarks>
/// Gets the details of the specified storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
public static StorageClassificationMapping Get(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName)
{
return operations.GetAsync(fabricName, storageClassificationName, storageClassificationMappingName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the details of a storage classification mapping.
/// </summary>
/// <remarks>
/// Gets the details of the specified storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageClassificationMapping> GetAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create storage classification mapping.
/// </summary>
/// <remarks>
/// The operation to create a storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
/// <param name='pairingInput'>
/// Pairing input.
/// </param>
public static StorageClassificationMapping Create(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput pairingInput)
{
return operations.CreateAsync(fabricName, storageClassificationName, storageClassificationMappingName, pairingInput).GetAwaiter().GetResult();
}
/// <summary>
/// Create storage classification mapping.
/// </summary>
/// <remarks>
/// The operation to create a storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
/// <param name='pairingInput'>
/// Pairing input.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageClassificationMapping> CreateAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput pairingInput, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, pairingInput, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete a storage classification mapping.
/// </summary>
/// <remarks>
/// The operation to delete a storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
public static void Delete(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName)
{
operations.DeleteAsync(fabricName, storageClassificationName, storageClassificationMappingName).GetAwaiter().GetResult();
}
/// <summary>
/// Delete a storage classification mapping.
/// </summary>
/// <remarks>
/// The operation to delete a storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the list of storage classification mappings objects under a storage.
/// </summary>
/// <remarks>
/// Lists the storage classification mappings for the fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classfication name.
/// </param>
public static IPage<StorageClassificationMapping> ListByReplicationStorageClassifications(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName)
{
return operations.ListByReplicationStorageClassificationsAsync(fabricName, storageClassificationName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of storage classification mappings objects under a storage.
/// </summary>
/// <remarks>
/// Lists the storage classification mappings for the fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classfication name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<StorageClassificationMapping>> ListByReplicationStorageClassificationsAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByReplicationStorageClassificationsWithHttpMessagesAsync(fabricName, storageClassificationName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the list of storage classification mappings objects under a vault.
/// </summary>
/// <remarks>
/// Lists the storage classification mappings in the vault.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<StorageClassificationMapping> List(this IReplicationStorageClassificationMappingsOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of storage classification mappings objects under a vault.
/// </summary>
/// <remarks>
/// Lists the storage classification mappings in the vault.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<StorageClassificationMapping>> ListAsync(this IReplicationStorageClassificationMappingsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create storage classification mapping.
/// </summary>
/// <remarks>
/// The operation to create a storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
/// <param name='pairingInput'>
/// Pairing input.
/// </param>
public static StorageClassificationMapping BeginCreate(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput pairingInput)
{
return operations.BeginCreateAsync(fabricName, storageClassificationName, storageClassificationMappingName, pairingInput).GetAwaiter().GetResult();
}
/// <summary>
/// Create storage classification mapping.
/// </summary>
/// <remarks>
/// The operation to create a storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
/// <param name='pairingInput'>
/// Pairing input.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageClassificationMapping> BeginCreateAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput pairingInput, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, pairingInput, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete a storage classification mapping.
/// </summary>
/// <remarks>
/// The operation to delete a storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
public static void BeginDelete(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName)
{
operations.BeginDeleteAsync(fabricName, storageClassificationName, storageClassificationMappingName).GetAwaiter().GetResult();
}
/// <summary>
/// Delete a storage classification mapping.
/// </summary>
/// <remarks>
/// The operation to delete a storage classification mapping.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='storageClassificationName'>
/// Storage classification name.
/// </param>
/// <param name='storageClassificationMappingName'>
/// Storage classification mapping name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IReplicationStorageClassificationMappingsOperations operations, string fabricName, string storageClassificationName, string storageClassificationMappingName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(fabricName, storageClassificationName, storageClassificationMappingName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the list of storage classification mappings objects under a storage.
/// </summary>
/// <remarks>
/// Lists the storage classification mappings for the fabric.
/// </remarks>
/// <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<StorageClassificationMapping> ListByReplicationStorageClassificationsNext(this IReplicationStorageClassificationMappingsOperations operations, string nextPageLink)
{
return operations.ListByReplicationStorageClassificationsNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of storage classification mappings objects under a storage.
/// </summary>
/// <remarks>
/// Lists the storage classification mappings for the fabric.
/// </remarks>
/// <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<StorageClassificationMapping>> ListByReplicationStorageClassificationsNextAsync(this IReplicationStorageClassificationMappingsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByReplicationStorageClassificationsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the list of storage classification mappings objects under a vault.
/// </summary>
/// <remarks>
/// Lists the storage classification mappings in the vault.
/// </remarks>
/// <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<StorageClassificationMapping> ListNext(this IReplicationStorageClassificationMappingsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of storage classification mappings objects under a vault.
/// </summary>
/// <remarks>
/// Lists the storage classification mappings in the vault.
/// </remarks>
/// <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<StorageClassificationMapping>> ListNextAsync(this IReplicationStorageClassificationMappingsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private partial class CSharpCodeGenerator
{
private class ExpressionCodeGenerator : CSharpCodeGenerator
{
public ExpressionCodeGenerator(
InsertionPoint insertionPoint,
SelectionResult selectionResult,
AnalyzerResult analyzerResult) :
base(insertionPoint, selectionResult, analyzerResult)
{
}
public static bool IsExtractMethodOnExpression(SelectionResult code)
{
return code.SelectionInExpression;
}
protected override SyntaxToken CreateMethodName()
{
var methodName = "NewMethod";
var containingScope = this.CSharpSelectionResult.GetContainingScope();
methodName = GetMethodNameBasedOnExpression(methodName, containingScope);
var semanticModel = this.SemanticDocument.SemanticModel;
var nameGenerator = new UniqueNameGenerator(semanticModel);
return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(containingScope, methodName));
}
private static string GetMethodNameBasedOnExpression(string methodName, SyntaxNode expression)
{
if (expression.Parent != null &&
expression.Parent.Kind() == SyntaxKind.EqualsValueClause &&
expression.Parent.Parent != null &&
expression.Parent.Parent.Kind() == SyntaxKind.VariableDeclarator)
{
var name = ((VariableDeclaratorSyntax)expression.Parent.Parent).Identifier.ValueText;
return (name != null && name.Length > 0) ? MakeMethodName("Get", name) : methodName;
}
if (expression is MemberAccessExpressionSyntax memberAccess)
{
expression = memberAccess.Name;
}
if (expression is NameSyntax)
{
SimpleNameSyntax unqualifiedName;
switch (expression.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
unqualifiedName = (SimpleNameSyntax)expression;
break;
case SyntaxKind.QualifiedName:
unqualifiedName = ((QualifiedNameSyntax)expression).Right;
break;
case SyntaxKind.AliasQualifiedName:
unqualifiedName = ((AliasQualifiedNameSyntax)expression).Name;
break;
default:
throw new System.NotSupportedException("Unexpected name kind: " + expression.Kind().ToString());
}
var unqualifiedNameIdentifierValueText = unqualifiedName.Identifier.ValueText;
return (unqualifiedNameIdentifierValueText != null && unqualifiedNameIdentifierValueText.Length > 0) ? MakeMethodName("Get", unqualifiedNameIdentifierValueText) : methodName;
}
return methodName;
}
protected override IEnumerable<StatementSyntax> GetInitialStatementsForMethodDefinitions()
{
Contract.ThrowIfFalse(IsExtractMethodOnExpression(this.CSharpSelectionResult));
ExpressionSyntax expression = null;
// special case for array initializer
var returnType = this.AnalyzerResult.ReturnType;
var containingScope = this.CSharpSelectionResult.GetContainingScope();
if (returnType.TypeKind == TypeKind.Array && containingScope is InitializerExpressionSyntax)
{
var typeSyntax = returnType.GenerateTypeSyntax();
expression = SyntaxFactory.ArrayCreationExpression(typeSyntax as ArrayTypeSyntax, containingScope as InitializerExpressionSyntax);
}
else
{
expression = containingScope as ExpressionSyntax;
}
if (this.AnalyzerResult.HasReturnType)
{
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
SyntaxFactory.ReturnStatement(
WrapInCheckedExpressionIfNeeded(expression)));
}
else
{
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
SyntaxFactory.ExpressionStatement(
WrapInCheckedExpressionIfNeeded(expression)));
}
}
private ExpressionSyntax WrapInCheckedExpressionIfNeeded(ExpressionSyntax expression)
{
var kind = this.CSharpSelectionResult.UnderCheckedExpressionContext();
if (kind == SyntaxKind.None)
{
return expression;
}
return SyntaxFactory.CheckedExpression(kind, expression);
}
protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken)
{
var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken);
if (callSiteContainer != null)
{
return callSiteContainer;
}
else
{
return GetCallSiteContainerFromExpression();
}
}
private SyntaxNode GetCallSiteContainerFromExpression()
{
var container = this.CSharpSelectionResult.GetInnermostStatementContainer();
Contract.ThrowIfNull(container);
Contract.ThrowIfFalse(container.IsStatementContainerNode() ||
container is TypeDeclarationSyntax ||
container is ConstructorDeclarationSyntax ||
container is CompilationUnitSyntax);
return container;
}
protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite()
{
var scope = (SyntaxNode)this.CSharpSelectionResult.GetContainingScopeOf<StatementSyntax>();
if (scope == null)
{
scope = this.CSharpSelectionResult.GetContainingScopeOf<FieldDeclarationSyntax>();
}
if (scope == null)
{
scope = this.CSharpSelectionResult.GetContainingScopeOf<ConstructorInitializerSyntax>();
}
if (scope == null)
{
// This is similar to FieldDeclaration case but we only want to do this
// if the member has an expression body.
scope = this.CSharpSelectionResult.GetContainingScopeOf<ArrowExpressionClauseSyntax>().Parent;
}
return scope;
}
protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite()
=> GetFirstStatementOrInitializerSelectedAtCallSite();
protected override async Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(
SyntaxAnnotation callSiteAnnotation, CancellationToken cancellationToken)
{
var enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite();
var callSignature = CreateCallSignature().WithAdditionalAnnotations(callSiteAnnotation);
var invocation = callSignature.IsKind(SyntaxKind.AwaitExpression) ? ((AwaitExpressionSyntax)callSignature).Expression : callSignature;
var sourceNode = this.CSharpSelectionResult.GetContainingScope();
Contract.ThrowIfTrue(
sourceNode.Parent is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)sourceNode.Parent).Name == sourceNode,
"invalid scope. given scope is not an expression");
// To lower the chances that replacing sourceNode with callSignature will break the user's
// code, we make the enclosing statement semantically explicit. This ends up being a little
// bit more work because we need to annotate the sourceNode so that we can get back to it
// after rewriting the enclosing statement.
var updatedDocument = this.SemanticDocument.Document;
var sourceNodeAnnotation = new SyntaxAnnotation();
var enclosingStatementAnnotation = new SyntaxAnnotation();
var newEnclosingStatement = enclosingStatement
.ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation))
.WithAdditionalAnnotations(enclosingStatementAnnotation);
updatedDocument = await updatedDocument.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(false);
var updatedRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
newEnclosingStatement = updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode();
// because of the complexification we cannot guarantee that there is only one annotation.
// however complexification of names is prepended, so the last annotation should be the original one.
sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode();
// we want to replace the old identifier with a invocation expression, but because of MakeExplicit we might have
// a member access now instead of the identifier. So more syntax fiddling is needed.
if (sourceNode.Parent.Kind() == SyntaxKind.SimpleMemberAccessExpression &&
((ExpressionSyntax)sourceNode).IsRightSideOfDot())
{
var explicitMemberAccess = (MemberAccessExpressionSyntax)sourceNode.Parent;
var replacementMemberAccess = explicitMemberAccess.CopyAnnotationsTo(
SyntaxFactory.MemberAccessExpression(
sourceNode.Parent.Kind(),
explicitMemberAccess.Expression,
(SimpleNameSyntax)((InvocationExpressionSyntax)invocation).Expression));
var newInvocation = SyntaxFactory.InvocationExpression(
replacementMemberAccess,
((InvocationExpressionSyntax)invocation).ArgumentList);
var newCallSignature = callSignature != invocation ?
callSignature.ReplaceNode(invocation, newInvocation) : invocation.CopyAnnotationsTo(newInvocation);
sourceNode = sourceNode.Parent;
callSignature = newCallSignature;
}
return newEnclosingStatement.ReplaceNode(sourceNode, callSignature);
}
}
}
}
}
| |
// 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 SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
internal class WinHttpAuthHelper
{
// TODO: Issue #2165. This looks messy but it is fast. Research a cleaner way
// to do this which keeps high performance lookup.
//
// Fast lookup table to convert WINHTTP_AUTH constants to strings.
// WINHTTP_AUTH_SCHEME_BASIC = 0x00000001;
// WINHTTP_AUTH_SCHEME_NTLM = 0x00000002;
// WINHTTP_AUTH_SCHEME_DIGEST = 0x00000008;
// WINHTTP_AUTH_SCHEME_NEGOTIATE = 0x00000010;
private static readonly string[] s_authSchemeStringMapping =
{
null,
"Basic",
"NTLM",
null,
null,
null,
null,
null,
"Digest",
null,
null,
null,
null,
null,
null,
null,
"Negotiate"
};
private static readonly uint[] s_authSchemePriorityOrder =
{
Interop.WinHttp.WINHTTP_AUTH_SCHEME_NEGOTIATE,
Interop.WinHttp.WINHTTP_AUTH_SCHEME_NTLM,
Interop.WinHttp.WINHTTP_AUTH_SCHEME_DIGEST,
Interop.WinHttp.WINHTTP_AUTH_SCHEME_BASIC
};
// TODO: Issue #2165. This current design uses a handler-wide lock to Add/Retrieve
// from the cache. Need to improve this for next iteration in order
// to boost performance and scalability.
private readonly CredentialCache _credentialCache = new CredentialCache();
private readonly object _credentialCacheLock = new object();
public void CheckResponseForAuthentication(
WinHttpRequestState state,
ref uint proxyAuthScheme,
ref uint serverAuthScheme)
{
uint supportedSchemes = 0;
uint firstSchemeIgnored = 0;
uint authTarget = 0;
Uri uri = state.RequestMessage.RequestUri;
state.RetryRequest = false;
// Check the status code and retry the request applying credentials if needed.
var statusCode = (HttpStatusCode)WinHttpResponseParser.GetResponseHeaderNumberInfo(
state.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE);
switch (statusCode)
{
case HttpStatusCode.Unauthorized:
if (state.ServerCredentials == null || state.LastStatusCode == HttpStatusCode.Unauthorized)
{
// Either we don't have server credentials or we already tried
// to set the credentials and it failed before.
// So we will let the 401 be the final status code returned.
break;
}
state.LastStatusCode = statusCode;
// Determine authorization scheme to use. We ignore the firstScheme
// parameter which is included in the supportedSchemes flags already.
// We pass the schemes to ChooseAuthScheme which will pick the scheme
// based on most secure scheme to least secure scheme ordering.
if (!Interop.WinHttp.WinHttpQueryAuthSchemes(
state.RequestHandle,
out supportedSchemes,
out firstSchemeIgnored,
out authTarget))
{
// WinHTTP returns an error for schemes it doesn't handle.
// So, we need to ignore the error and just let it stay at 401.
break;
}
// WinHTTP returns the proper authTarget based on the status code (401, 407).
// But we can validate with assert.
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
serverAuthScheme = ChooseAuthScheme(supportedSchemes, state.RequestMessage.RequestUri, state.ServerCredentials);
if (serverAuthScheme != 0)
{
if (SetWinHttpCredential(
state.RequestHandle,
state.ServerCredentials,
uri,
serverAuthScheme,
authTarget))
{
state.RetryRequest = true;
}
}
break;
case HttpStatusCode.ProxyAuthenticationRequired:
if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
// We tried already to set the credentials.
break;
}
state.LastStatusCode = statusCode;
// If we don't have any proxy credentials to try, then we end up with 407.
ICredentials proxyCreds = state.Proxy == null ?
state.DefaultProxyCredentials :
state.Proxy.Credentials;
if (proxyCreds == null)
{
break;
}
// Determine authorization scheme to use. We ignore the firstScheme
// parameter which is included in the supportedSchemes flags already.
// We pass the schemes to ChooseAuthScheme which will pick the scheme
// based on most secure scheme to least secure scheme ordering.
if (!Interop.WinHttp.WinHttpQueryAuthSchemes(
state.RequestHandle,
out supportedSchemes,
out firstSchemeIgnored,
out authTarget))
{
// WinHTTP returns an error for schemes it doesn't handle.
// So, we need to ignore the error and just let it stay at 407.
break;
}
// WinHTTP returns the proper authTarget based on the status code (401, 407).
// But we can validate with assert.
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY);
proxyAuthScheme = ChooseAuthScheme(
supportedSchemes,
// TODO: Issue #6997. If Proxy==null, we're using the system proxy which is possibly
// discovered/calculated with a PAC file. So, we can't determine the actual proxy uri at
// this point since it is calculated internally in WinHTTP. For now, pass in null for the uri.
state.Proxy?.GetProxy(state.RequestMessage.RequestUri),
proxyCreds);
state.RetryRequest = true;
break;
default:
if (state.PreAuthenticate && serverAuthScheme != 0)
{
SaveServerCredentialsToCache(uri, serverAuthScheme, state.ServerCredentials);
}
break;
}
}
public void PreAuthenticateRequest(WinHttpRequestState state, uint proxyAuthScheme)
{
// Set proxy credentials if we have them.
// If a proxy authentication challenge was responded to, reset
// those credentials before each SendRequest, because the proxy
// may require re-authentication after responding to a 401 or
// to a redirect. If you don't, you can get into a
// 407-401-407-401- loop.
if (proxyAuthScheme != 0)
{
ICredentials proxyCredentials;
Uri proxyUri;
if (state.Proxy != null)
{
proxyCredentials = state.Proxy.Credentials;
proxyUri = state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
else
{
proxyCredentials = state.DefaultProxyCredentials;
proxyUri = state.RequestMessage.RequestUri;
}
SetWinHttpCredential(
state.RequestHandle,
proxyCredentials,
proxyUri,
proxyAuthScheme,
Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY);
}
// Apply pre-authentication headers for server authentication?
if (state.PreAuthenticate)
{
uint authScheme;
NetworkCredential serverCredentials;
if (GetServerCredentialsFromCache(
state.RequestMessage.RequestUri,
out authScheme,
out serverCredentials))
{
SetWinHttpCredential(
state.RequestHandle,
serverCredentials,
state.RequestMessage.RequestUri,
authScheme,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
state.LastStatusCode = HttpStatusCode.Unauthorized; // Remember we already set the creds.
}
// No cached credential to use at this time. The request will first go out with no
// 'Authorization' header. Later, if a 401 occurs, we will be able to cache the credential
// since we will then know the proper auth scheme to use.
//
// TODO: Issue #2165. Adding logging to highlight the 'cache miss'.
}
}
// TODO: Issue #2165. Consider refactoring cache logic in separate class and avoid out parameters.
public bool GetServerCredentialsFromCache(
Uri uri,
out uint serverAuthScheme,
out NetworkCredential serverCredentials)
{
serverAuthScheme = 0;
serverCredentials = null;
NetworkCredential cred = null;
lock (_credentialCacheLock)
{
foreach (uint authScheme in s_authSchemePriorityOrder)
{
cred = _credentialCache.GetCredential(uri, s_authSchemeStringMapping[authScheme]);
if (cred != null)
{
serverAuthScheme = authScheme;
serverCredentials = cred;
return true;
}
}
}
return false;
}
public void SaveServerCredentialsToCache(Uri uri, uint authScheme, ICredentials serverCredentials)
{
string authType = s_authSchemeStringMapping[authScheme];
Debug.Assert(!string.IsNullOrEmpty(authType));
NetworkCredential cred = serverCredentials.GetCredential(uri, authType);
if (cred != null)
{
lock (_credentialCacheLock)
{
try
{
_credentialCache.Add(uri, authType, cred);
}
catch (ArgumentException)
{
// The credential was already added.
}
}
}
}
public void ChangeDefaultCredentialsPolicy(
SafeWinHttpHandle requestHandle,
uint authTarget,
bool allowDefaultCredentials)
{
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY ||
authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
uint optionData = allowDefaultCredentials ?
(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY ?
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM :
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW) :
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
if (!Interop.WinHttp.WinHttpSetOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_AUTOLOGON_POLICY,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetOption));
}
}
private bool SetWinHttpCredential(
SafeWinHttpHandle requestHandle,
ICredentials credentials,
Uri uri,
uint authScheme,
uint authTarget)
{
string userName;
string password;
Debug.Assert(credentials != null);
Debug.Assert(authScheme != 0);
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY ||
authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
NetworkCredential networkCredential = credentials.GetCredential(uri, s_authSchemeStringMapping[authScheme]);
if (networkCredential == null)
{
return false;
}
if (networkCredential == CredentialCache.DefaultNetworkCredentials)
{
// Only Negotiate and NTLM can use default credentials. Otherwise,
// behave as-if there were no credentials.
if (authScheme == Interop.WinHttp.WINHTTP_AUTH_SCHEME_NEGOTIATE ||
authScheme == Interop.WinHttp.WINHTTP_AUTH_SCHEME_NTLM)
{
// Allow WinHTTP to transmit the default credentials.
ChangeDefaultCredentialsPolicy(requestHandle, authTarget, allowDefaultCredentials:true);
userName = null;
password = null;
}
else
{
return false;
}
}
else
{
userName = networkCredential.UserName;
password = networkCredential.Password;
string domain = networkCredential.Domain;
// WinHTTP does not support a blank username. So, we will throw an exception.
if (string.IsNullOrEmpty(userName))
{
throw new InvalidOperationException(SR.net_http_username_empty_string);
}
if (!string.IsNullOrEmpty(domain))
{
userName = domain + "\\" + userName;
}
}
if (!Interop.WinHttp.WinHttpSetCredentials(
requestHandle,
authTarget,
authScheme,
userName,
password,
IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError(nameof(Interop.WinHttp.WinHttpSetCredentials));
}
return true;
}
private static uint ChooseAuthScheme(uint supportedSchemes, Uri uri, ICredentials credentials)
{
if (credentials == null)
{
return 0;
}
if (uri == null && !(credentials is NetworkCredential))
{
// TODO: Issue #6997.
// If the credentials are a NetworkCredential, the uri isn't used when calling .GetCredential() since
// it will work against all uri's. Otherwise, credentials is probably a CredentialCache and passing in
// null for a uri is invalid.
return 0;
}
foreach (uint authScheme in s_authSchemePriorityOrder)
{
if ((supportedSchemes & authScheme) != 0 && credentials.GetCredential(uri, s_authSchemeStringMapping[authScheme]) != null)
{
return authScheme;
}
}
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using AonWeb.FluentHttp.Caching;
using AonWeb.FluentHttp.Helpers;
using AonWeb.FluentHttp.Settings;
namespace AonWeb.FluentHttp.Handlers.Caching
{
// this class is inspired by the excellent work in CacheCow Caching libraries - https://github.com/aliostad/CacheCow
// for whatever reason, I couldn't get the inmemory cache in the HttpClientHandler / HttpCacheConfigurationHandler
// to play nice with call / client builders, and the cache kept disappearing
// additionally I need an implementation that allows for deserialized object level caching in addition to http response caching
// so I implemented a cachehandler that plugs in to the TypedBuilder higher up,
// but the base logic for cache validation / invalidation was based off CacheCow
public abstract class CacheConfigurationHandlerCore
{
protected readonly ICacheManager _cacheManager;
protected CacheConfigurationHandlerCore(ICacheSettings settings, ICacheManager cacheManager)
{
Enabled = true;
_cacheManager = cacheManager;
Settings = settings;
}
public ICacheSettings Settings { get; }
#region IHandler<HandlerType> Implementation
public bool Enabled { get; set; }
public HandlerPriority GetPriority(HandlerType type)
{
if (type == HandlerType.Sending)
return HandlerPriority.First;
if (type == HandlerType.Sent)
return HandlerPriority.Last;
return HandlerPriority.Default;
}
#endregion
protected ICacheContext GetContext(IHandlerContext handlerContext)
{
var context = handlerContext.Items["CacheContext"] as ICacheContext;
if (context == null)
{
context = new CacheContext(Settings, handlerContext);
handlerContext.Items["CacheContext"] = context;
}
return context;
}
protected async Task TryGetFromCache(IHandlerContextWithResult handlerContext)
{
if (!Enabled)
return;
var context = GetContext(handlerContext);
var requestValidation = context.RequestValidator(context);
if (requestValidation != RequestValidationResult.OK)
{
await ExpireResult(context, requestValidation);
return;
}
var result = await _cacheManager.Get(context);
var responseValidation = ResponseValidationResult.NotExist;
if (!result.IsEmpty)
{
context.ResultInspector?.Invoke(result);
responseValidation = context.ResponseValidator(context, result.Metadata);
}
// TODO: Determine the need for conditional put - if so, that logic would go here
if (responseValidation == ResponseValidationResult.Stale && !context.AllowStaleResultValidator(context, result.Metadata))
responseValidation = ResponseValidationResult.MustRevalidate;
if (responseValidation == ResponseValidationResult.MustRevalidate && context.Request != null)
{
if (result.Metadata.ETag != null)
context.Request.Headers.Add("If-None-Match", result.Metadata.ETag);
else if (result.Metadata.LastModified != null)
context.Request.Headers.Add("If-Modified-Since", result.Metadata.LastModified.Value.ToString("r"));
//hang on to this we are going to need it in a sec. We could try to get it from cache store, but it may have expired by then
context.Items["CacheHandlerCachedItem"] = result;
return;
}
if (result.IsEmpty)
{
var missedResult = await context.HandlerRegister.OnMiss(context);
if (missedResult.IsDirty)
{
result = new CacheEntry(missedResult.Value, null);
}
}
if (!result.IsEmpty)
{
var hitResult = await context.HandlerRegister.OnHit(context, result.Value);
if (!hitResult.IsDirty || !(bool)hitResult.Value)
handlerContext.Result = result.Value;
}
context.Items["CacheHandlerCachedItem"] = result;
}
protected async Task TryGetRevalidatedResult(IHandlerContextWithResult handlerContext, HttpRequestMessage request, HttpResponseMessage response)
{
if (!Enabled)
return;
var context = GetContext(handlerContext);
var result = (CacheEntry)context.Items["CacheHandlerCachedItem"];
var meta = CachingHelpers.CreateResponseMetadata(result, request, response, context);
if (result == null || !context.RevalidateValidator(context, meta))
return;
if (!result.IsEmpty && result.Value != null)
{
result.UpdateResponseMetadata(request, response, context);
context.ResultInspector?.Invoke(result);
}
else
{
result = CacheEntry.Empty;
}
if (result.IsEmpty)
{
var missedResult = await context.HandlerRegister.OnMiss(context);
if (missedResult.IsDirty)
{
result = new CacheEntry(missedResult.Value, null);
}
}
if (!result.IsEmpty)
{
var hitResult = await context.HandlerRegister.OnHit(context, result.Value);
if (hitResult.IsDirty && !(bool)hitResult.Value)
handlerContext.Result = result.Value;
}
context.Items["CacheHandlerCachedItem"] = result;
}
protected async Task TryCacheResult(IHandlerContext handlerContext, object result, HttpRequestMessage request, HttpResponseMessage response)
{
if (!Enabled)
return;
var context = GetContext(handlerContext);
var cacheEntry = new CacheEntry(result, request, response, context);
var requestValidation = context.RequestValidator(context);
if (requestValidation == RequestValidationResult.OK)
{
var validationResult = context.ResponseValidator(context, cacheEntry.Metadata);
if (validationResult == ResponseValidationResult.OK
|| validationResult == ResponseValidationResult.MustRevalidate)
{
await _cacheManager.Put(context, cacheEntry);
}
await context.HandlerRegister.OnStore(context, cacheEntry.Value);
}
else
{
await ExpireResult(context, requestValidation);
}
}
protected Task ExpireResult(IHandlerContext handlerContext, RequestValidationResult reason)
{
var context = GetContext(handlerContext);
return ExpireResult(context, reason);
}
private async Task ExpireResult(ICacheContext context, RequestValidationResult reason)
{
if (!Enabled)
return;
if ((context.Items["CacheHandler_ItemExpired"] as bool?).GetValueOrDefault())
return;
var expiringResult = await context.HandlerRegister.OnExpiring(context, reason);
var uris = await _cacheManager.Delete(context, expiringResult.Value as IEnumerable<Uri>);
await context.HandlerRegister.OnExpired(context, reason, new ReadOnlyCollection<Uri>(uris));
context.Items["CacheHandler_ItemExpired"] = true;
}
}
}
| |
// <copyright file="HttpCommandExecutor.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Provides a way of executing Commands over HTTP
/// </summary>
public class HttpCommandExecutor : ICommandExecutor
{
private const string JsonMimeType = "application/json";
private const string PngMimeType = "image/png";
private const string Utf8CharsetType = "utf-8";
private const string RequestAcceptHeader = JsonMimeType + ", " + PngMimeType;
private const string UserAgentHeaderTemplate = "selenium/{0} (.net {1})";
private Uri remoteServerUri;
private TimeSpan serverResponseTimeout;
private bool enableKeepAlive;
private bool isDisposed;
private IWebProxy proxy;
private CommandInfoRepository commandInfoRepository = new W3CWireProtocolCommandInfoRepository();
private HttpClient client;
/// <summary>
/// Initializes a new instance of the <see cref="HttpCommandExecutor"/> class
/// </summary>
/// <param name="addressOfRemoteServer">Address of the WebDriver Server</param>
/// <param name="timeout">The timeout within which the server must respond.</param>
public HttpCommandExecutor(Uri addressOfRemoteServer, TimeSpan timeout)
: this(addressOfRemoteServer, timeout, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpCommandExecutor"/> class
/// </summary>
/// <param name="addressOfRemoteServer">Address of the WebDriver Server</param>
/// <param name="timeout">The timeout within which the server must respond.</param>
/// <param name="enableKeepAlive"><see langword="true"/> if the KeepAlive header should be sent
/// with HTTP requests; otherwise, <see langword="false"/>.</param>
public HttpCommandExecutor(Uri addressOfRemoteServer, TimeSpan timeout, bool enableKeepAlive)
{
if (addressOfRemoteServer == null)
{
throw new ArgumentNullException("addressOfRemoteServer", "You must specify a remote address to connect to");
}
if (!addressOfRemoteServer.AbsoluteUri.EndsWith("/", StringComparison.OrdinalIgnoreCase))
{
addressOfRemoteServer = new Uri(addressOfRemoteServer.ToString() + "/");
}
this.remoteServerUri = addressOfRemoteServer;
this.serverResponseTimeout = timeout;
this.enableKeepAlive = enableKeepAlive;
}
/// <summary>
/// Occurs when the <see cref="HttpCommandExecutor"/> is sending an HTTP
/// request to the remote end WebDriver implementation.
/// </summary>
public event EventHandler<SendingRemoteHttpRequestEventArgs> SendingRemoteHttpRequest;
/// <summary>
/// Gets the repository of objects containin information about commands.
/// </summary>
public CommandInfoRepository CommandInfoRepository
{
get { return this.commandInfoRepository; }
protected set { this.commandInfoRepository = value; }
}
/// <summary>
/// Gets or sets an <see cref="IWebProxy"/> object to be used to proxy requests
/// between this <see cref="HttpCommandExecutor"/> and the remote end WebDriver
/// implementation.
/// </summary>
public IWebProxy Proxy
{
get { return this.proxy; }
set { this.proxy = value; }
}
/// <summary>
/// Gets or sets a value indicating whether keep-alive is enabled for HTTP
/// communication between this <see cref="HttpCommandExecutor"/> and the
/// remote end WebDriver implementation.
/// </summary>
public bool IsKeepAliveEnabled
{
get { return this.enableKeepAlive; }
set { this.enableKeepAlive = value; }
}
/// <summary>
/// Executes a command
/// </summary>
/// <param name="commandToExecute">The command you wish to execute</param>
/// <returns>A response from the browser</returns>
public virtual Response Execute(Command commandToExecute)
{
if (commandToExecute == null)
{
throw new ArgumentNullException("commandToExecute", "commandToExecute cannot be null");
}
CommandInfo info = this.commandInfoRepository.GetCommandInfo(commandToExecute.Name);
if (info == null)
{
throw new NotImplementedException(string.Format("The command you are attempting to execute, {0}, does not exist in the protocol dialect used by the remote end.", commandToExecute.Name));
}
if (this.client == null)
{
this.CreateHttpClient();
}
HttpRequestInfo requestInfo = new HttpRequestInfo(this.remoteServerUri, commandToExecute, info);
HttpResponseInfo responseInfo = null;
try
{
responseInfo = this.MakeHttpRequest(requestInfo).GetAwaiter().GetResult();
}
catch (HttpRequestException ex)
{
WebException innerWebException = ex.InnerException as WebException;
if (innerWebException != null)
{
if (innerWebException.Status == WebExceptionStatus.Timeout)
{
string timeoutMessage = "The HTTP request to the remote WebDriver server for URL {0} timed out after {1} seconds.";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, timeoutMessage, requestInfo.FullUri.AbsoluteUri, this.serverResponseTimeout.TotalSeconds), ex);
}
else if (innerWebException.Status == WebExceptionStatus.ConnectFailure)
{
string connectFailureMessage = "Could not connect to the remote WebDriver server for URL {0}.";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, connectFailureMessage, requestInfo.FullUri.AbsoluteUri, this.serverResponseTimeout.TotalSeconds), ex);
}
else if (innerWebException.Response == null)
{
string nullResponseMessage = "A exception with a null response was thrown sending an HTTP request to the remote WebDriver server for URL {0}. The status of the exception was {1}, and the message was: {2}";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, nullResponseMessage, requestInfo.FullUri.AbsoluteUri, innerWebException.Status, innerWebException.Message), innerWebException);
}
}
string unknownErrorMessage = "An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL {0}. The exception message was: {1}";
throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, unknownErrorMessage, requestInfo.FullUri.AbsoluteUri, ex.Message), ex);
}
Response toReturn = this.CreateResponse(responseInfo);
return toReturn;
}
/// <summary>
/// Raises the <see cref="SendingRemoteHttpRequest"/> event.
/// </summary>
/// <param name="eventArgs">A <see cref="SendingRemoteHttpRequestEventArgs"/> that contains the event data.</param>
protected virtual void OnSendingRemoteHttpRequest(SendingRemoteHttpRequestEventArgs eventArgs)
{
if (eventArgs == null)
{
throw new ArgumentNullException("eventArgs", "eventArgs must not be null");
}
if (this.SendingRemoteHttpRequest != null)
{
this.SendingRemoteHttpRequest(this, eventArgs);
}
}
private void CreateHttpClient()
{
HttpClientHandler httpClientHandler = new HttpClientHandler();
string userInfo = this.remoteServerUri.UserInfo;
if (!string.IsNullOrEmpty(userInfo) && userInfo.Contains(":"))
{
string[] userInfoComponents = this.remoteServerUri.UserInfo.Split(new char[] { ':' }, 2);
httpClientHandler.Credentials = new NetworkCredential(userInfoComponents[0], userInfoComponents[1]);
httpClientHandler.PreAuthenticate = true;
}
httpClientHandler.Proxy = this.Proxy;
// httpClientHandler.MaxConnectionsPerServer = 2000;
this.client = new HttpClient(httpClientHandler);
string userAgentString = string.Format(CultureInfo.InvariantCulture, UserAgentHeaderTemplate, ResourceUtilities.AssemblyVersion, ResourceUtilities.PlatformFamily);
this.client.DefaultRequestHeaders.UserAgent.ParseAdd(userAgentString);
this.client.DefaultRequestHeaders.Accept.ParseAdd(RequestAcceptHeader);
if (!this.IsKeepAliveEnabled)
{
this.client.DefaultRequestHeaders.Connection.ParseAdd("close");
}
this.client.Timeout = this.serverResponseTimeout;
}
private async Task<HttpResponseInfo> MakeHttpRequest(HttpRequestInfo requestInfo)
{
SendingRemoteHttpRequestEventArgs eventArgs = new SendingRemoteHttpRequestEventArgs(null, requestInfo.RequestBody);
this.OnSendingRemoteHttpRequest(eventArgs);
HttpMethod method = new HttpMethod(requestInfo.HttpMethod);
HttpRequestMessage requestMessage = new HttpRequestMessage(method, requestInfo.FullUri);
if (requestInfo.HttpMethod == CommandInfo.GetCommand)
{
CacheControlHeaderValue cacheControlHeader = new CacheControlHeaderValue();
cacheControlHeader.NoCache = true;
requestMessage.Headers.CacheControl = cacheControlHeader;
}
if (requestInfo.HttpMethod == CommandInfo.PostCommand)
{
MediaTypeWithQualityHeaderValue acceptHeader = new MediaTypeWithQualityHeaderValue(JsonMimeType);
acceptHeader.CharSet = Utf8CharsetType;
requestMessage.Headers.Accept.Add(acceptHeader);
byte[] bytes = Encoding.UTF8.GetBytes(eventArgs.RequestBody);
requestMessage.Content = new ByteArrayContent(bytes, 0, bytes.Length);
}
HttpResponseMessage responseMessage = await this.client.SendAsync(requestMessage);
HttpResponseInfo httpResponseInfo = new HttpResponseInfo();
httpResponseInfo.Body = await responseMessage.Content.ReadAsStringAsync();
httpResponseInfo.ContentType = responseMessage.Content.Headers.ContentType.ToString();
httpResponseInfo.StatusCode = responseMessage.StatusCode;
return httpResponseInfo;
}
private Response CreateResponse(HttpResponseInfo responseInfo)
{
Response response = new Response();
string body = responseInfo.Body;
if (responseInfo.ContentType != null && responseInfo.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
response = Response.FromJson(body);
}
else
{
response.Value = body;
}
if (this.CommandInfoRepository.SpecificationLevel < 1 && (responseInfo.StatusCode < HttpStatusCode.OK || responseInfo.StatusCode >= HttpStatusCode.BadRequest))
{
if (responseInfo.StatusCode >= HttpStatusCode.BadRequest && responseInfo.StatusCode < HttpStatusCode.InternalServerError)
{
response.Status = WebDriverResult.UnhandledError;
}
else if (responseInfo.StatusCode >= HttpStatusCode.InternalServerError)
{
if (responseInfo.StatusCode == HttpStatusCode.NotImplemented)
{
response.Status = WebDriverResult.UnknownCommand;
}
else if (response.Status == WebDriverResult.Success)
{
response.Status = WebDriverResult.UnhandledError;
}
}
else
{
response.Status = WebDriverResult.UnhandledError;
}
}
if (response.Value is string)
{
response.Value = ((string)response.Value).Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
}
return response;
}
/// <summary>
/// Releases all resources used by the <see cref="HttpCommandExecutor"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="HttpCommandExecutor"/> and
/// optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release managed and resources;
/// <see langword="false"/> to only release unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (this.client != null)
{
this.client.Dispose();
}
this.isDisposed = true;
}
}
private class HttpRequestInfo
{
public HttpRequestInfo(Uri serverUri, Command commandToExecute, CommandInfo commandInfo)
{
this.FullUri = commandInfo.CreateCommandUri(serverUri, commandToExecute);
this.HttpMethod = commandInfo.Method;
this.RequestBody = commandToExecute.ParametersAsJsonString;
}
public Uri FullUri { get; set; }
public string HttpMethod { get; set; }
public string RequestBody { get; set; }
}
private class HttpResponseInfo
{
public HttpStatusCode StatusCode { get; set; }
public string Body { get; set; }
public string ContentType { get; set; }
}
}
}
| |
--- /dev/null 2016-08-04 17:45:37.000000000 -0400
+++ src/System.Xml.XPath/src/SR.cs 2016-08-04 17:50:08.918579000 -0400
@@ -0,0 +1,558 @@
+using System;
+using System.Resources;
+
+namespace FxResources.System.Xml.XPath
+{
+ internal static class SR
+ {
+
+ }
+}
+
+namespace System
+{
+ internal static class SR
+ {
+ private static ResourceManager s_resourceManager;
+
+ private const String s_resourcesName = "FxResources.System.Xml.XPath.SR";
+
+ private static ResourceManager ResourceManager
+ {
+ get
+ {
+ if (SR.s_resourceManager == null)
+ {
+ SR.s_resourceManager = new ResourceManager(SR.ResourceType);
+ }
+ return SR.s_resourceManager;
+ }
+ }
+
+ internal static Type ResourceType
+ {
+ get
+ {
+ return typeof(FxResources.System.Xml.XPath.SR);
+ }
+ }
+
+ internal static String Sch_EnumFinished
+ {
+ get
+ {
+ return SR.GetResourceString("Sch_EnumFinished", null);
+ }
+ }
+
+ internal static String Sch_EnumNotStarted
+ {
+ get
+ {
+ return SR.GetResourceString("Sch_EnumNotStarted", null);
+ }
+ }
+
+ internal static String Sch_XsdDateTimeCompare
+ {
+ get
+ {
+ return SR.GetResourceString("Sch_XsdDateTimeCompare", null);
+ }
+ }
+
+ internal static String Xdom_Empty_LocalName
+ {
+ get
+ {
+ return SR.GetResourceString("Xdom_Empty_LocalName", null);
+ }
+ }
+
+ internal static String Xml_BadNameChar
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_BadNameChar", null);
+ }
+ }
+
+ internal static String Xml_BadStartNameChar
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_BadStartNameChar", null);
+ }
+ }
+
+ internal static String Xml_EmptyName
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_EmptyName", null);
+ }
+ }
+
+ internal static String Xml_ErrorPosition
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_ErrorPosition", null);
+ }
+ }
+
+ internal static String Xml_InvalidBase64Value
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidBase64Value", null);
+ }
+ }
+
+ internal static String Xml_InvalidBinHexValue
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidBinHexValue", null);
+ }
+ }
+
+ internal static String Xml_InvalidBinHexValueOddCount
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidBinHexValueOddCount", null);
+ }
+ }
+
+ internal static String Xml_InvalidCharacter
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidCharacter", null);
+ }
+ }
+
+ internal static String Xml_InvalidNodeType
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidNodeType", null);
+ }
+ }
+
+ internal static String Xml_InvalidOperation
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidOperation", null);
+ }
+ }
+
+ internal static String Xml_InvalidPIName
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidPIName", null);
+ }
+ }
+
+ internal static String Xml_InvalidReadContentAs
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidReadContentAs", null);
+ }
+ }
+
+ internal static String Xml_InvalidReadElementContentAs
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidReadElementContentAs", null);
+ }
+ }
+
+ internal static String Xml_InvalidSurrogateHighChar
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidSurrogateHighChar", null);
+ }
+ }
+
+ internal static String Xml_InvalidSurrogateMissingLowChar
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidSurrogateMissingLowChar", null);
+ }
+ }
+
+ internal static String Xml_InvalidSurrogatePairWithArgs
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_InvalidSurrogatePairWithArgs", null);
+ }
+ }
+
+ internal static String Xml_MessageWithErrorPosition
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_MessageWithErrorPosition", null);
+ }
+ }
+
+ internal static String Xml_MixingBinaryContentMethods
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_MixingBinaryContentMethods", null);
+ }
+ }
+
+ internal static String Xml_NamespaceDeclXmlXmlns
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_NamespaceDeclXmlXmlns", null);
+ }
+ }
+
+ internal static String Xml_PrefixForEmptyNs
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_PrefixForEmptyNs", null);
+ }
+ }
+
+ internal static String Xml_UnknownResourceString
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_UnknownResourceString", null);
+ }
+ }
+
+ internal static String Xml_XmlnsPrefix
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_XmlnsPrefix", null);
+ }
+ }
+
+ internal static String Xml_XmlPrefix
+ {
+ get
+ {
+ return SR.GetResourceString("Xml_XmlPrefix", null);
+ }
+ }
+
+ internal static String XmlBadName
+ {
+ get
+ {
+ return SR.GetResourceString("XmlBadName", null);
+ }
+ }
+
+ internal static String XmlConvert_BadFormat
+ {
+ get
+ {
+ return SR.GetResourceString("XmlConvert_BadFormat", null);
+ }
+ }
+
+ internal static String XmlConvert_Overflow
+ {
+ get
+ {
+ return SR.GetResourceString("XmlConvert_Overflow", null);
+ }
+ }
+
+ internal static String XmlConvert_TypeFromString
+ {
+ get
+ {
+ return SR.GetResourceString("XmlConvert_TypeFromString", null);
+ }
+ }
+
+ internal static String XmlConvert_TypeListBadMapping
+ {
+ get
+ {
+ return SR.GetResourceString("XmlConvert_TypeListBadMapping", null);
+ }
+ }
+
+ internal static String XmlConvert_TypeListBadMapping2
+ {
+ get
+ {
+ return SR.GetResourceString("XmlConvert_TypeListBadMapping2", null);
+ }
+ }
+
+ internal static String XmlConvert_TypeNoNamespace
+ {
+ get
+ {
+ return SR.GetResourceString("XmlConvert_TypeNoNamespace", null);
+ }
+ }
+
+ internal static String XmlConvert_TypeNoPrefix
+ {
+ get
+ {
+ return SR.GetResourceString("XmlConvert_TypeNoPrefix", null);
+ }
+ }
+
+ internal static String XmlConvert_TypeToString
+ {
+ get
+ {
+ return SR.GetResourceString("XmlConvert_TypeToString", null);
+ }
+ }
+
+ internal static String XmlNoNameAllowed
+ {
+ get
+ {
+ return SR.GetResourceString("XmlNoNameAllowed", null);
+ }
+ }
+
+ internal static String XmlUndefinedAlias
+ {
+ get
+ {
+ return SR.GetResourceString("XmlUndefinedAlias", null);
+ }
+ }
+
+ internal static String Xp_BadQueryObject
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_BadQueryObject", null);
+ }
+ }
+
+ internal static String Xp_CurrentNotAllowed
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_CurrentNotAllowed", null);
+ }
+ }
+
+ internal static String Xp_ExprExpected
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_ExprExpected", null);
+ }
+ }
+
+ internal static String Xp_FunctionFailed
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_FunctionFailed", null);
+ }
+ }
+
+ internal static String Xp_InvalidArgumentType
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_InvalidArgumentType", null);
+ }
+ }
+
+ internal static String Xp_InvalidKeyPattern
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_InvalidKeyPattern", null);
+ }
+ }
+
+ internal static String Xp_InvalidName
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_InvalidName", null);
+ }
+ }
+
+ internal static String Xp_InvalidNumArgs
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_InvalidNumArgs", null);
+ }
+ }
+
+ internal static String Xp_InvalidPattern
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_InvalidPattern", null);
+ }
+ }
+
+ internal static String Xp_InvalidToken
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_InvalidToken", null);
+ }
+ }
+
+ internal static String Xp_NoContext
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_NoContext", null);
+ }
+ }
+
+ internal static String Xp_NodeSetExpected
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_NodeSetExpected", null);
+ }
+ }
+
+ internal static String Xp_NotSupported
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_NotSupported", null);
+ }
+ }
+
+ internal static String Xp_QueryTooComplex
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_QueryTooComplex", null);
+ }
+ }
+
+ internal static String Xp_UnclosedString
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_UnclosedString", null);
+ }
+ }
+
+ internal static String Xp_UndefFunc
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_UndefFunc", null);
+ }
+ }
+
+ internal static String Xp_UndefinedXsltContext
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_UndefinedXsltContext", null);
+ }
+ }
+
+ internal static String Xp_UndefVar
+ {
+ get
+ {
+ return SR.GetResourceString("Xp_UndefVar", null);
+ }
+ }
+
+ internal static String Xpn_BadPosition
+ {
+ get
+ {
+ return SR.GetResourceString("Xpn_BadPosition", null);
+ }
+ }
+
+ internal static String Format(String resourceFormat, params Object[] args)
+ {
+ if (args == null)
+ {
+ return resourceFormat;
+ }
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, args);
+ }
+ return String.Concat(resourceFormat, String.Join(", ", args));
+ }
+
+ internal static String Format(String resourceFormat, Object p1)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2, Object p3)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2, p3);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 });
+ }
+
+ internal static String GetResourceString(String resourceKey, String defaultString)
+ {
+ String str = null;
+ try
+ {
+ str = SR.ResourceManager.GetString(resourceKey);
+ }
+ catch (MissingManifestResourceException missingManifestResourceException)
+ {
+ }
+ if (defaultString != null && resourceKey.Equals(str))
+ {
+ return defaultString;
+ }
+ return str;
+ }
+
+ private static Boolean UsingResourceKeys()
+ {
+ return false;
+ }
+ }
+}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ReadonlypropertyOperations operations.
/// </summary>
internal partial class ReadonlypropertyOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IReadonlypropertyOperations
{
/// <summary>
/// Initializes a new instance of the ReadonlypropertyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ReadonlypropertyOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that have readonly properties
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ReadonlyObj>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ReadonlyObj>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ReadonlyObj>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that have readonly properties
/// </summary>
/// <param name='complexBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(ReadonlyObj complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.WasHosting
{
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.Security.Principal;
using System.ServiceModel.Activation;
using System.ServiceModel.Activation.Diagnostics;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.Hosting;
using Microsoft.Web.Administration;
static class MetabaseSettingsIis7Constants
{
internal const string SitesSectionName = "system.applicationHost/sites";
internal const string ClientCertMapAuthenticationName = "system.webServer/security/authentication/clientCertificateMappingAuthentication";
internal const string IisClientCertMapAuthenticationName = "system.webServer/security/authentication/iisClientCertificateMappingAuthentication";
internal const string AnonymousAuthenticationSectionName = "system.webServer/security/authentication/anonymousAuthentication";
internal const string BasicAuthenticationSectionName = "system.webServer/security/authentication/basicAuthentication";
internal const string DigestAuthenticationSectionName = "system.webServer/security/authentication/digestAuthentication";
internal const string WindowsAuthenticationSectionName = "system.webServer/security/authentication/windowsAuthentication";
internal const string SecurityAccessSectionName = "system.webServer/security/access";
internal const string EnabledAttributeName = "enabled";
internal const string RealmAttributeName = "realm";
internal const string ValueAttributeName = "value";
internal const string SslFlagsAttributeName = "sslFlags";
internal const string ProviderElementName = "providers";
internal const string BindingsElementName = "bindings";
internal const string ProtocolAttributeName = "protocol";
internal const string BindingInfoAttributeName = "bindingInformation";
internal const string PathAttributeName = "path";
internal const string EnabledProtocolsAttributeName = "enabledProtocols";
internal const string NameAttributeName = "name";
internal const string ExtendedProtectionElementName = "extendedProtection";
internal const string TokenCheckingAttributeName = "tokenChecking";
internal const string FlagsAttributeName = "flags";
internal const string CommaSeparator = ",";
internal const string WebConfigGetSectionMethodName = "GetSection";
}
// MetabaseSettingsIis7 use ServerManager class to get Metabase settings. ServerManager
// does not work in Longhorn Sever/SP1 builds.
class MetabaseSettingsIis7 : MetabaseSettingsIis
{
internal MetabaseSettingsIis7()
: base()
{
if (!Iis7Helper.IsIis7)
{
DiagnosticUtility.DebugAssert("MetabaseSettingsIis7 constructor must not be called when running outside of IIS7");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInternal(true);
}
PopulateSiteProperties();
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "called by MetabaseSettingsIis7 constructor")]
void PopulateSiteProperties()
{
Site site = ServerManagerWrapper.GetSite(HostingEnvironment.SiteName);
DiagnosticUtility.DebugAssert(site != null, "Unable to find site.");
//
// Build up the binding table.
//
IDictionary<string, List<string>> bindingList = ServerManagerWrapper.GetProtocolBindingTable(site);
// Convert to string arrays
foreach (KeyValuePair<string, List<string>> entry in bindingList)
{
this.Bindings.Add(entry.Key, entry.Value.ToArray());
entry.Value.Clear();
}
// Clear the temporary buffer
bindingList.Clear();
//
// Build up the protocol list.
//
string[] protocols = ServerManagerWrapper.GetEnabledProtocols(site).Split(MetabaseSettingsIis7Constants.CommaSeparator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string protocolValue in protocols)
{
string protocol = protocolValue.Trim();
protocol = protocol.ToLowerInvariant();
if (string.IsNullOrEmpty(protocol) || this.Protocols.Contains(protocol))
{
// Ignore duplicates and empty protocols
continue;
}
else if (string.Compare(protocol, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(protocol, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) == 0)
{
// Special casing HTTPS. If HTTP is enabled, it means that
// both HTTP and HTTPS are enabled.
if (this.Bindings.ContainsKey(Uri.UriSchemeHttp))
{
this.Protocols.Add(Uri.UriSchemeHttp);
}
if (this.Bindings.ContainsKey(Uri.UriSchemeHttps))
{
this.Protocols.Add(Uri.UriSchemeHttps);
}
}
else if (this.Bindings.ContainsKey(protocol))
{
// We only take the protocols that have bindings.
this.Protocols.Add(protocol);
}
}
}
protected override HostedServiceTransportSettings CreateTransportSettings(string relativeVirtualPath)
{
Debug.Print("MetabaseSettingsIis7.CreateTransportSettings() calling ServerManager.GetWebConfiguration() virtualPath: " + relativeVirtualPath);
string absolutePath = VirtualPathUtility.ToAbsolute(relativeVirtualPath, HostingEnvironmentWrapper.ApplicationVirtualPath);
Configuration config =
ServerManagerWrapper.GetWebConfiguration(
HostingEnvironment.SiteName,
absolutePath);
HostedServiceTransportSettings transportSettings = new HostedServiceTransportSettings();
ProcessAnonymousAuthentication(config, ref transportSettings);
ProcessBasicAuthentication(config, ref transportSettings);
ProcessWindowsAuthentication(config, ref transportSettings);
ProcessDigestAuthentication(config, ref transportSettings);
ProcessSecurityAccess(config, ref transportSettings);
return transportSettings;
}
void ProcessAnonymousAuthentication(Configuration config, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = ServerManagerWrapper.GetSection(config, MetabaseSettingsIis7Constants.AnonymousAuthenticationSectionName);
if ((section != null) &&
((bool)ServerManagerWrapper.GetAttributeValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AuthFlags = transportSettings.AuthFlags | AuthFlags.AuthAnonymous;
}
}
void ProcessBasicAuthentication(Configuration config, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = ServerManagerWrapper.GetSection(config, MetabaseSettingsIis7Constants.BasicAuthenticationSectionName);
if ((section != null) &&
((bool)ServerManagerWrapper.GetAttributeValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AuthFlags = transportSettings.AuthFlags | AuthFlags.AuthBasic;
transportSettings.Realm = (string)ServerManagerWrapper.GetAttributeValue(section, MetabaseSettingsIis7Constants.RealmAttributeName);
}
}
void ProcessWindowsAuthentication(Configuration config, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = ServerManagerWrapper.GetSection(config, MetabaseSettingsIis7Constants.WindowsAuthenticationSectionName);
if ((section != null) &&
((bool)ServerManagerWrapper.GetAttributeValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AuthFlags = transportSettings.AuthFlags | AuthFlags.AuthNTLM;
List<string> providerList = ServerManagerWrapper.GetProviders(section, MetabaseSettingsIis7Constants.ProviderElementName,
MetabaseSettingsIis7Constants.ValueAttributeName);
if (providerList.Count != 0)
{
transportSettings.AuthProviders = providerList.ToArray();
}
}
try
{
ConfigurationElement element = section.GetChildElement(MetabaseSettingsIis7Constants.ExtendedProtectionElementName);
if (element != null)
{
ExtendedProtectionTokenChecking tokenChecking;
ExtendedProtectionFlags flags;
List<string> spnList;
ServerManagerWrapper.ReadIisExtendedProtectionPolicy(element, out tokenChecking, out flags, out spnList);
transportSettings.IisExtendedProtectionPolicy = BuildExtendedProtectionPolicy(tokenChecking, flags, spnList);
}
}
catch (COMException e)
{
// hit this exception only when IIS does not support CBT
// safe for us to igore this COMException so that services not using CBT still can be activated
// if a service does use CBT in binding, channel listener will catch it when comparing IIS setting against WCF (on CBT) and throw exception
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.WebHostNoCBTSupport,
SR.TraceCodeWebHostNoCBTSupport, this, e);
}
}
}
void ProcessDigestAuthentication(Configuration config, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = ServerManagerWrapper.GetSection(config, MetabaseSettingsIis7Constants.DigestAuthenticationSectionName);
if ((section != null) &&
((bool)ServerManagerWrapper.GetAttributeValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AuthFlags = transportSettings.AuthFlags | AuthFlags.AuthMD5;
}
}
void ProcessSecurityAccess(Configuration config, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = ServerManagerWrapper.GetSection(config, MetabaseSettingsIis7Constants.SecurityAccessSectionName);
// Check SSL Flags.
if (section != null)
{
int sslFlags = (int)ServerManagerWrapper.GetAttributeValue(section, MetabaseSettingsIis7Constants.SslFlagsAttributeName);
transportSettings.AccessSslFlags = (HttpAccessSslFlags)sslFlags;
// Clear SslMapCert field, which should not contain any useful data now.
transportSettings.AccessSslFlags &= ~(HttpAccessSslFlags.SslMapCert);
}
// Check whether IIS client certificate mapping is enabled.
section = ServerManagerWrapper.GetSection(config, MetabaseSettingsIis7Constants.IisClientCertMapAuthenticationName);
if ((section != null) &&
((bool)ServerManagerWrapper.GetAttributeValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AccessSslFlags |= HttpAccessSslFlags.SslMapCert;
}
else
{
// Check whether Active Directory client certification mapping is enabled.
section = ServerManagerWrapper.GetSection(config, MetabaseSettingsIis7Constants.ClientCertMapAuthenticationName);
if ((section != null) &&
((bool)ServerManagerWrapper.GetAttributeValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AccessSslFlags |= HttpAccessSslFlags.SslMapCert;
}
}
}
protected override IEnumerable<string> GetSiteApplicationPaths()
{
return ServerManagerWrapper.GetApplicationPaths();
}
// wraps calls to ServerManager with Asserts as necessary to support partial trust scenarios
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
static class ServerManagerWrapper
{
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by MetabaseSettingsIis7.PopulateSiteProperties")]
static internal Site GetSite(string name)
{
return new ServerManager().Sites[name];
}
static internal Configuration GetWebConfiguration(string siteName, string absolutePath)
{
return new ServerManager().GetWebConfiguration(siteName, absolutePath);
}
static internal ConfigurationSection GetSection(Configuration config, string sectionName)
{
return config.GetSection(sectionName);
}
static internal List<string> GetProviders(ConfigurationSection section, string providerElementName, string valueAttributeName)
{
List<string> providerList = new List<string>();
foreach (ConfigurationElement element in section.GetCollection(providerElementName))
{
providerList.Add((string)ServerManagerWrapper.GetAttributeValue(element, valueAttributeName));
}
return providerList;
}
static internal object GetAttributeValue(ConfigurationSection section, string attributeName)
{
return section.GetAttribute(attributeName).Value;
}
static internal object GetAttributeValue(ConfigurationElement element, string attributeName)
{
return element.GetAttribute(attributeName).Value;
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by MetabaseSettingsIis7.PopulateSiteProperties")]
static internal IDictionary<string, List<string>> GetProtocolBindingTable(Site site)
{
IDictionary<string, List<string>> bindingList = new Dictionary<string, List<string>>();
foreach (Microsoft.Web.Administration.Binding binding in site.Bindings)
{
string protocol = binding.Protocol.ToLowerInvariant();
string bindingInformation = binding.BindingInformation;
Debug.Print("MetabaseSettingsIis7.ctor() adding Protocol: " + protocol + " BindingInformation: " + bindingInformation);
if (!bindingList.ContainsKey(protocol))
{
bindingList.Add(protocol, new List<string>());
}
bindingList[protocol].Add(bindingInformation);
}
return bindingList;
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by MetabaseSettingsIis7.PopulateSiteProperties")]
static internal string GetEnabledProtocols(Site site)
{
Application application = site.Applications[HostingEnvironmentWrapper.ApplicationVirtualPath];
DiagnosticUtility.DebugAssert(application != null, "Unable to find application.");
return application.EnabledProtocols;
}
static internal void ReadIisExtendedProtectionPolicy(ConfigurationElement element, out ExtendedProtectionTokenChecking tokenChecking,
out ExtendedProtectionFlags flags, out List<string> spnList)
{
tokenChecking = (ExtendedProtectionTokenChecking)element.GetAttributeValue(MetabaseSettingsIis7Constants.TokenCheckingAttributeName);
flags = (ExtendedProtectionFlags)element.GetAttributeValue(MetabaseSettingsIis7Constants.FlagsAttributeName);
spnList = new List<string>();
foreach (ConfigurationElement configElement in element.GetCollection())
{
spnList.Add((string)configElement[MetabaseSettingsIis7Constants.NameAttributeName]);
}
}
static internal IEnumerable<string> GetApplicationPaths()
{
//Get the site ourselves instead of calling GetSite() because we should dispose of the ServerManager
using (ServerManager serverManager = new ServerManager())
{
List<string> appPaths = new List<string>();
Site site = serverManager.Sites[HostingEnvironment.SiteName];
foreach (Application app in site.Applications)
{
appPaths.Add(app.Path);
}
return appPaths;
}
}
}
}
// MetabaseSettingsIis7V2 use WebConfigurationManager to get Metabase settings, we depend on
// some methods which only availble in Longhorn Server/SP1 build.
class MetabaseSettingsIis7V2 : MetabaseSettingsIis
{
static MethodInfo getSectionMethod;
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by MetabaseSettingsIis7Factory.CreateMetabaseSettings")]
internal MetabaseSettingsIis7V2()
: base()
{
if (!Iis7Helper.IsIis7)
{
DiagnosticUtility.DebugAssert("MetabaseSettingsIis7V2 constructor must not be called when running outside of IIS7");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInternal(true);
}
PopulateSiteProperties();
}
static internal MethodInfo GetSectionMethod
{
get
{
if (getSectionMethod == null)
{
Type type = typeof(WebConfigurationManager);
getSectionMethod = type.GetMethod(
MetabaseSettingsIis7Constants.WebConfigGetSectionMethodName,
new Type[3] { typeof(string), typeof(string), typeof(string) }
);
}
return getSectionMethod;
}
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by MetabaseSettingsIis7V2 constructor")]
void PopulateSiteProperties()
{
ConfigurationElement site = WebConfigurationManagerWrapper.GetSite(HostingEnvironment.SiteName);
//
// Build up the binding table.
//
IDictionary<string, List<string>> bindingList = WebConfigurationManagerWrapper.GetProtocolBindingTable(site);
// Convert to string arrays
foreach (KeyValuePair<string, List<string>> entry in bindingList)
{
this.Bindings.Add(entry.Key, entry.Value.ToArray());
entry.Value.Clear();
}
// Clear the temporary buffer
bindingList.Clear();
//
// Build up the protocol list.
//
string[] protocols = WebConfigurationManagerWrapper.GetEnabledProtocols(site).Split(MetabaseSettingsIis7Constants.CommaSeparator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string protocolValue in protocols)
{
string protocol = protocolValue.Trim();
protocol = protocol.ToLowerInvariant();
if (string.IsNullOrEmpty(protocol) || this.Protocols.Contains(protocol))
{
// Ignore duplicates and empty protocols
continue;
}
else if (string.Compare(protocol, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(protocol, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) == 0)
{
// Special casing HTTPS. If HTTP is enabled, it means that
// both HTTP and HTTPS are enabled.
if (this.Bindings.ContainsKey(Uri.UriSchemeHttp))
{
this.Protocols.Add(Uri.UriSchemeHttp);
}
if (this.Bindings.ContainsKey(Uri.UriSchemeHttps))
{
this.Protocols.Add(Uri.UriSchemeHttps);
}
}
else if (this.Bindings.ContainsKey(protocol))
{
// We only take the protocols that have bindings.
this.Protocols.Add(protocol);
}
}
}
protected override HostedServiceTransportSettings CreateTransportSettings(string relativeVirtualPath)
{
Debug.Print("MetabaseSettingsIis7.CreateTransportSettings() calling ServerManager.GetWebConfiguration() virtualPath: " + relativeVirtualPath);
string absolutePath = VirtualPathUtility.ToAbsolute(relativeVirtualPath, HostingEnvironment.ApplicationVirtualPath);
HostedServiceTransportSettings transportSettings = new HostedServiceTransportSettings();
string siteName = HostingEnvironment.SiteName;
ProcessAnonymousAuthentication(siteName, absolutePath, ref transportSettings);
ProcessBasicAuthentication(siteName, absolutePath, ref transportSettings);
ProcessWindowsAuthentication(siteName, absolutePath, ref transportSettings);
ProcessDigestAuthentication(siteName, absolutePath, ref transportSettings);
ProcessSecurityAccess(siteName, absolutePath, ref transportSettings);
return transportSettings;
}
void ProcessAnonymousAuthentication(string siteName, string virtualPath, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = WebConfigurationManagerWrapper.WebConfigGetSection(siteName, virtualPath, MetabaseSettingsIis7Constants.AnonymousAuthenticationSectionName);
if ((section != null) &&
((bool)WebConfigurationManagerWrapper.GetValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AuthFlags = transportSettings.AuthFlags | AuthFlags.AuthAnonymous;
}
}
void ProcessBasicAuthentication(string siteName, string virtualPath, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = WebConfigurationManagerWrapper.WebConfigGetSection(siteName, virtualPath, MetabaseSettingsIis7Constants.BasicAuthenticationSectionName);
if ((section != null) &&
((bool)WebConfigurationManagerWrapper.GetValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AuthFlags = transportSettings.AuthFlags | AuthFlags.AuthBasic;
transportSettings.Realm = (string)section.GetAttribute(MetabaseSettingsIis7Constants.RealmAttributeName).Value;
}
}
void ProcessWindowsAuthentication(string siteName, string virtualPath, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = WebConfigurationManagerWrapper.WebConfigGetSection(siteName, virtualPath, MetabaseSettingsIis7Constants.WindowsAuthenticationSectionName);
if ((section != null) &&
((bool)WebConfigurationManagerWrapper.GetValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AuthFlags = transportSettings.AuthFlags | AuthFlags.AuthNTLM;
List<string> providerList = WebConfigurationManagerWrapper.GetProviderList(section);
if (providerList.Count != 0)
{
transportSettings.AuthProviders = providerList.ToArray();
}
// Check the CBT configuration
try
{
ConfigurationElement element = section.GetChildElement(MetabaseSettingsIis7Constants.ExtendedProtectionElementName);
if (element != null)
{
ExtendedProtectionTokenChecking tokenChecking;
ExtendedProtectionFlags flags;
List<string> spnList;
WebConfigurationManagerWrapper.ReadIisExtendedProtectionPolicy(element, out tokenChecking, out flags, out spnList);
transportSettings.IisExtendedProtectionPolicy = BuildExtendedProtectionPolicy(tokenChecking, flags, spnList);
}
}
catch (COMException e)
{
// hit this exception only when IIS does not support CBT
// safe for us to igore this COMException so that services not using CBT still can be activated
// if a service does use CBT in binding, channel listener will catch it when comparing IIS setting against WCF (on CBT) and throw exception
if (DiagnosticUtility.ShouldTraceWarning)
{
TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.WebHostNoCBTSupport,
SR.TraceCodeWebHostNoCBTSupport, this, e);
}
}
}
}
void ProcessDigestAuthentication(string siteName, string virtualPath, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = WebConfigurationManagerWrapper.WebConfigGetSection(siteName, virtualPath, MetabaseSettingsIis7Constants.DigestAuthenticationSectionName);
if ((section != null) &&
((bool)WebConfigurationManagerWrapper.GetValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AuthFlags = transportSettings.AuthFlags | AuthFlags.AuthMD5;
}
}
void ProcessSecurityAccess(string siteName, string virtualPath, ref HostedServiceTransportSettings transportSettings)
{
ConfigurationSection section = WebConfigurationManagerWrapper.WebConfigGetSection(siteName, virtualPath, MetabaseSettingsIis7Constants.SecurityAccessSectionName);
// Check SSL Flags.
if (section != null)
{
int sslFlags = (int)WebConfigurationManagerWrapper.GetValue(section, MetabaseSettingsIis7Constants.SslFlagsAttributeName);
transportSettings.AccessSslFlags = (HttpAccessSslFlags)sslFlags;
// Clear SslMapCert field, which should not contain any useful data now.
transportSettings.AccessSslFlags &= ~(HttpAccessSslFlags.SslMapCert);
}
// Check whether IIS client certificate mapping is enabled.
section = WebConfigurationManagerWrapper.WebConfigGetSection(siteName, virtualPath, MetabaseSettingsIis7Constants.IisClientCertMapAuthenticationName);
if ((section != null) &&
((bool)WebConfigurationManagerWrapper.GetValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AccessSslFlags |= HttpAccessSslFlags.SslMapCert;
}
else
{
// Check whether Active Directory client certification mapping is enabled.
section = WebConfigurationManagerWrapper.WebConfigGetSection(siteName, virtualPath, MetabaseSettingsIis7Constants.ClientCertMapAuthenticationName);
if ((section != null) &&
((bool)WebConfigurationManagerWrapper.GetValue(section, MetabaseSettingsIis7Constants.EnabledAttributeName))
)
{
transportSettings.AccessSslFlags |= HttpAccessSslFlags.SslMapCert;
}
}
}
protected override IEnumerable<string> GetSiteApplicationPaths()
{
ConfigurationElement site = WebConfigurationManagerWrapper.GetSite(HostingEnvironment.SiteName);
return WebConfigurationManagerWrapper.GetApplicationPaths(site);
}
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
static class WebConfigurationManagerWrapper
{
// Helper Method to get a site configuration
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by MetabaseSettingsIis7V2.PopulateSiteProperties")]
static internal ConfigurationElement GetSite(string siteName)
{
ConfigurationSection sitesSection = WebConfigGetSection(null, null, MetabaseSettingsIis7Constants.SitesSectionName);
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
return FindElement(sitesCollection, MetabaseSettingsIis7Constants.NameAttributeName, siteName);
}
// Helper method to find element based on an string attribute.
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by GetSite")]
static internal ConfigurationElement FindElement(ConfigurationElementCollection collection, string attributeName, string value)
{
foreach (ConfigurationElement element in collection)
{
if (String.Equals((string)element[attributeName], value, StringComparison.OrdinalIgnoreCase))
{
return element;
}
}
return null;
}
static internal ConfigurationSection WebConfigGetSection(string siteName, string virtualPath, string sectionName)
{
return (ConfigurationSection)GetSectionMethod.Invoke(null, new object[] { siteName, virtualPath, sectionName });
}
static internal object GetValue(ConfigurationSection section, string name)
{
return section[name];
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by MetabaseSettingsIis7V2.PopulateSiteProperties")]
static internal IDictionary<string, List<string>> GetProtocolBindingTable(ConfigurationElement site)
{
IDictionary<string, List<string>> bindingList = new Dictionary<string, List<string>>();
foreach (ConfigurationElement binding in site.GetCollection(MetabaseSettingsIis7Constants.BindingsElementName))
{
string protocol = ((string)binding[MetabaseSettingsIis7Constants.ProtocolAttributeName]).ToLowerInvariant();
string bindingInformation = (string)binding[MetabaseSettingsIis7Constants.BindingInfoAttributeName];
Debug.Print("MetabaseSettingsIis7V2.ctor() adding Protocol: " + protocol + " BindingInformation: " + bindingInformation);
if (!bindingList.ContainsKey(protocol))
{
bindingList.Add(protocol, new List<string>());
}
bindingList[protocol].Add(bindingInformation);
}
return bindingList;
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Called by MetabaseSettingsIis7V2.PopulateSiteProperties")]
static internal string GetEnabledProtocols(ConfigurationElement site)
{
ConfigurationElement application = FindElement(
site.GetCollection(),
MetabaseSettingsIis7Constants.PathAttributeName,
HostingEnvironment.ApplicationVirtualPath
);
DiagnosticUtility.DebugAssert(application != null, "Unable to find application.");
return (string)application[MetabaseSettingsIis7Constants.EnabledProtocolsAttributeName];
}
static internal List<string> GetProviderList(ConfigurationElement section)
{
List<string> providerList = new List<string>();
foreach (ConfigurationElement element in section.GetCollection(MetabaseSettingsIis7Constants.ProviderElementName))
{
providerList.Add((string)element[MetabaseSettingsIis7Constants.ValueAttributeName]);
}
return providerList;
}
// translate IIS setting on extended protection to NCL object
static internal void ReadIisExtendedProtectionPolicy(ConfigurationElement element, out ExtendedProtectionTokenChecking tokenChecking,
out ExtendedProtectionFlags flags, out List<string> spnList)
{
tokenChecking = (ExtendedProtectionTokenChecking)element.GetAttributeValue(MetabaseSettingsIis7Constants.TokenCheckingAttributeName);
flags = (ExtendedProtectionFlags)element.GetAttributeValue(MetabaseSettingsIis7Constants.FlagsAttributeName);
spnList = new List<string>();
foreach (ConfigurationElement configElement in element.GetCollection())
{
spnList.Add((string)configElement[MetabaseSettingsIis7Constants.NameAttributeName]);
}
}
static internal IEnumerable<string> GetApplicationPaths(ConfigurationElement site)
{
List<string> appPaths = new List<string>();
ConfigurationElementCollection applications = site.GetCollection();
foreach (ConfigurationElement application in applications)
{
string appPath = (string)application["path"];
appPaths.Add(appPath);
}
return appPaths;
}
}
}
// Note: There is a dependency on this class name and CreateMetabaseSettings
// method name from System.ServiceModel.dll
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUninstantiatedInternalClasses,
Justification = "Instantiated by System.ServiceModel")]
internal class MetabaseSettingsIis7Factory
{
internal static MetabaseSettings CreateMetabaseSettings()
{
MethodInfo method = MetabaseSettingsIis7V2.GetSectionMethod;
if (method != null)
{
return new MetabaseSettingsIis7V2();
}
return new MetabaseSettingsIis7();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using JoinRpg.Data.Write.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using JoinRpg.Services.Interfaces;
using JoinRpg.Services.Interfaces.Email;
using JoinRpg.Services.Interfaces.Notification;
using Microsoft.Practices.ServiceLocation;
namespace JoinRpg.Services.Impl
{
[UsedImplicitly]
public class AccommodationServiceImpl : DbServiceImplBase, IAccommodationService
{
private IEmailService EmailService { get; }
public async Task<ProjectAccommodationType> SaveRoomTypeAsync(ProjectAccommodationType roomType)
{
if (roomType.ProjectId == 0)
throw new ActivationException("Inconsistent state. ProjectId can't be 0");
ProjectAccommodationType result;
if (roomType.Id != 0)
{
result = await UnitOfWork.GetDbSet<ProjectAccommodationType>().FindAsync(roomType.Id).ConfigureAwait(false);
if (result?.ProjectId != roomType.ProjectId)
{
return null;
}
result.Name = roomType.Name;
result.Cost = roomType.Cost;
result.Capacity = roomType.Capacity;
result.Description = roomType.Description;
result.IsAutoFilledAccommodation = roomType.IsAutoFilledAccommodation;
result.IsInfinite = roomType.IsInfinite;
result.IsPlayerSelectable = roomType.IsPlayerSelectable;
}
else
{
result = UnitOfWork.GetDbSet<ProjectAccommodationType>().Add(roomType);
}
await UnitOfWork.SaveChangesAsync().ConfigureAwait(false);
return result;
}
public async Task<IReadOnlyCollection<ProjectAccommodationType>> GetRoomTypesAsync(int projectId)
{
return await AccomodationRepository.GetAccommodationForProject(projectId).ConfigureAwait(false);
}
public async Task<ProjectAccommodationType> GetRoomTypeAsync(int roomTypeId)
{
return await UnitOfWork.GetDbSet<ProjectAccommodationType>()
.Include(x => x.ProjectAccommodations)
.Include(x => x.Desirous)
.FirstOrDefaultAsync(x => x.Id == roomTypeId);
}
public async Task OccupyRoom(OccupyRequest request)
{
var room = await UnitOfWork.GetDbSet<ProjectAccommodation>()
.Include(r => r.Inhabitants)
.Include(r => r.ProjectAccommodationType)
.Where(r => r.ProjectId == request.ProjectId && r.Id == request.RoomId)
.FirstOrDefaultAsync();
var accommodationRequests = await UnitOfWork.GetDbSet<AccommodationRequest>()
.Include(r => r.Subjects.Select(s => s.Player))
.Include(r => r.Project)
.Where(r => r.ProjectId == request.ProjectId && request.AccommodationRequestIds.Contains(r.Id))
.ToListAsync();
room.Project.RequestMasterAccess(CurrentUserId, acl => acl.CanSetPlayersAccommodations);
foreach (var accommodationRequest in accommodationRequests)
{
var freeSpace = room.GetRoomFreeSpace();
if (freeSpace < accommodationRequest.Subjects.Count)
{
throw new JoinRpgInsufficientRoomSpaceException(room);
}
accommodationRequest.AccommodationId = room.Id;
accommodationRequest.Accommodation = room;
}
await UnitOfWork.SaveChangesAsync();
await EmailService.Email(await CreateRoomEmail<OccupyRoomEmail>(room, accommodationRequests.SelectMany(ar => ar.Subjects).ToArray()));
}
private async Task<T> CreateRoomEmail<T>(ProjectAccommodation room, Claim[] changed)
where T: RoomEmailBase, new()
{
return new T()
{
Changed = changed,
Initiator = await GetCurrentUser(),
ProjectName = room.Project.ProjectName,
Recipients = room.GetSubscriptions().ToList(),
Room = room,
Text = new MarkdownString()
};
}
public async Task UnOccupyRoom(UnOccupyRequest request)
{
var accommodationRequest = await UnitOfWork.GetDbSet<AccommodationRequest>()
.Include(r => r.Subjects.Select(s => s.Player))
.Include(r => r.Project)
.Where(r => r.ProjectId == request.ProjectId && r.Id == request.AccommodationRequestId)
.FirstOrDefaultAsync();
var room = await UnitOfWork.GetDbSet<ProjectAccommodation>()
.Include(r => r.Inhabitants)
.Include(r => r.ProjectAccommodationType)
.Where(r => r.ProjectId == request.ProjectId && r.Id == accommodationRequest.AccommodationId)
.FirstOrDefaultAsync();
await UnOccupyRoomImpl(room, new[] {accommodationRequest});
}
private async Task UnOccupyRoomImpl(ProjectAccommodation room,
IReadOnlyCollection<AccommodationRequest> accommodationRequests)
{
room.Project.RequestMasterAccess(CurrentUserId, acl => acl.CanSetPlayersAccommodations);
foreach (var request in accommodationRequests)
{
request.AccommodationId = null;
request.Accommodation = null;
}
await UnitOfWork.SaveChangesAsync();
await EmailService.Email(
await CreateRoomEmail<UnOccupyRoomEmail>(room, accommodationRequests.SelectMany(x => x.Subjects).ToArray()));
}
public async Task UnOccupyRoomAll(UnOccupyAllRequest request)
{
var room = await GetRoomQuery(request.ProjectId)
.Where(r => r.Id == request.RoomId)
.FirstOrDefaultAsync();
await UnOccupyRoomImpl(room, room.Inhabitants.ToList());
}
private IQueryable<ProjectAccommodation> GetRoomQuery(int projectId)
{
return UnitOfWork.GetDbSet<ProjectAccommodation>()
.Include(r => r.Project)
.Include(r => r.Inhabitants)
.Include(r => r.ProjectAccommodationType)
.Include(r => r.Inhabitants.Select(i => i.Subjects.Select(c => c.Player)))
.Where(r => r.ProjectId == projectId);
}
public async Task UnOccupyRoomType(int projectId, int roomTypeId)
{
var rooms = await GetRoomQuery(projectId)
.Where(r => r.Inhabitants.Any())
.Where(r => r.AccommodationTypeId == roomTypeId)
.ToListAsync();
foreach (var room in rooms)
{
await UnOccupyRoomImpl(room, room.Inhabitants.ToList());
}
}
public async Task UnOccupyAll(int projectId)
{
var rooms = await GetRoomQuery(projectId)
.Where(r => r.Inhabitants.Any())
.ToListAsync();
foreach (var room in rooms)
{
await UnOccupyRoomImpl(room, room.Inhabitants.ToList());
}
}
public async Task RemoveRoomType(int accomodationTypeId)
{
var entity = UnitOfWork.GetDbSet<ProjectAccommodationType>().Find(accomodationTypeId);
if (entity == null)
{
throw new JoinRpgEntityNotFoundException(accomodationTypeId, "ProjectAccommodationType");
}
var occupiedRoom =
entity.ProjectAccommodations.FirstOrDefault(pa => pa.IsOccupied());
if (occupiedRoom != null)
{
throw new RoomIsOccupiedException(occupiedRoom);
}
UnitOfWork.GetDbSet<ProjectAccommodationType>().Remove(entity);
await UnitOfWork.SaveChangesAsync().ConfigureAwait(false);
}
public async Task<IEnumerable<ProjectAccommodation>> AddRooms(int projectId, int roomTypeId, string rooms)
{
//TODO: Implement rooms names checking
ProjectAccommodationType roomType = UnitOfWork.GetDbSet<ProjectAccommodationType>().Find(roomTypeId);
if (roomType == null)
throw new JoinRpgEntityNotFoundException(roomTypeId, typeof(ProjectAccommodationType).Name);
if (roomType.ProjectId != projectId)
throw new ArgumentException($"Room type {roomTypeId} is from another project than specified", nameof(roomTypeId));
// Internal function
// Creates new room using name and parameters from given room info
ProjectAccommodation CreateRoom(string name)
=> new ProjectAccommodation
{
Name = name,
AccommodationTypeId = roomTypeId,
ProjectId = projectId,
ProjectAccommodationType = roomType
};
// Internal function
// Iterates through rooms list and creates object for each room from a list
IEnumerable<ProjectAccommodation> CreateRooms(string r)
{
foreach (string roomCandidate in r.Split(','))
{
int rangePos = roomCandidate.IndexOf('-');
if (rangePos > -1)
{
if (int.TryParse(roomCandidate.Substring(0, rangePos).Trim(), out int roomsRangeStart)
&& int.TryParse(roomCandidate.Substring(rangePos + 1).Trim(), out int roomsRangeEnd)
&& roomsRangeStart < roomsRangeEnd)
{
while (roomsRangeStart <= roomsRangeEnd)
{
yield return CreateRoom(roomsRangeStart.ToString());
roomsRangeStart++;
}
// Range was defined correctly, we can continue to next item
continue;
}
}
yield return CreateRoom(roomCandidate.Trim());
}
}
IEnumerable<ProjectAccommodation> result =
UnitOfWork.GetDbSet<ProjectAccommodation>().AddRange(CreateRooms(rooms));
await UnitOfWork.SaveChangesAsync();
return result;
}
private ProjectAccommodation GetRoom(int roomId, int? projectId = null, int? roomTypeId = null)
{
var result = UnitOfWork.GetDbSet<ProjectAccommodation>().Find(roomId);
if (result == null)
throw new JoinRpgEntityNotFoundException(roomId, typeof(ProjectAccommodation).Name);
if (projectId.HasValue)
{
if (result.ProjectId != projectId.Value)
throw new ArgumentException($"Room {roomId} is from different project than specified", nameof(projectId));
}
if (roomTypeId.HasValue)
{
if (result.AccommodationTypeId != roomTypeId.Value)
throw new ArgumentException($"Room {roomId} is from different room type than specified", nameof(projectId));
}
return result;
}
public async Task EditRoom(int roomId, string name, int? projectId = null, int? roomTypeId = null)
{
var entity = GetRoom(roomId, projectId, roomTypeId);
entity.Name = name;
await UnitOfWork.SaveChangesAsync().ConfigureAwait(false);
}
public async Task DeleteRoom(int roomId, int? projectId = null, int? roomTypeId = null)
{
var entity = GetRoom(roomId, projectId, roomTypeId);
if (entity.IsOccupied())
{
throw new RoomIsOccupiedException(entity);
}
UnitOfWork.GetDbSet<ProjectAccommodation>().Remove(entity);
await UnitOfWork.SaveChangesAsync().ConfigureAwait(false);
}
public AccommodationServiceImpl(IUnitOfWork unitOfWork, IEmailService emailService) : base(unitOfWork)
{
EmailService = emailService;
}
}
}
| |
// 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 Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
public static partial class CastingHelper
{
/// <summary>
/// Returns true if '<paramref name="thisType"/>' can be cast to '<paramref name="otherType"/>'.
/// Assumes '<paramref name="thisType"/>' is in it's boxed form if it's a value type (i.e.
/// [System.Int32].CanCastTo([System.Object]) will return true).
/// </summary>
public static bool CanCastTo(this TypeDesc thisType, TypeDesc otherType)
{
return thisType.CanCastToInternal(otherType, null);
}
private static bool CanCastToInternal(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (thisType == otherType)
{
return true;
}
switch (thisType.Category)
{
case TypeFlags.GenericParameter:
return ((GenericParameterDesc)thisType).CanCastGenericParameterTo(otherType, protect);
case TypeFlags.Array:
case TypeFlags.SzArray:
return ((ArrayType)thisType).CanCastArrayTo(otherType, protect);
default:
Debug.Assert(thisType.IsDefType);
return thisType.CanCastToClassOrInterface(otherType, protect);
}
}
private static bool CanCastGenericParameterTo(this GenericParameterDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
// A boxed variable type can be cast to any of its constraints, or object, if none are specified
if (otherType.IsObject)
{
return true;
}
if (thisType.HasNotNullableValueTypeConstraint &&
otherType.IsWellKnownType(WellKnownType.ValueType))
{
return true;
}
foreach (var typeConstraint in thisType.TypeConstraints)
{
if (typeConstraint.CanCastToInternal(otherType, protect))
{
return true;
}
}
return false;
}
private static bool CanCastArrayTo(this ArrayType thisType, TypeDesc otherType, StackOverflowProtect protect)
{
// Casting the array to one of the base types or interfaces?
if (otherType.IsDefType)
{
return thisType.CanCastToClassOrInterface(otherType, protect);
}
// Casting array to something else (between SzArray and Array, for example)?
if (thisType.Category != otherType.Category)
{
return false;
}
ArrayType otherArrayType = (ArrayType)otherType;
// Check ranks if we're casting multidim arrays
if (!thisType.IsSzArray && thisType.Rank != otherArrayType.Rank)
{
return false;
}
return thisType.CanCastParamTo(otherArrayType.ParameterType, protect);
}
private static bool CanCastParamTo(this ParameterizedType thisType, TypeDesc paramType, StackOverflowProtect protect)
{
// While boxed value classes inherit from object their
// unboxed versions do not. Parameterized types have the
// unboxed version, thus, if the from type parameter is value
// class then only an exact match/equivalence works.
if (thisType.ParameterType == paramType)
{
return true;
}
TypeDesc curTypesParm = thisType.ParameterType;
// Object parameters don't need an exact match but only inheritance, check for that
TypeDesc fromParamUnderlyingType = curTypesParm.UnderlyingType;
if (fromParamUnderlyingType.IsGCPointer)
{
return curTypesParm.CanCastToInternal(paramType, protect);
}
else if (curTypesParm.IsGenericParameter)
{
var genericVariableFromParam = (GenericParameterDesc)curTypesParm;
if (genericVariableFromParam.HasReferenceTypeConstraint)
{
return genericVariableFromParam.CanCastToInternal(paramType, protect);
}
}
else if (fromParamUnderlyingType.IsPrimitive)
{
TypeDesc toParamUnderlyingType = paramType.UnderlyingType;
if (toParamUnderlyingType.IsPrimitive)
{
if (toParamUnderlyingType == fromParamUnderlyingType)
{
return true;
}
if (ArePrimitveTypesEquivalentSize(fromParamUnderlyingType, toParamUnderlyingType))
{
return true;
}
}
}
// Anything else is not a match
return false;
}
// Returns true of the two types are equivalent primitive types. Used by array casts.
static private bool ArePrimitveTypesEquivalentSize(TypeDesc type1, TypeDesc type2)
{
Debug.Assert(type1.IsPrimitive && type2.IsPrimitive);
// Primitive types such as E_T_I4 and E_T_U4 are interchangeable
// Enums with interchangeable underlying types are interchangable
// BOOL is NOT interchangeable with I1/U1, neither CHAR -- with I2/U2
// Float and double are not interchangable here.
int sourcePrimitiveTypeEquivalenceSize = type1.GetIntegralTypeMatchSize();
// Quick check to see if the first type can be matched.
if (sourcePrimitiveTypeEquivalenceSize == 0)
{
return false;
}
int targetPrimitiveTypeEquivalenceSize = type2.GetIntegralTypeMatchSize();
return sourcePrimitiveTypeEquivalenceSize == targetPrimitiveTypeEquivalenceSize;
}
private static int GetIntegralTypeMatchSize(this TypeDesc type)
{
Debug.Assert(type.IsPrimitive);
switch (type.Category)
{
case TypeFlags.SByte:
case TypeFlags.Byte:
return 1;
case TypeFlags.UInt16:
case TypeFlags.Int16:
return 2;
case TypeFlags.Int32:
case TypeFlags.UInt32:
return 4;
case TypeFlags.Int64:
case TypeFlags.UInt64:
return 8;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
return type.Context.Target.PointerSize;
default:
return 0;
}
}
private static bool CanCastToClassOrInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (otherType.IsInterface)
{
return thisType.CanCastToInterface(otherType, protect);
}
else
{
return thisType.CanCastToClass(otherType, protect);
}
}
private static bool CanCastToInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (!otherType.HasVariance)
{
return thisType.CanCastToNonVariantInterface(otherType,protect);
}
else
{
if (thisType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
foreach (var interfaceType in thisType.RuntimeInterfaces)
{
if (interfaceType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
}
}
return false;
}
private static bool CanCastToNonVariantInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
if (otherType == thisType)
{
return true;
}
foreach (var interfaceType in thisType.RuntimeInterfaces)
{
if (interfaceType == otherType)
{
return true;
}
}
return false;
}
private static bool CanCastByVarianceToInterfaceOrDelegate(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protectInput)
{
if (!thisType.HasSameTypeDefinition(otherType))
{
return false;
}
var stackOverflowProtectKey = new CastingPair(thisType, otherType);
if (protectInput != null)
{
if (protectInput.Contains(stackOverflowProtectKey))
return false;
}
StackOverflowProtect protect = new StackOverflowProtect(stackOverflowProtectKey, protectInput);
Instantiation instantiationThis = thisType.Instantiation;
Instantiation instantiationTarget = otherType.Instantiation;
Instantiation instantiationOpen = thisType.GetTypeDefinition().Instantiation;
Debug.Assert(instantiationThis.Length == instantiationTarget.Length &&
instantiationThis.Length == instantiationOpen.Length);
for (int i = 0; i < instantiationThis.Length; i++)
{
TypeDesc arg = instantiationThis[i];
TypeDesc targetArg = instantiationTarget[i];
if (arg != targetArg)
{
GenericParameterDesc openArgType = (GenericParameterDesc)instantiationOpen[i];
switch (openArgType.Variance)
{
case GenericVariance.Covariant:
if (!arg.IsBoxedAndCanCastTo(targetArg, protect))
return false;
break;
case GenericVariance.Contravariant:
if (!targetArg.IsBoxedAndCanCastTo(arg, protect))
return false;
break;
default:
// non-variant
Debug.Assert(openArgType.Variance == GenericVariance.None);
return false;
}
}
}
return true;
}
private static bool CanCastToClass(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
TypeDesc curType = thisType;
// If the target type has variant type parameters, we take a slower path
if (curType.HasVariance)
{
// First chase inheritance hierarchy until we hit a class that only differs in its instantiation
do
{
if (curType == otherType)
{
return true;
}
if (curType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect))
{
return true;
}
curType = curType.BaseType;
}
while (curType != null);
}
else
{
// If there are no variant type parameters, just chase the hierarchy
// Allow curType to be nullable, which means this method
// will additionally return true if curType is Nullable<T> && (
// currType == otherType
// OR otherType is System.ValueType or System.Object)
// Always strip Nullable from the otherType, if present
if (otherType.IsNullable && !curType.IsNullable)
{
return thisType.CanCastTo(otherType.Instantiation[0]);
}
do
{
if (curType == otherType)
return true;
curType = curType.BaseType;
} while (curType != null);
}
return false;
}
private static bool IsBoxedAndCanCastTo(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect)
{
TypeDesc fromUnderlyingType = thisType.UnderlyingType;
if (fromUnderlyingType.IsGCPointer)
{
return thisType.CanCastToInternal(otherType, protect);
}
else if (thisType.IsGenericParameter)
{
var genericVariableFromParam = (GenericParameterDesc)thisType;
if (genericVariableFromParam.HasReferenceTypeConstraint)
{
return genericVariableFromParam.CanCastToInternal(otherType, protect);
}
}
return false;
}
private class StackOverflowProtect
{
private CastingPair _value;
private StackOverflowProtect _previous;
public StackOverflowProtect(CastingPair value, StackOverflowProtect previous)
{
_value = value;
_previous = previous;
}
public bool Contains(CastingPair value)
{
for (var current = this; current != null; current = current._previous)
if (current._value.Equals(value))
return true;
return false;
}
}
private struct CastingPair
{
public readonly TypeDesc FromType;
public readonly TypeDesc ToType;
public CastingPair(TypeDesc fromType, TypeDesc toType)
{
FromType = fromType;
ToType = toType;
}
public bool Equals(CastingPair other) => FromType == other.FromType && ToType == other.ToType;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Discounts;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Shipping;
using Nop.Core.Domain.Tax;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Discounts;
using Nop.Services.Payments;
using Nop.Services.Shipping;
using Nop.Services.Tax;
namespace Nop.Services.Orders
{
/// <summary>
/// Order service
/// </summary>
public partial class OrderTotalCalculationService : IOrderTotalCalculationService
{
#region Fields
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly IPriceCalculationService _priceCalculationService;
private readonly ITaxService _taxService;
private readonly IShippingService _shippingService;
private readonly IPaymentService _paymentService;
private readonly ICheckoutAttributeParser _checkoutAttributeParser;
private readonly IDiscountService _discountService;
private readonly IGiftCardService _giftCardService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly TaxSettings _taxSettings;
private readonly RewardPointsSettings _rewardPointsSettings;
private readonly ShippingSettings _shippingSettings;
private readonly ShoppingCartSettings _shoppingCartSettings;
private readonly CatalogSettings _catalogSettings;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="workContext">Work context</param>
/// <param name="storeContext">Store context</param>
/// <param name="priceCalculationService">Price calculation service</param>
/// <param name="taxService">Tax service</param>
/// <param name="shippingService">Shipping service</param>
/// <param name="paymentService">Payment service</param>
/// <param name="checkoutAttributeParser">Checkout attribute parser</param>
/// <param name="discountService">Discount service</param>
/// <param name="giftCardService">Gift card service</param>
/// <param name="genericAttributeService">Generic attribute service</param>
/// <param name="taxSettings">Tax settings</param>
/// <param name="rewardPointsSettings">Reward points settings</param>
/// <param name="shippingSettings">Shipping settings</param>
/// <param name="shoppingCartSettings">Shopping cart settings</param>
/// <param name="catalogSettings">Catalog settings</param>
public OrderTotalCalculationService(IWorkContext workContext,
IStoreContext storeContext,
IPriceCalculationService priceCalculationService,
ITaxService taxService,
IShippingService shippingService,
IPaymentService paymentService,
ICheckoutAttributeParser checkoutAttributeParser,
IDiscountService discountService,
IGiftCardService giftCardService,
IGenericAttributeService genericAttributeService,
TaxSettings taxSettings,
RewardPointsSettings rewardPointsSettings,
ShippingSettings shippingSettings,
ShoppingCartSettings shoppingCartSettings,
CatalogSettings catalogSettings)
{
this._workContext = workContext;
this._storeContext = storeContext;
this._priceCalculationService = priceCalculationService;
this._taxService = taxService;
this._shippingService = shippingService;
this._paymentService = paymentService;
this._checkoutAttributeParser = checkoutAttributeParser;
this._discountService = discountService;
this._giftCardService = giftCardService;
this._genericAttributeService = genericAttributeService;
this._taxSettings = taxSettings;
this._rewardPointsSettings = rewardPointsSettings;
this._shippingSettings = shippingSettings;
this._shoppingCartSettings = shoppingCartSettings;
this._catalogSettings = catalogSettings;
}
#endregion
#region Utilities
/// <summary>
/// Gets an order discount (applied to order subtotal)
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="orderSubTotal">Order subtotal</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Order discount</returns>
protected virtual decimal GetOrderSubtotalDiscount(Customer customer,
decimal orderSubTotal, out Discount appliedDiscount)
{
appliedDiscount = null;
decimal discountAmount = decimal.Zero;
if (_catalogSettings.IgnoreDiscounts)
return discountAmount;
var allDiscounts = _discountService.GetAllDiscounts(DiscountType.AssignedToOrderSubTotal);
var allowedDiscounts = new List<Discount>();
if (allDiscounts != null)
foreach (var discount in allDiscounts)
if (_discountService.IsDiscountValid(discount, customer) &&
discount.DiscountType == DiscountType.AssignedToOrderSubTotal &&
!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
appliedDiscount = allowedDiscounts.GetPreferredDiscount(orderSubTotal);
if (appliedDiscount != null)
discountAmount = appliedDiscount.GetDiscountAmount(orderSubTotal);
if (discountAmount < decimal.Zero)
discountAmount = decimal.Zero;
return discountAmount;
}
/// <summary>
/// Gets a shipping discount
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shippingTotal">Shipping total</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Shipping discount</returns>
protected virtual decimal GetShippingDiscount(Customer customer, decimal shippingTotal, out Discount appliedDiscount)
{
appliedDiscount = null;
decimal shippingDiscountAmount = decimal.Zero;
if (_catalogSettings.IgnoreDiscounts)
return shippingDiscountAmount;
var allDiscounts = _discountService.GetAllDiscounts(DiscountType.AssignedToShipping);
var allowedDiscounts = new List<Discount>();
if (allDiscounts != null)
foreach (var discount in allDiscounts)
if (_discountService.IsDiscountValid(discount, customer) &&
discount.DiscountType == DiscountType.AssignedToShipping &&
!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
appliedDiscount = allowedDiscounts.GetPreferredDiscount(shippingTotal);
if (appliedDiscount != null)
{
shippingDiscountAmount = appliedDiscount.GetDiscountAmount(shippingTotal);
}
if (shippingDiscountAmount < decimal.Zero)
shippingDiscountAmount = decimal.Zero;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
shippingDiscountAmount = Math.Round(shippingDiscountAmount, 2);
return shippingDiscountAmount;
}
/// <summary>
/// Gets an order discount (applied to order total)
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="orderTotal">Order total</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Order discount</returns>
protected virtual decimal GetOrderTotalDiscount(Customer customer, decimal orderTotal, out Discount appliedDiscount)
{
appliedDiscount = null;
decimal discountAmount = decimal.Zero;
if (_catalogSettings.IgnoreDiscounts)
return discountAmount;
var allDiscounts = _discountService.GetAllDiscounts(DiscountType.AssignedToOrderTotal);
var allowedDiscounts = new List<Discount>();
if (allDiscounts != null)
foreach (var discount in allDiscounts)
if (_discountService.IsDiscountValid(discount, customer) &&
discount.DiscountType == DiscountType.AssignedToOrderTotal &&
!allowedDiscounts.ContainsDiscount(discount))
allowedDiscounts.Add(discount);
appliedDiscount = allowedDiscounts.GetPreferredDiscount(orderTotal);
if (appliedDiscount != null)
discountAmount = appliedDiscount.GetDiscountAmount(orderTotal);
if (discountAmount < decimal.Zero)
discountAmount = decimal.Zero;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
discountAmount = Math.Round(discountAmount, 2);
return discountAmount;
}
#endregion
#region Methods
/// <summary>
/// Gets shopping cart subtotal
/// </summary>
/// <param name="cart">Cart</param>
/// <param name="includingTax">A value indicating whether calculated price should include tax</param>
/// <param name="discountAmount">Applied discount amount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <param name="subTotalWithoutDiscount">Sub total (without discount)</param>
/// <param name="subTotalWithDiscount">Sub total (with discount)</param>
public virtual void GetShoppingCartSubTotal(IList<ShoppingCartItem> cart,
bool includingTax,
out decimal discountAmount, out Discount appliedDiscount,
out decimal subTotalWithoutDiscount, out decimal subTotalWithDiscount)
{
SortedDictionary<decimal, decimal> taxRates = null;
GetShoppingCartSubTotal(cart, includingTax,
out discountAmount, out appliedDiscount,
out subTotalWithoutDiscount, out subTotalWithDiscount, out taxRates);
}
/// <summary>
/// Gets shopping cart subtotal
/// </summary>
/// <param name="cart">Cart</param>
/// <param name="includingTax">A value indicating whether calculated price should include tax</param>
/// <param name="discountAmount">Applied discount amount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <param name="subTotalWithoutDiscount">Sub total (without discount)</param>
/// <param name="subTotalWithDiscount">Sub total (with discount)</param>
/// <param name="taxRates">Tax rates (of order sub total)</param>
public virtual void GetShoppingCartSubTotal(IList<ShoppingCartItem> cart,
bool includingTax,
out decimal discountAmount, out Discount appliedDiscount,
out decimal subTotalWithoutDiscount, out decimal subTotalWithDiscount,
out SortedDictionary<decimal, decimal> taxRates)
{
discountAmount = decimal.Zero;
appliedDiscount = null;
subTotalWithoutDiscount = decimal.Zero;
subTotalWithDiscount = decimal.Zero;
taxRates = new SortedDictionary<decimal, decimal>();
if (cart.Count == 0)
return;
//get the customer
Customer customer = cart.GetCustomer();
//sub totals
decimal subTotalExclTaxWithoutDiscount = decimal.Zero;
decimal subTotalInclTaxWithoutDiscount = decimal.Zero;
foreach (var shoppingCartItem in cart)
{
decimal taxRate = decimal.Zero;
decimal sciSubTotal = _priceCalculationService.GetSubTotal(shoppingCartItem, true);
decimal sciExclTax = _taxService.GetProductPrice(shoppingCartItem.Product, sciSubTotal, false, customer, out taxRate);
decimal sciInclTax = _taxService.GetProductPrice(shoppingCartItem.Product, sciSubTotal, true, customer, out taxRate);
subTotalExclTaxWithoutDiscount += sciExclTax;
subTotalInclTaxWithoutDiscount += sciInclTax;
//tax rates
decimal sciTax = sciInclTax - sciExclTax;
if (taxRate > decimal.Zero && sciTax > decimal.Zero)
{
if (!taxRates.ContainsKey(taxRate))
{
taxRates.Add(taxRate, sciTax);
}
else
{
taxRates[taxRate] = taxRates[taxRate] + sciTax;
}
}
}
//checkout attributes
if (customer != null)
{
var checkoutAttributesXml = customer.GetAttribute<string>(SystemCustomerAttributeNames.CheckoutAttributes, _genericAttributeService, _storeContext.CurrentStore.Id);
var caValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(checkoutAttributesXml);
if (caValues!=null)
{
foreach (var caValue in caValues)
{
decimal taxRate = decimal.Zero;
decimal caExclTax = _taxService.GetCheckoutAttributePrice(caValue, false, customer, out taxRate);
decimal caInclTax = _taxService.GetCheckoutAttributePrice(caValue, true, customer, out taxRate);
subTotalExclTaxWithoutDiscount += caExclTax;
subTotalInclTaxWithoutDiscount += caInclTax;
//tax rates
decimal caTax = caInclTax - caExclTax;
if (taxRate > decimal.Zero && caTax > decimal.Zero)
{
if (!taxRates.ContainsKey(taxRate))
{
taxRates.Add(taxRate, caTax);
}
else
{
taxRates[taxRate] = taxRates[taxRate] + caTax;
}
}
}
}
}
//subtotal without discount
if (includingTax)
subTotalWithoutDiscount = subTotalInclTaxWithoutDiscount;
else
subTotalWithoutDiscount = subTotalExclTaxWithoutDiscount;
if (subTotalWithoutDiscount < decimal.Zero)
subTotalWithoutDiscount = decimal.Zero;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
subTotalWithoutDiscount = Math.Round(subTotalWithoutDiscount, 2);
/*We calculate discount amount on order subtotal excl tax (discount first)*/
//calculate discount amount ('Applied to order subtotal' discount)
decimal discountAmountExclTax = GetOrderSubtotalDiscount(customer, subTotalExclTaxWithoutDiscount, out appliedDiscount);
if (subTotalExclTaxWithoutDiscount < discountAmountExclTax)
discountAmountExclTax = subTotalExclTaxWithoutDiscount;
decimal discountAmountInclTax = discountAmountExclTax;
//subtotal with discount (excl tax)
decimal subTotalExclTaxWithDiscount = subTotalExclTaxWithoutDiscount - discountAmountExclTax;
decimal subTotalInclTaxWithDiscount = subTotalExclTaxWithDiscount;
//add tax for shopping items & checkout attributes
Dictionary<decimal, decimal> tempTaxRates = new Dictionary<decimal, decimal>(taxRates);
foreach (KeyValuePair<decimal, decimal> kvp in tempTaxRates)
{
decimal taxRate = kvp.Key;
decimal taxValue = kvp.Value;
if (taxValue != decimal.Zero)
{
//discount the tax amount that applies to subtotal items
if (subTotalExclTaxWithoutDiscount > decimal.Zero)
{
decimal discountTax = taxRates[taxRate] * (discountAmountExclTax / subTotalExclTaxWithoutDiscount);
discountAmountInclTax += discountTax;
taxValue = taxRates[taxRate] - discountTax;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
taxValue = Math.Round(taxValue, 2);
taxRates[taxRate] = taxValue;
}
//subtotal with discount (incl tax)
subTotalInclTaxWithDiscount += taxValue;
}
}
if (_shoppingCartSettings.RoundPricesDuringCalculation)
{
discountAmountInclTax = Math.Round(discountAmountInclTax, 2);
discountAmountExclTax = Math.Round(discountAmountExclTax, 2);
}
if (includingTax)
{
subTotalWithDiscount = subTotalInclTaxWithDiscount;
discountAmount = discountAmountInclTax;
}
else
{
subTotalWithDiscount = subTotalExclTaxWithDiscount;
discountAmount = discountAmountExclTax;
}
if (subTotalWithDiscount < decimal.Zero)
subTotalWithDiscount = decimal.Zero;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
subTotalWithDiscount = Math.Round(subTotalWithDiscount, 2);
}
/// <summary>
/// Gets shopping cart additional shipping charge
/// </summary>
/// <param name="cart">Cart</param>
/// <returns>Additional shipping charge</returns>
public virtual decimal GetShoppingCartAdditionalShippingCharge(IList<ShoppingCartItem> cart)
{
decimal additionalShippingCharge = decimal.Zero;
bool isFreeShipping = IsFreeShipping(cart);
if (isFreeShipping)
return decimal.Zero;
foreach (var sci in cart)
if (sci.IsShipEnabled && !sci.IsFreeShipping)
additionalShippingCharge += sci.AdditionalShippingCharge;
return additionalShippingCharge;
}
/// <summary>
/// Gets a value indicating whether shipping is free
/// </summary>
/// <param name="cart">Cart</param>
/// <returns>A value indicating whether shipping is free</returns>
public virtual bool IsFreeShipping(IList<ShoppingCartItem> cart)
{
Customer customer = cart.GetCustomer();
if (customer != null)
{
//check whether customer is in a customer role with free shipping applied
var customerRoles = customer.CustomerRoles.Where(cr => cr.Active);
foreach (var customerRole in customerRoles)
if (customerRole.FreeShipping)
return true;
}
bool shoppingCartRequiresShipping = cart.RequiresShipping();
if (!shoppingCartRequiresShipping)
return true;
//check whether all shopping cart items are marked as free shipping
bool allItemsAreFreeShipping = true;
foreach (var sc in cart)
{
if (sc.IsShipEnabled && !sc.IsFreeShipping)
{
allItemsAreFreeShipping = false;
break;
}
}
if (allItemsAreFreeShipping)
return true;
//free shipping over $X
if (_shippingSettings.FreeShippingOverXEnabled)
{
//check whether we have subtotal enough to have free shipping
decimal subTotalDiscountAmount = decimal.Zero;
Discount subTotalAppliedDiscount = null;
decimal subTotalWithoutDiscountBase = decimal.Zero;
decimal subTotalWithDiscountBase = decimal.Zero;
GetShoppingCartSubTotal(cart, _shippingSettings.FreeShippingOverXIncludingTax, out subTotalDiscountAmount,
out subTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase);
if (subTotalWithDiscountBase > _shippingSettings.FreeShippingOverXValue)
return true;
}
//otherwise, return false
return false;
}
/// <summary>
/// Adjust shipping rate (free shipping, additional charges, discounts)
/// </summary>
/// <param name="shippingRate">Shipping rate to adjust</param>
/// <param name="cart">Cart</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Adjusted shipping rate</returns>
public virtual decimal AdjustShippingRate(decimal shippingRate,
IList<ShoppingCartItem> cart, out Discount appliedDiscount)
{
appliedDiscount = null;
//free shipping
if (IsFreeShipping(cart))
return decimal.Zero;
//additional shipping charges
decimal additionalShippingCharge = GetShoppingCartAdditionalShippingCharge(cart);
var adjustedRate = shippingRate + additionalShippingCharge;
//discount
var customer = cart.GetCustomer();
decimal discountAmount = GetShippingDiscount(customer, adjustedRate, out appliedDiscount);
adjustedRate = adjustedRate - discountAmount;
if (adjustedRate < decimal.Zero)
adjustedRate = decimal.Zero;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
adjustedRate = Math.Round(adjustedRate, 2);
return adjustedRate;
}
/// <summary>
/// Gets shopping cart shipping total
/// </summary>
/// <param name="cart">Cart</param>
/// <returns>Shipping total</returns>
public virtual decimal? GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart)
{
bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return GetShoppingCartShippingTotal(cart, includingTax);
}
/// <summary>
/// Gets shopping cart shipping total
/// </summary>
/// <param name="cart">Cart</param>
/// <param name="includingTax">A value indicating whether calculated price should include tax</param>
/// <returns>Shipping total</returns>
public virtual decimal? GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax)
{
decimal taxRate = decimal.Zero;
return GetShoppingCartShippingTotal(cart, includingTax, out taxRate);
}
/// <summary>
/// Gets shopping cart shipping total
/// </summary>
/// <param name="cart">Cart</param>
/// <param name="includingTax">A value indicating whether calculated price should include tax</param>
/// <param name="taxRate">Applied tax rate</param>
/// <returns>Shipping total</returns>
public virtual decimal? GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax,
out decimal taxRate)
{
Discount appliedDiscount = null;
return GetShoppingCartShippingTotal(cart, includingTax, out taxRate, out appliedDiscount);
}
/// <summary>
/// Gets shopping cart shipping total
/// </summary>
/// <param name="cart">Cart</param>
/// <param name="includingTax">A value indicating whether calculated price should include tax</param>
/// <param name="taxRate">Applied tax rate</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <returns>Shipping total</returns>
public virtual decimal? GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax,
out decimal taxRate, out Discount appliedDiscount)
{
decimal? shippingTotal = null;
decimal? shippingTotalTaxed = null;
appliedDiscount = null;
taxRate = decimal.Zero;
var customer = cart.GetCustomer();
bool isFreeShipping = IsFreeShipping(cart);
if (isFreeShipping)
return decimal.Zero;
ShippingOption shippingOption = null;
if (customer != null)
shippingOption = customer.GetAttribute<ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, _genericAttributeService, _storeContext.CurrentStore.Id);
if (shippingOption != null)
{
//use last shipping option (get from cache)
//adjust shipping rate
shippingTotal = AdjustShippingRate(shippingOption.Rate, cart, out appliedDiscount);
}
else
{
//use fixed rate (if possible)
Address shippingAddress = null;
if (customer != null)
shippingAddress = customer.ShippingAddress;
var shippingRateComputationMethods = _shippingService.LoadActiveShippingRateComputationMethods(_storeContext.CurrentStore.Id);
if (shippingRateComputationMethods == null || shippingRateComputationMethods.Count == 0)
throw new NopException("Shipping rate computation method could not be loaded");
if (shippingRateComputationMethods.Count == 1)
{
var shippingRateComputationMethod = shippingRateComputationMethods[0];
var shippingOptionRequests = _shippingService.CreateShippingOptionRequests(cart, shippingAddress);
decimal? fixedRate = null;
foreach (var shippingOptionRequest in shippingOptionRequests)
{
//calculate fixed rates for each request-package
var fixedRateTmp = shippingRateComputationMethod.GetFixedRate(shippingOptionRequest);
if (fixedRateTmp.HasValue)
{
if (!fixedRate.HasValue)
fixedRate = decimal.Zero;
fixedRate += fixedRateTmp.Value;
}
}
if (fixedRate.HasValue)
{
//adjust shipping rate
shippingTotal = AdjustShippingRate(fixedRate.Value, cart, out appliedDiscount);
}
}
}
if (shippingTotal.HasValue)
{
if (shippingTotal.Value < decimal.Zero)
shippingTotal = decimal.Zero;
//round
if (_shoppingCartSettings.RoundPricesDuringCalculation)
shippingTotal = Math.Round(shippingTotal.Value, 2);
shippingTotalTaxed = _taxService.GetShippingPrice(shippingTotal.Value,
includingTax,
customer,
out taxRate);
//round
if (_shoppingCartSettings.RoundPricesDuringCalculation)
shippingTotalTaxed = Math.Round(shippingTotalTaxed.Value, 2);
}
return shippingTotalTaxed;
}
/// <summary>
/// Gets tax
/// </summary>
/// <param name="cart">Shopping cart</param>
/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating tax</param>
/// <returns>Tax total</returns>
public virtual decimal GetTaxTotal(IList<ShoppingCartItem> cart, bool usePaymentMethodAdditionalFee = true)
{
if (cart == null)
throw new ArgumentNullException("cart");
SortedDictionary<decimal, decimal> taxRates = null;
return GetTaxTotal(cart, out taxRates, usePaymentMethodAdditionalFee);
}
/// <summary>
/// Gets tax
/// </summary>
/// <param name="cart">Shopping cart</param>
/// <param name="taxRates">Tax rates</param>
/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating tax</param>
/// <returns>Tax total</returns>
public virtual decimal GetTaxTotal(IList<ShoppingCartItem> cart,
out SortedDictionary<decimal, decimal> taxRates, bool usePaymentMethodAdditionalFee = true)
{
if (cart == null)
throw new ArgumentNullException("cart");
taxRates = new SortedDictionary<decimal, decimal>();
var customer = cart.GetCustomer();
string paymentMethodSystemName = "";
if (customer != null)
{
paymentMethodSystemName = customer.GetAttribute<string>(
SystemCustomerAttributeNames.SelectedPaymentMethod,
_genericAttributeService,
_storeContext.CurrentStore.Id);
}
//order sub total (items + checkout attributes)
decimal subTotalTaxTotal = decimal.Zero;
decimal orderSubTotalDiscountAmount = decimal.Zero;
Discount orderSubTotalAppliedDiscount = null;
decimal subTotalWithoutDiscountBase = decimal.Zero;
decimal subTotalWithDiscountBase = decimal.Zero;
SortedDictionary<decimal, decimal> orderSubTotalTaxRates = null;
GetShoppingCartSubTotal(cart, false,
out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount,
out subTotalWithoutDiscountBase, out subTotalWithDiscountBase,
out orderSubTotalTaxRates);
foreach (KeyValuePair<decimal, decimal> kvp in orderSubTotalTaxRates)
{
decimal taxRate = kvp.Key;
decimal taxValue = kvp.Value;
subTotalTaxTotal += taxValue;
if (taxRate > decimal.Zero && taxValue > decimal.Zero)
{
if (!taxRates.ContainsKey(taxRate))
taxRates.Add(taxRate, taxValue);
else
taxRates[taxRate] = taxRates[taxRate] + taxValue;
}
}
//shipping
decimal shippingTax = decimal.Zero;
if (_taxSettings.ShippingIsTaxable)
{
decimal taxRate = decimal.Zero;
decimal? shippingExclTax = GetShoppingCartShippingTotal(cart, false, out taxRate);
decimal? shippingInclTax = GetShoppingCartShippingTotal(cart, true, out taxRate);
if (shippingExclTax.HasValue && shippingInclTax.HasValue)
{
shippingTax = shippingInclTax.Value - shippingExclTax.Value;
//ensure that tax is equal or greater than zero
if (shippingTax < decimal.Zero)
shippingTax = decimal.Zero;
//tax rates
if (taxRate > decimal.Zero && shippingTax > decimal.Zero)
{
if (!taxRates.ContainsKey(taxRate))
taxRates.Add(taxRate, shippingTax);
else
taxRates[taxRate] = taxRates[taxRate] + shippingTax;
}
}
}
//payment method additional fee
decimal paymentMethodAdditionalFeeTax = decimal.Zero;
if (usePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable)
{
decimal taxRate = decimal.Zero;
decimal paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);
decimal paymentMethodAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer, out taxRate);
decimal paymentMethodAdditionalFeeInclTax = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer, out taxRate);
paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;
//ensure that tax is equal or greater than zero
if (paymentMethodAdditionalFeeTax < decimal.Zero)
paymentMethodAdditionalFeeTax = decimal.Zero;
//tax rates
if (taxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
{
if (!taxRates.ContainsKey(taxRate))
taxRates.Add(taxRate, paymentMethodAdditionalFeeTax);
else
taxRates[taxRate] = taxRates[taxRate] + paymentMethodAdditionalFeeTax;
}
}
//add at least one tax rate (0%)
if (taxRates.Count == 0)
taxRates.Add(decimal.Zero, decimal.Zero);
//summarize taxes
decimal taxTotal = subTotalTaxTotal + shippingTax + paymentMethodAdditionalFeeTax;
//ensure that tax is equal or greater than zero
if (taxTotal < decimal.Zero)
taxTotal = decimal.Zero;
//round tax
if (_shoppingCartSettings.RoundPricesDuringCalculation)
taxTotal = Math.Round(taxTotal, 2);
return taxTotal;
}
/// <summary>
/// Gets shopping cart total
/// </summary>
/// <param name="cart">Cart</param>
/// <param name="ignoreRewardPonts">A value indicating whether we should ignore reward points (if enabled and a customer is going to use them)</param>
/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating order total</param>
/// <returns>Shopping cart total;Null if shopping cart total couldn't be calculated now</returns>
public virtual decimal? GetShoppingCartTotal(IList<ShoppingCartItem> cart,
bool ignoreRewardPonts = false, bool usePaymentMethodAdditionalFee = true)
{
decimal discountAmount = decimal.Zero;
Discount appliedDiscount = null;
int redeemedRewardPoints = 0;
decimal redeemedRewardPointsAmount = decimal.Zero;
List<AppliedGiftCard> appliedGiftCards = null;
return GetShoppingCartTotal(cart, out discountAmount, out appliedDiscount,
out appliedGiftCards,
out redeemedRewardPoints, out redeemedRewardPointsAmount, ignoreRewardPonts, usePaymentMethodAdditionalFee);
}
/// <summary>
/// Gets shopping cart total
/// </summary>
/// <param name="cart">Cart</param>
/// <param name="appliedGiftCards">Applied gift cards</param>
/// <param name="discountAmount">Applied discount amount</param>
/// <param name="appliedDiscount">Applied discount</param>
/// <param name="redeemedRewardPoints">Reward points to redeem</param>
/// <param name="redeemedRewardPointsAmount">Reward points amount in primary store currency to redeem</param>
/// <param name="ignoreRewardPonts">A value indicating whether we should ignore reward points (if enabled and a customer is going to use them)</param>
/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating order total</param>
/// <returns>Shopping cart total;Null if shopping cart total couldn't be calculated now</returns>
public virtual decimal? GetShoppingCartTotal(IList<ShoppingCartItem> cart,
out decimal discountAmount, out Discount appliedDiscount,
out List<AppliedGiftCard> appliedGiftCards,
out int redeemedRewardPoints, out decimal redeemedRewardPointsAmount,
bool ignoreRewardPonts = false, bool usePaymentMethodAdditionalFee = true)
{
redeemedRewardPoints = 0;
redeemedRewardPointsAmount = decimal.Zero;
var customer = cart.GetCustomer();
string paymentMethodSystemName = "";
if (customer != null)
{
paymentMethodSystemName = customer.GetAttribute<string>(
SystemCustomerAttributeNames.SelectedPaymentMethod,
_genericAttributeService,
_storeContext.CurrentStore.Id);
}
//subtotal without tax
decimal subtotalBase = decimal.Zero;
decimal orderSubTotalDiscountAmount = decimal.Zero;
Discount orderSubTotalAppliedDiscount = null;
decimal subTotalWithoutDiscountBase = decimal.Zero;
decimal subTotalWithDiscountBase = decimal.Zero;
GetShoppingCartSubTotal(cart, false,
out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount,
out subTotalWithoutDiscountBase, out subTotalWithDiscountBase);
//subtotal with discount
subtotalBase = subTotalWithDiscountBase;
//shipping without tax
decimal? shoppingCartShipping = GetShoppingCartShippingTotal(cart, false);
//payment method additional fee without tax
decimal paymentMethodAdditionalFeeWithoutTax = decimal.Zero;
if (usePaymentMethodAdditionalFee && !String.IsNullOrEmpty(paymentMethodSystemName))
{
decimal paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);
paymentMethodAdditionalFeeWithoutTax = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee,
false, customer);
}
//tax
decimal shoppingCartTax = GetTaxTotal(cart, usePaymentMethodAdditionalFee);
//order total
decimal resultTemp = decimal.Zero;
resultTemp += subtotalBase;
if (shoppingCartShipping.HasValue)
{
resultTemp += shoppingCartShipping.Value;
}
resultTemp += paymentMethodAdditionalFeeWithoutTax;
resultTemp += shoppingCartTax;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
resultTemp = Math.Round(resultTemp, 2);
#region Order total discount
discountAmount = GetOrderTotalDiscount(customer, resultTemp, out appliedDiscount);
//sub totals with discount
if (resultTemp < discountAmount)
discountAmount = resultTemp;
//reduce subtotal
resultTemp -= discountAmount;
if (resultTemp < decimal.Zero)
resultTemp = decimal.Zero;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
resultTemp = Math.Round(resultTemp, 2);
#endregion
#region Applied gift cards
//let's apply gift cards now (gift cards that can be used)
appliedGiftCards = new List<AppliedGiftCard>();
if (!cart.IsRecurring())
{
//we don't apply gift cards for recurring products
var giftCards = _giftCardService.GetActiveGiftCardsAppliedByCustomer(customer);
if (giftCards!=null)
foreach (var gc in giftCards)
if (resultTemp > decimal.Zero)
{
decimal remainingAmount = gc.GetGiftCardRemainingAmount();
decimal amountCanBeUsed = decimal.Zero;
if (resultTemp > remainingAmount)
amountCanBeUsed = remainingAmount;
else
amountCanBeUsed = resultTemp;
//reduce subtotal
resultTemp -= amountCanBeUsed;
var appliedGiftCard = new AppliedGiftCard();
appliedGiftCard.GiftCard = gc;
appliedGiftCard.AmountCanBeUsed = amountCanBeUsed;
appliedGiftCards.Add(appliedGiftCard);
}
}
#endregion
if (resultTemp < decimal.Zero)
resultTemp = decimal.Zero;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
resultTemp = Math.Round(resultTemp, 2);
decimal? orderTotal = null;
if (!shoppingCartShipping.HasValue)
{
//return null if we have errors
orderTotal = null;
return orderTotal;
}
else
{
//return result if we have no errors
orderTotal = resultTemp;
}
#region Reward points
if (_rewardPointsSettings.Enabled &&
!ignoreRewardPonts &&
customer.GetAttribute<bool>(SystemCustomerAttributeNames.UseRewardPointsDuringCheckout,
_genericAttributeService, _storeContext.CurrentStore.Id))
{
int rewardPointsBalance = customer.GetRewardPointsBalance();
if (CheckMinimumRewardPointsToUseRequirement(rewardPointsBalance))
{
decimal rewardPointsBalanceAmount = ConvertRewardPointsToAmount(rewardPointsBalance);
if (orderTotal.HasValue && orderTotal.Value > decimal.Zero)
{
if (orderTotal.Value > rewardPointsBalanceAmount)
{
redeemedRewardPoints = rewardPointsBalance;
redeemedRewardPointsAmount = rewardPointsBalanceAmount;
}
else
{
redeemedRewardPointsAmount = orderTotal.Value;
redeemedRewardPoints = ConvertAmountToRewardPoints(redeemedRewardPointsAmount);
}
}
}
}
#endregion
if (orderTotal.HasValue)
{
orderTotal = orderTotal.Value - redeemedRewardPointsAmount;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
orderTotal = Math.Round(orderTotal.Value, 2);
return orderTotal;
}
else
return null;
}
/// <summary>
/// Converts reward points to amount primary store currency
/// </summary>
/// <param name="rewardPoints">Reward points</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertRewardPointsToAmount(int rewardPoints)
{
decimal result = decimal.Zero;
if (rewardPoints <= 0)
return decimal.Zero;
result = rewardPoints * _rewardPointsSettings.ExchangeRate;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
result = Math.Round(result, 2);
return result;
}
/// <summary>
/// Converts an amount in primary store currency to reward points
/// </summary>
/// <param name="amount">Amount</param>
/// <returns>Converted value</returns>
public virtual int ConvertAmountToRewardPoints(decimal amount)
{
int result = 0;
if (amount <= 0)
return 0;
if (_rewardPointsSettings.ExchangeRate > 0)
result = (int)Math.Ceiling(amount / _rewardPointsSettings.ExchangeRate);
return result;
}
/// <summary>
/// Gets a value indicating whether a customer has minimum amount of reward points to use (if enabled)
/// </summary>
/// <param name="rewardPoints">Reward points to check</param>
/// <returns>true - reward points could use; false - cannot be used.</returns>
public virtual bool CheckMinimumRewardPointsToUseRequirement(int rewardPoints)
{
if (_rewardPointsSettings.MinimumRewardPointsToUse <= 0)
return true;
return rewardPoints >= _rewardPointsSettings.MinimumRewardPointsToUse;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal abstract class EditAndContinueTestHelpers
{
public abstract AbstractEditAndContinueAnalyzer Analyzer { get; }
public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span);
public abstract SyntaxTree ParseText(string source);
public abstract Compilation CreateLibraryCompilation(string name, IEnumerable<SyntaxTree> trees);
public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method);
internal void VerifyUnchangedDocument(
string source,
ActiveStatementSpan[] oldActiveStatements,
TextSpan?[] trackingSpansOpt,
TextSpan[] expectedNewActiveStatements,
ImmutableArray<TextSpan>[] expectedOldExceptionRegions,
ImmutableArray<TextSpan>[] expectedNewExceptionRegions)
{
var text = SourceText.From(source);
var tree = ParseText(source);
var root = tree.GetRoot();
tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
TestActiveStatementTrackingService trackingService;
if (trackingSpansOpt != null)
{
trackingService = new TestActiveStatementTrackingService(documentId, trackingSpansOpt);
}
else
{
trackingService = null;
}
var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
Analyzer.AnalyzeUnchangedDocument(
oldActiveStatements.AsImmutable(),
text,
root,
documentId,
trackingService,
actualNewActiveStatements,
actualNewExceptionRegions);
// check active statements:
AssertSpansEqual(expectedNewActiveStatements, actualNewActiveStatements, source, text);
// check new exception regions:
Assert.Equal(expectedNewExceptionRegions.Length, actualNewExceptionRegions.Length);
for (int i = 0; i < expectedNewExceptionRegions.Length; i++)
{
AssertSpansEqual(expectedNewExceptionRegions[i], actualNewExceptionRegions[i], source, text);
}
}
internal void VerifyRudeDiagnostics(
EditScript<SyntaxNode> editScript,
ActiveStatementsDescription description,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
var oldActiveStatements = description.OldSpans;
if (description.TrackingSpans != null)
{
Assert.Equal(oldActiveStatements.Length, description.TrackingSpans.Length);
}
string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
var diagnostics = new List<RudeEditDiagnostic>();
var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
var updatedActiveMethodMatches = new List<AbstractEditAndContinueAnalyzer.UpdatedMethodInfo>();
var editMap = Analyzer.BuildEditMap(editScript);
DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
TestActiveStatementTrackingService trackingService;
if (description.TrackingSpans != null)
{
trackingService = new TestActiveStatementTrackingService(documentId, description.TrackingSpans);
}
else
{
trackingService = null;
}
Analyzer.AnalyzeSyntax(
editScript,
editMap,
oldText,
newText,
documentId,
trackingService,
oldActiveStatements.AsImmutable(),
actualNewActiveStatements,
actualNewExceptionRegions,
updatedActiveMethodMatches,
diagnostics);
diagnostics.Verify(newSource, expectedDiagnostics);
// check active statements:
AssertSpansEqual(description.NewSpans, actualNewActiveStatements, newSource, newText);
if (diagnostics.Count == 0)
{
// check old exception regions:
for (int i = 0; i < oldActiveStatements.Length; i++)
{
var actualOldExceptionRegions = Analyzer.GetExceptionRegions(
oldText,
editScript.Match.OldRoot,
oldActiveStatements[i].Span,
isLeaf: (oldActiveStatements[i].Flags & ActiveStatementFlags.LeafFrame) != 0);
AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText);
}
// check new exception regions:
Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length);
for (int i = 0; i < description.NewRegions.Length; i++)
{
AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText);
}
}
else
{
for (int i = 0; i < oldActiveStatements.Length; i++)
{
Assert.Equal(0, description.NewRegions[i].Length);
}
}
if (description.TrackingSpans != null)
{
AssertEx.Equal(trackingService.TrackingSpans, description.NewSpans.Select(s => (TextSpan?)s));
}
}
internal void VerifyLineEdits(
EditScript<SyntaxNode> editScript,
IEnumerable<LineChange> expectedLineEdits,
IEnumerable<string> expectedNodeUpdates,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
var diagnostics = new List<RudeEditDiagnostic>();
var editMap = Analyzer.BuildEditMap(editScript);
var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>();
var actualLineEdits = new List<LineChange>();
Analyzer.AnalyzeTrivia(
oldText,
newText,
editScript.Match,
editMap,
triviaEdits,
actualLineEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource, expectedDiagnostics);
AssertEx.Equal(expectedLineEdits, actualLineEdits, itemSeparator: ",\r\n");
var actualNodeUpdates = triviaEdits.Select(e => e.Value.ToString().ToLines().First());
AssertEx.Equal(expectedNodeUpdates, actualNodeUpdates, itemSeparator: ",\r\n");
}
internal void VerifySemantics(
EditScript<SyntaxNode> editScript,
ActiveStatementsDescription activeStatements,
IEnumerable<string> additionalOldSources,
IEnumerable<string> additionalNewSources,
SemanticEditDescription[] expectedSemanticEdits,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
var editMap = Analyzer.BuildEditMap(editScript);
var oldRoot = editScript.Match.OldRoot;
var newRoot = editScript.Match.NewRoot;
var oldSource = oldRoot.SyntaxTree.ToString();
var newSource = newRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
IEnumerable<SyntaxTree> oldTrees = new[] { oldRoot.SyntaxTree };
IEnumerable<SyntaxTree> newTrees = new[] { newRoot.SyntaxTree };
if (additionalOldSources != null)
{
oldTrees = oldTrees.Concat(additionalOldSources.Select(s => ParseText(s)));
}
if (additionalOldSources != null)
{
newTrees = newTrees.Concat(additionalNewSources.Select(s => ParseText(s)));
}
var oldCompilation = CreateLibraryCompilation("Old", oldTrees);
var newCompilation = CreateLibraryCompilation("New", newTrees);
if (oldCompilation is CSharpCompilation)
{
oldCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
newCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
}
else
{
// TODO: verify all compilation diagnostics like C# does (tests need to be updated)
oldTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
newTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
}
var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree);
var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);
var oldActiveStatements = activeStatements.OldSpans.AsImmutable();
var updatedActiveMethodMatches = new List<AbstractEditAndContinueAnalyzer.UpdatedMethodInfo>();
var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>();
var actualLineEdits = new List<LineChange>();
var actualSemanticEdits = new List<SemanticEdit>();
var diagnostics = new List<RudeEditDiagnostic>();
var actualNewActiveStatements = new LinePositionSpan[activeStatements.OldSpans.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[activeStatements.OldSpans.Length];
Analyzer.AnalyzeSyntax(
editScript,
editMap,
oldText,
newText,
null,
null,
oldActiveStatements,
actualNewActiveStatements,
actualNewExceptionRegions,
updatedActiveMethodMatches,
diagnostics);
diagnostics.Verify(newSource);
Analyzer.AnalyzeTrivia(
oldText,
newText,
editScript.Match,
editMap,
triviaEdits,
actualLineEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource);
Analyzer.AnalyzeSemantics(
editScript,
editMap,
oldText,
oldActiveStatements,
triviaEdits,
updatedActiveMethodMatches,
oldModel,
newModel,
actualSemanticEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource, expectedDiagnostics);
if (expectedSemanticEdits == null)
{
return;
}
Assert.Equal(expectedSemanticEdits.Length, actualSemanticEdits.Count);
for (int i = 0; i < actualSemanticEdits.Count; i++)
{
var editKind = expectedSemanticEdits[i].Kind;
Assert.Equal(editKind, actualSemanticEdits[i].Kind);
var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdits[i].SymbolProvider(oldCompilation) : null;
var expectedNewSymbol = expectedSemanticEdits[i].SymbolProvider(newCompilation);
var actualOldSymbol = actualSemanticEdits[i].OldSymbol;
var actualNewSymbol = actualSemanticEdits[i].NewSymbol;
Assert.Equal(expectedOldSymbol, actualOldSymbol);
Assert.Equal(expectedNewSymbol, actualNewSymbol);
var expectedSyntaxMap = expectedSemanticEdits[i].SyntaxMap;
var actualSyntaxMap = actualSemanticEdits[i].SyntaxMap;
Assert.Equal(expectedSemanticEdits[i].PreserveLocalVariables, actualSemanticEdits[i].PreserveLocalVariables);
if (expectedSyntaxMap != null)
{
Assert.NotNull(actualSyntaxMap);
Assert.True(expectedSemanticEdits[i].PreserveLocalVariables);
var newNodes = new List<SyntaxNode>();
foreach (var expectedSpanMapping in expectedSyntaxMap)
{
var newNode = FindNode(newRoot, expectedSpanMapping.Value);
var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key);
var actualOldNode = actualSyntaxMap(newNode);
Assert.Equal(expectedOldNode, actualOldNode);
newNodes.Add(newNode);
}
}
else
{
Assert.Null(actualSyntaxMap);
}
}
}
private static void AssertSpansEqual(IList<TextSpan> expected, IList<LinePositionSpan> actual, string newSource, SourceText newText)
{
AssertEx.Equal(
expected,
actual.Select(span => newText.Lines.GetTextSpan(span)),
itemSeparator: "\r\n",
itemInspector: s => DisplaySpan(newSource, s));
}
private static string DisplaySpan(string source, TextSpan span)
{
return span + ": [" + source.Substring(span.Start, span.Length).Replace("\r\n", " ") + "]";
}
internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch)
{
Dictionary<SyntaxNode, AbstractEditAndContinueAnalyzer.LambdaInfo> lazyActiveOrMatchedLambdas = null;
var map = analyzer.ComputeMap(bodyMatch, new AbstractEditAndContinueAnalyzer.ActiveNode[0], ref lazyActiveOrMatchedLambdas, new List<RudeEditDiagnostic>());
var result = new Dictionary<SyntaxNode, SyntaxNode>();
foreach (var pair in map.Forward)
{
if (pair.Value == bodyMatch.NewRoot)
{
Assert.Same(pair.Key, bodyMatch.OldRoot);
continue;
}
result.Add(pair.Key, pair.Value);
}
return result;
}
public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match)
{
return ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot));
}
public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches)
{
return new MatchingPairs(matches
.OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start)
.ThenByDescending(partners => partners.Key.Span.Length)
.Select(partners => new MatchingPair
{
Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "),
New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ")
}));
}
private static IEnumerable<KeyValuePair<K, V>> ReverseMapping<K, V>(IEnumerable<KeyValuePair<V, K>> mapping)
{
foreach (var pair in mapping)
{
yield return KeyValuePair.Create(pair.Value, pair.Key);
}
}
}
internal static class EditScriptTestUtils
{
public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected)
{
AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n");
}
}
}
| |
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.HostedServices;
using BTCPayServer.Payments;
using BTCPayServer.Services;
using BTCPayServer.Services.Rates;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
namespace BTCPayServer.Controllers.Greenfield
{
[ApiController]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
[EnableCors(CorsPolicies.All)]
public class GreenfieldPullPaymentController : ControllerBase
{
private readonly PullPaymentHostedService _pullPaymentService;
private readonly LinkGenerator _linkGenerator;
private readonly ApplicationDbContextFactory _dbContextFactory;
private readonly CurrencyNameTable _currencyNameTable;
private readonly BTCPayNetworkJsonSerializerSettings _serializerSettings;
private readonly BTCPayNetworkProvider _networkProvider;
private readonly IEnumerable<IPayoutHandler> _payoutHandlers;
public GreenfieldPullPaymentController(PullPaymentHostedService pullPaymentService,
LinkGenerator linkGenerator,
ApplicationDbContextFactory dbContextFactory,
CurrencyNameTable currencyNameTable,
Services.BTCPayNetworkJsonSerializerSettings serializerSettings,
BTCPayNetworkProvider networkProvider,
IEnumerable<IPayoutHandler> payoutHandlers)
{
_pullPaymentService = pullPaymentService;
_linkGenerator = linkGenerator;
_dbContextFactory = dbContextFactory;
_currencyNameTable = currencyNameTable;
_serializerSettings = serializerSettings;
_networkProvider = networkProvider;
_payoutHandlers = payoutHandlers;
}
[HttpGet("~/api/v1/stores/{storeId}/pull-payments")]
[Authorize(Policy = Policies.CanManagePullPayments, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<IActionResult> GetPullPayments(string storeId, bool includeArchived = false)
{
using var ctx = _dbContextFactory.CreateContext();
var pps = await ctx.PullPayments
.Where(p => p.StoreId == storeId && (includeArchived || !p.Archived))
.OrderByDescending(p => p.StartDate)
.ToListAsync();
return Ok(pps.Select(CreatePullPaymentData).ToArray());
}
[HttpPost("~/api/v1/stores/{storeId}/pull-payments")]
[Authorize(Policy = Policies.CanManagePullPayments, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<IActionResult> CreatePullPayment(string storeId, CreatePullPaymentRequest request)
{
if (request is null)
{
ModelState.AddModelError(string.Empty, "Missing body");
return this.CreateValidationError(ModelState);
}
if (request.Amount <= 0.0m)
{
ModelState.AddModelError(nameof(request.Amount), "The amount should more than 0.");
}
if (request.Name is String name && name.Length > 50)
{
ModelState.AddModelError(nameof(request.Name), "The name should be maximum 50 characters.");
}
if (request.Currency is String currency)
{
request.Currency = currency.ToUpperInvariant().Trim();
if (_currencyNameTable.GetCurrencyData(request.Currency, false) is null)
{
ModelState.AddModelError(nameof(request.Currency), "Invalid currency");
}
}
else
{
ModelState.AddModelError(nameof(request.Currency), "This field is required");
}
if (request.ExpiresAt is DateTimeOffset expires && request.StartsAt is DateTimeOffset start && expires < start)
{
ModelState.AddModelError(nameof(request.ExpiresAt), $"expiresAt should be higher than startAt");
}
if (request.Period <= TimeSpan.Zero)
{
ModelState.AddModelError(nameof(request.Period), $"The period should be positive");
}
if (request.BOLT11Expiration <= TimeSpan.Zero)
{
ModelState.AddModelError(nameof(request.BOLT11Expiration), $"The BOLT11 expiration should be positive");
}
PaymentMethodId?[]? paymentMethods = null;
if (request.PaymentMethods is { } paymentMethodsStr)
{
paymentMethods = paymentMethodsStr.Select(s =>
{
PaymentMethodId.TryParse(s, out var pmi);
return pmi;
}).ToArray();
var supported = (await _payoutHandlers.GetSupportedPaymentMethods(HttpContext.GetStoreData())).ToArray();
for (int i = 0; i < paymentMethods.Length; i++)
{
if (!supported.Contains(paymentMethods[i]))
{
request.AddModelError(paymentRequest => paymentRequest.PaymentMethods[i], "Invalid or unsupported payment method", this);
}
}
}
else
{
ModelState.AddModelError(nameof(request.PaymentMethods), "This field is required");
}
if (!ModelState.IsValid)
return this.CreateValidationError(ModelState);
var ppId = await _pullPaymentService.CreatePullPayment(new HostedServices.CreatePullPayment()
{
StartsAt = request.StartsAt,
ExpiresAt = request.ExpiresAt,
Period = request.Period,
BOLT11Expiration = request.BOLT11Expiration,
Name = request.Name,
Description = request.Description,
Amount = request.Amount,
Currency = request.Currency,
StoreId = storeId,
PaymentMethodIds = paymentMethods
});
var pp = await _pullPaymentService.GetPullPayment(ppId, false);
return this.Ok(CreatePullPaymentData(pp));
}
private Client.Models.PullPaymentData CreatePullPaymentData(Data.PullPaymentData pp)
{
var ppBlob = pp.GetBlob();
return new BTCPayServer.Client.Models.PullPaymentData()
{
Id = pp.Id,
StartsAt = pp.StartDate,
ExpiresAt = pp.EndDate,
Amount = ppBlob.Limit,
Name = ppBlob.Name,
Description = ppBlob.Description,
Currency = ppBlob.Currency,
Period = ppBlob.Period,
Archived = pp.Archived,
BOLT11Expiration = ppBlob.BOLT11Expiration,
ViewLink = _linkGenerator.GetUriByAction(
nameof(UIPullPaymentController.ViewPullPayment),
"UIPullPayment",
new { pullPaymentId = pp.Id },
Request.Scheme,
Request.Host,
Request.PathBase)
};
}
[HttpGet("~/api/v1/pull-payments/{pullPaymentId}")]
[AllowAnonymous]
public async Task<IActionResult> GetPullPayment(string pullPaymentId)
{
if (pullPaymentId is null)
return PullPaymentNotFound();
var pp = await _pullPaymentService.GetPullPayment(pullPaymentId, false);
if (pp is null)
return PullPaymentNotFound();
return Ok(CreatePullPaymentData(pp));
}
[HttpGet("~/api/v1/pull-payments/{pullPaymentId}/payouts")]
[AllowAnonymous]
public async Task<IActionResult> GetPayouts(string pullPaymentId, bool includeCancelled = false)
{
if (pullPaymentId is null)
return PullPaymentNotFound();
var pp = await _pullPaymentService.GetPullPayment(pullPaymentId, true);
if (pp is null)
return PullPaymentNotFound();
var payouts = pp.Payouts.Where(p => p.State != PayoutState.Cancelled || includeCancelled).ToList();
var cd = _currencyNameTable.GetCurrencyData(pp.GetBlob().Currency, false);
return base.Ok(payouts
.Select(p => ToModel(p, cd)).ToList());
}
[HttpGet("~/api/v1/pull-payments/{pullPaymentId}/payouts/{payoutId}")]
[AllowAnonymous]
public async Task<IActionResult> GetPayout(string pullPaymentId, string payoutId)
{
if (payoutId is null)
return PayoutNotFound();
await using var ctx = _dbContextFactory.CreateContext();
var pp = await _pullPaymentService.GetPullPayment(pullPaymentId, true);
if (pp is null)
return PullPaymentNotFound();
var payout = pp.Payouts.FirstOrDefault(p => p.Id == payoutId);
if (payout is null)
return PayoutNotFound();
var cd = _currencyNameTable.GetCurrencyData(payout.PullPaymentData.GetBlob().Currency, false);
return base.Ok(ToModel(payout, cd));
}
private Client.Models.PayoutData ToModel(Data.PayoutData p, CurrencyData cd)
{
var blob = p.GetBlob(_serializerSettings);
var model = new Client.Models.PayoutData()
{
Id = p.Id,
PullPaymentId = p.PullPaymentDataId,
Date = p.Date,
Amount = blob.Amount,
PaymentMethodAmount = blob.CryptoAmount,
Revision = blob.Revision,
State = p.State
};
model.Destination = blob.Destination;
model.PaymentMethod = p.PaymentMethodId;
model.CryptoCode = p.GetPaymentMethodId().CryptoCode;
return model;
}
[HttpPost("~/api/v1/pull-payments/{pullPaymentId}/payouts")]
[AllowAnonymous]
public async Task<IActionResult> CreatePayout(string pullPaymentId, CreatePayoutRequest request)
{
if (!PaymentMethodId.TryParse(request?.PaymentMethod, out var paymentMethodId))
{
ModelState.AddModelError(nameof(request.PaymentMethod), "Invalid payment method");
return this.CreateValidationError(ModelState);
}
var payoutHandler = _payoutHandlers.FindPayoutHandler(paymentMethodId);
if (payoutHandler is null)
{
ModelState.AddModelError(nameof(request.PaymentMethod), "Invalid payment method");
return this.CreateValidationError(ModelState);
}
await using var ctx = _dbContextFactory.CreateContext();
var pp = await ctx.PullPayments.FindAsync(pullPaymentId);
if (pp is null)
return PullPaymentNotFound();
var ppBlob = pp.GetBlob();
var destination = await payoutHandler.ParseAndValidateClaimDestination(paymentMethodId, request!.Destination, ppBlob);
if (destination.destination is null)
{
ModelState.AddModelError(nameof(request.Destination), destination.error ?? "The destination is invalid for the payment specified");
return this.CreateValidationError(ModelState);
}
if (request.Amount is null && destination.destination.Amount != null)
{
request.Amount = destination.destination.Amount;
}
else if (request.Amount != null && destination.destination.Amount != null && request.Amount != destination.destination.Amount)
{
ModelState.AddModelError(nameof(request.Amount), $"Amount is implied in destination ({destination.destination.Amount}) that does not match the payout amount provided {request.Amount})");
return this.CreateValidationError(ModelState);
}
if (request.Amount is { } v && (v < ppBlob.MinimumClaim || v == 0.0m))
{
ModelState.AddModelError(nameof(request.Amount), $"Amount too small (should be at least {ppBlob.MinimumClaim})");
return this.CreateValidationError(ModelState);
}
var cd = _currencyNameTable.GetCurrencyData(pp.GetBlob().Currency, false);
var result = await _pullPaymentService.Claim(new ClaimRequest()
{
Destination = destination.destination,
PullPaymentId = pullPaymentId,
Value = request.Amount,
PaymentMethodId = paymentMethodId
});
switch (result.Result)
{
case ClaimRequest.ClaimResult.Ok:
break;
case ClaimRequest.ClaimResult.Duplicate:
return this.CreateAPIError("duplicate-destination", ClaimRequest.GetErrorMessage(result.Result));
case ClaimRequest.ClaimResult.Expired:
return this.CreateAPIError("expired", ClaimRequest.GetErrorMessage(result.Result));
case ClaimRequest.ClaimResult.NotStarted:
return this.CreateAPIError("not-started", ClaimRequest.GetErrorMessage(result.Result));
case ClaimRequest.ClaimResult.Archived:
return this.CreateAPIError("archived", ClaimRequest.GetErrorMessage(result.Result));
case ClaimRequest.ClaimResult.Overdraft:
return this.CreateAPIError("overdraft", ClaimRequest.GetErrorMessage(result.Result));
case ClaimRequest.ClaimResult.AmountTooLow:
return this.CreateAPIError("amount-too-low", ClaimRequest.GetErrorMessage(result.Result));
case ClaimRequest.ClaimResult.PaymentMethodNotSupported:
return this.CreateAPIError("payment-method-not-supported", ClaimRequest.GetErrorMessage(result.Result));
default:
throw new NotSupportedException("Unsupported ClaimResult");
}
return Ok(ToModel(result.PayoutData, cd));
}
[HttpDelete("~/api/v1/stores/{storeId}/pull-payments/{pullPaymentId}")]
[Authorize(Policy = Policies.CanManagePullPayments, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<IActionResult> ArchivePullPayment(string storeId, string pullPaymentId)
{
using var ctx = _dbContextFactory.CreateContext();
var pp = await ctx.PullPayments.FindAsync(pullPaymentId);
if (pp is null || pp.StoreId != storeId)
return PullPaymentNotFound();
await _pullPaymentService.Cancel(new PullPaymentHostedService.CancelRequest(pullPaymentId));
return Ok();
}
[HttpDelete("~/api/v1/stores/{storeId}/payouts/{payoutId}")]
[Authorize(Policy = Policies.CanManagePullPayments, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<IActionResult> CancelPayout(string storeId, string payoutId)
{
using var ctx = _dbContextFactory.CreateContext();
var payout = await ctx.Payouts.GetPayout(payoutId, storeId);
if (payout is null)
return PayoutNotFound();
await _pullPaymentService.Cancel(new PullPaymentHostedService.CancelRequest(new[] { payoutId }));
return Ok();
}
[HttpPost("~/api/v1/stores/{storeId}/payouts/{payoutId}")]
[Authorize(Policy = Policies.CanManagePullPayments, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<IActionResult> ApprovePayout(string storeId, string payoutId, ApprovePayoutRequest approvePayoutRequest, CancellationToken cancellationToken = default)
{
using var ctx = _dbContextFactory.CreateContext();
ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
var revision = approvePayoutRequest?.Revision;
if (revision is null)
{
ModelState.AddModelError(nameof(approvePayoutRequest.Revision), "The `revision` property is required");
}
if (!ModelState.IsValid)
return this.CreateValidationError(ModelState);
var payout = await ctx.Payouts.GetPayout(payoutId, storeId, true, true);
if (payout is null)
return PayoutNotFound();
RateResult? rateResult = null;
try
{
rateResult = await _pullPaymentService.GetRate(payout, approvePayoutRequest?.RateRule, cancellationToken);
if (rateResult.BidAsk == null)
{
return this.CreateAPIError("rate-unavailable", $"Rate unavailable: {rateResult.EvaluatedRule}");
}
}
catch (FormatException)
{
ModelState.AddModelError(nameof(approvePayoutRequest.RateRule), "Invalid RateRule");
return this.CreateValidationError(ModelState);
}
var ppBlob = payout.PullPaymentData.GetBlob();
var cd = _currencyNameTable.GetCurrencyData(ppBlob.Currency, false);
var result = await _pullPaymentService.Approve(new PullPaymentHostedService.PayoutApproval()
{
PayoutId = payoutId,
Revision = revision!.Value,
Rate = rateResult.BidAsk.Ask
});
var errorMessage = PullPaymentHostedService.PayoutApproval.GetErrorMessage(result);
switch (result)
{
case PullPaymentHostedService.PayoutApproval.Result.Ok:
return Ok(ToModel(await ctx.Payouts.GetPayout(payoutId, storeId, true), cd));
case PullPaymentHostedService.PayoutApproval.Result.InvalidState:
return this.CreateAPIError("invalid-state", errorMessage);
case PullPaymentHostedService.PayoutApproval.Result.TooLowAmount:
return this.CreateAPIError("amount-too-low", errorMessage);
case PullPaymentHostedService.PayoutApproval.Result.OldRevision:
return this.CreateAPIError("old-revision", errorMessage);
case PullPaymentHostedService.PayoutApproval.Result.NotFound:
return PayoutNotFound();
default:
throw new NotSupportedException();
}
}
[HttpPost("~/api/v1/stores/{storeId}/payouts/{payoutId}/mark-paid")]
[Authorize(Policy = Policies.CanManagePullPayments, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<IActionResult> MarkPayoutPaid(string storeId, string payoutId, CancellationToken cancellationToken = default)
{
if (!ModelState.IsValid)
return this.CreateValidationError(ModelState);
var result = await _pullPaymentService.MarkPaid(new PayoutPaidRequest()
{
//TODO: Allow API to specify the manual proof object
Proof = null,
PayoutId = payoutId
});
var errorMessage = PayoutPaidRequest.GetErrorMessage(result);
switch (result)
{
case PayoutPaidRequest.PayoutPaidResult.Ok:
return Ok();
case PayoutPaidRequest.PayoutPaidResult.InvalidState:
return this.CreateAPIError("invalid-state", errorMessage);
case PayoutPaidRequest.PayoutPaidResult.NotFound:
return PayoutNotFound();
default:
throw new NotSupportedException();
}
}
private IActionResult PayoutNotFound()
{
return this.CreateAPIError(404, "payout-not-found", "The payout was not found");
}
private IActionResult PullPaymentNotFound()
{
return this.CreateAPIError(404, "pullpayment-not-found", "The pull payment was not found");
}
}
}
| |
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using RestSharp;
using System.Text;
using Gx.Conclusion;
using Gx.Rs.Api.Util;
using Gx.Links;
using System.Net;
using System.Linq;
using Gx.Records;
using Gx.Common;
using Gedcomx.Model;
using Gedcomx.Support;
using System.Diagnostics;
namespace Gx.Rs.Api
{
/// <summary>
/// This is the base class for all state instances.
/// </summary>
public abstract class GedcomxApplicationState : HypermediaEnabledData
{
/// <summary>
/// The factory responsible for creating new state instances from REST API response data.
/// </summary>
protected internal readonly StateFactory stateFactory;
/// <summary>
/// The default link loader for reading links from <see cref="Gx.Gedcomx"/> instances. Also see <seealso cref="Gx.Rs.Api.Util.EmbeddedLinkLoader.DEFAULT_EMBEDDED_LINK_RELS"/> for types of links that will be loaded.
/// </summary>
protected static readonly EmbeddedLinkLoader DEFAULT_EMBEDDED_LINK_LOADER = new EmbeddedLinkLoader();
private readonly String gzipSuffix = "-gzip";
/// <summary>
/// Gets or sets the main REST API client to use with all API calls.
/// </summary>
/// <value>
/// The REST API client to use with all API calls.
/// </value>
public IFilterableRestClient Client { get; protected set; }
/// <summary>
/// Gets or sets the current access token (the OAuth2 token), see https://familysearch.org/developers/docs/api/authentication/Access_Token_resource.
/// </summary>
/// <value>
/// The current access token (the OAuth2 token), see https://familysearch.org/developers/docs/api/authentication/Access_Token_resource.
/// </value>
public String CurrentAccessToken { get; set; }
/// <summary>
/// The link factory for managing RFC 5988 compliant hypermedia links.
/// </summary>
protected Tavis.LinkFactory linkFactory;
/// <summary>
/// The parser for extracting RFC 5988 compliant hypermedia links from a web response header.
/// </summary>
protected Tavis.LinkHeaderParser linkHeaderParser;
/// <summary>
/// Gets a value indicating whether this instance is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if this instance is authenticated; otherwise, <c>false</c>.
/// </value>
public bool IsAuthenticated { get { return CurrentAccessToken != null; } }
/// <summary>
/// Gets or sets the REST API request.
/// </summary>
/// <value>
/// The REST API request.
/// </value>
public IRestRequest Request { get; protected set; }
/// <summary>
/// Gets or sets the REST API response.
/// </summary>
/// <value>
/// The REST API response.
/// </value>
public IRestResponse Response { get; protected set; }
/// <summary>
/// Gets or sets the last embedded request (from a previous call to GedcomxApplicationState{T}.Embed{T}()).
/// </summary>
/// <value>
/// The last embedded request (from a previous call to GedcomxApplicationState{T}.Embed{T}()).
/// </value>
public IRestRequest LastEmbeddedRequest { get; set; }
/// <summary>
/// Gets or sets the last embedded response (from a previous call to GedcomxApplicationState{T}.Embed{T}()).
/// </summary>
/// <value>
/// The last embedded response (from a previous call to GedcomxApplicationState{T}.Embed{T}()).
/// </value>
public IRestResponse LastEmbeddedResponse { get; set; }
/// <summary>
/// Gets the entity tag of the entity represented by this instance.
/// </summary>
/// <value>
/// The entity tag of the entity represented by this instance.
/// </value>
public string ETag
{
get
{
var result = this.Response != null ? this.Response.Headers.Get("ETag").Select(x => x.Value.ToString()).FirstOrDefault() : null;
if (result != null && result.IndexOf(gzipSuffix) != -1)
{
result = result.Replace(gzipSuffix, String.Empty);
}
return result;
}
}
/// <summary>
/// Gets the last modified date of the entity represented by this instance.
/// </summary>
/// <value>
/// The last modified date of the entity represented by this instance.
/// </value>
public DateTime? LastModified
{
get
{
return this.Response != null ? this.Response.Headers.Get("Last-Modified").Select(x => (DateTime?)DateTime.Parse(x.Value.ToString())).FirstOrDefault() : null;
}
}
/// <summary>
/// Gets the link loader for reading links from <see cref="Gx.Gedcomx"/> instances. Also see <seealso cref="Gx.Rs.Api.Util.EmbeddedLinkLoader.DEFAULT_EMBEDDED_LINK_RELS"/> for types of links that will be loaded.
/// </summary>
/// <value>
/// This always returns the default embedded link loader.
/// </value>
protected EmbeddedLinkLoader EmbeddedLinkLoader
{
get
{
return DEFAULT_EMBEDDED_LINK_LOADER;
}
}
/// <summary>
/// Gets the main data element represented by this state instance.
/// </summary>
/// <value>
/// The main data element represented by this state instance.
/// </value>
protected abstract ISupportsLinks MainDataElement
{
get;
}
/// <summary>
/// Initializes a new instance of the <see cref="GedcomxApplicationState{T}"/> class.
/// </summary>
protected GedcomxApplicationState(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, StateFactory stateFactory)
{
linkFactory = new Tavis.LinkFactory();
linkHeaderParser = new Tavis.LinkHeaderParser(linkFactory);
this.Request = request;
this.Response = response;
this.Client = client;
this.CurrentAccessToken = accessToken;
this.stateFactory = stateFactory;
}
/// <summary>
/// Executes the specified link and embeds the response in the specified Gedcomx entity.
/// </summary>
/// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam>
/// <param name="link">The link to execute.</param>
/// <param name="entity">The entity which will embed the reponse data.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <exception cref="GedcomxApplicationException">Thrown when the server responds with HTTP status code >= 500 and < 600.</exception>
protected void Embed<T>(Link link, Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx
{
if (link.Href != null)
{
LastEmbeddedRequest = CreateRequestForEmbeddedResource(link.Rel).Build(link.Href, Method.GET);
LastEmbeddedResponse = Invoke(LastEmbeddedRequest, options);
if (LastEmbeddedResponse.StatusCode == HttpStatusCode.OK)
{
entity.Embed(LastEmbeddedResponse.ToIRestResponse<T>().Data);
}
else if (LastEmbeddedResponse.HasServerError())
{
throw new GedcomxApplicationException(String.Format("Unable to load embedded resources: server says \"{0}\" at {1}.", LastEmbeddedResponse.StatusDescription, LastEmbeddedRequest.Resource), LastEmbeddedResponse);
}
else
{
//todo: log a warning? throw an error?
}
}
}
/// <summary>
/// Creates a REST API request (with appropriate authentication headers).
/// </summary>
/// <param name="rel">This parameter is currently unused.</param>
/// <returns>A REST API requeset (with appropriate authentication headers).</returns>
protected virtual IRestRequest CreateRequestForEmbeddedResource(String rel)
{
return CreateAuthenticatedGedcomxRequest();
}
/// <summary>
/// Applies the specified options before calling IFilterableRestClient.Handle() which applies any filters before executing the request.
/// </summary>
/// <param name="request">The REST API request.</param>
/// <param name="options">The options to applying before the request is handled.</param>
/// <returns>The REST API response after being handled.</returns>
protected internal IRestResponse Invoke(IRestRequest request, params IStateTransitionOption[] options)
{
IRestResponse result;
foreach (IStateTransitionOption option in options)
{
option.Apply(request);
}
result = this.Client.Handle(request);
Debug.WriteLine(string.Format("\nRequest: {0}", request.Resource));
foreach (var header in request.Parameters)
{
Debug.WriteLine(string.Format("{0} {1}", header.Name, header.Value));
}
Debug.WriteLine(string.Format("\nResponse Status: {0} {1}", result.StatusCode, result.StatusDescription));
Debug.WriteLine(string.Format("\nResponse Content: {0}", result.Content));
return result;
}
/// <summary>
/// Clones the current state instance.
/// </summary>
/// <param name="request">The REST API request used to create this state instance.</param>
/// <param name="response">The REST API response used to create this state instance.</param>
/// <param name="client">The REST API client used to create this state instance.</param>
/// <returns>A cloned instance of the current state instance.</returns>
protected abstract GedcomxApplicationState Clone(IRestRequest request, IRestResponse response, IFilterableRestClient client);
/// <summary>
/// Creates a REST API request with authentication.
/// </summary>
/// <returns>The REST API request with authentication.</returns>
/// <remarks>This also sets the accept and content type headers.</remarks>
protected internal IRestRequest CreateAuthenticatedGedcomxRequest()
{
return CreateAuthenticatedRequest().Accept(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE).ContentType(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE);
}
/// <summary>
/// Creates a REST API request with authentication.
/// </summary>
/// <returns>The REST API request with authentication.</returns>
protected IRestRequest CreateAuthenticatedRequest()
{
IRestRequest request = CreateRequest();
if (this.CurrentAccessToken != null)
{
request = request.AddHeader("Authorization", "Bearer " + this.CurrentAccessToken);
}
return request;
}
/// <summary>
/// Creates a basic REST API request.
/// </summary>
/// <returns>A basic REST API request</returns>
protected IRestRequest CreateRequest()
{
return new RedirectableRestRequest();
}
/// <summary>
/// Extracts embedded links from the specified entity, calls each one, and embeds the response into the specified entity.
/// </summary>
/// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam>
/// <param name="entity">The entity with links and which shall have the data loaded into.</param>
/// <param name="options">The options to apply before handling the REST API requests.</param>
protected void IncludeEmbeddedResources<T>(Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx
{
Embed<T>(EmbeddedLinkLoader.LoadEmbeddedLinks(entity), entity, options);
}
/// <summary>
/// Executes the specified links and embeds the response into the specified entity.
/// </summary>
/// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam>
/// <param name="links">The links to call.</param>
/// <param name="entity">The entity which shall have the data loaded into.</param>
/// <param name="options">The options to apply before handling the REST API requests.</param>
protected void Embed<T>(IEnumerable<Link> links, Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx
{
foreach (Link link in links)
{
Embed<T>(link, entity, options);
}
}
/// <summary>
/// Gets the URI of the REST API request associated to this state instance.
/// </summary>
/// <returns>The URI of the REST API request associated to this state instance.</returns>
public string GetUri()
{
return this.Client.BaseUrl + this.Request.Resource;
}
/// <summary>
/// Determines whether this instance has error (server [code >= 500 and < 600] or client [code >= 400 and < 500]).
/// </summary>
/// <returns>True if a server or client error exists; otherwise, false.</returns>
public bool HasError()
{
return this.Response.HasClientError() || this.Response.HasServerError();
}
/// <summary>
/// Determines whether the current REST API response has the specified status.
/// </summary>
/// <param name="status">The status to evaluate.</param>
/// <returns>True if the current REST API response has the specified status; otherwise, false.</returns>
public bool HasStatus(HttpStatusCode status)
{
return this.Response.StatusCode == status;
}
/// <summary>
/// Returns the current state instance if there are no errors in the current REST API response; otherwise, it throws an exception with the response details.
/// </summary>
/// <returns>
/// A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response or throws an exception with the response details.
/// </returns>
/// <exception cref="GedcomxApplicationException">Thrown if <see cref="HasError()" /> returns true.</exception>
public virtual GedcomxApplicationState IfSuccessful()
{
if (HasError())
{
throw new GedcomxApplicationException(String.Format("Unsuccessful {0} to {1}", this.Request.Method, GetUri()), this.Response);
}
return this;
}
/// <summary>
/// Executes a HEAD verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Head(params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
request.Build(GetSelfUri(), Method.HEAD);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Executes an OPTIONS verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Options(params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
request.Build(GetSelfUri(), Method.OPTIONS);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Executes a GET verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Get(params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
request.Build(GetSelfUri(), Method.GET);
IRestResponse response = Invoke(request, options);
return Clone(request, response, this.Client);
}
/// <summary>
/// Executes an DELETE verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Delete(params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
request.Build(GetSelfUri(), Method.DELETE);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Executes a PUT verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="entity">The entity to be used as the body of the REST API request. This is the entity to be PUT.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Put(object entity, params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
if (contentType != null)
{
request.ContentType(contentType.Value as string);
}
request.SetEntity(entity).Build(GetSelfUri(), Method.PUT);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Executes a POST verb request against the current REST API request and returns a state instance with the response.
/// </summary>
/// <param name="entity">The entity to be used as the body of the REST API request. This is the entity to be POST.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public virtual GedcomxApplicationState Post(object entity, params IStateTransitionOption[] options)
{
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
if (contentType != null)
{
request.ContentType(contentType.Value as string);
}
request.SetEntity(entity).Build(GetSelfUri(), Method.POST);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Gets the warning headers from the current REST API response.
/// </summary>
/// <value>
/// The warning headers from the current REST API response.
/// </value>
public List<HttpWarning> Warnings
{
get
{
List<HttpWarning> warnings = new List<HttpWarning>();
IEnumerable<Parameter> warningValues = this.Response.Headers.Get("Warning");
if (warningValues != null)
{
foreach (Parameter warningValue in warningValues)
{
warnings.AddRange(HttpWarning.Parse(warningValue));
}
}
return warnings;
}
}
/// <summary>
/// Authenticates this session via OAuth2 password.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <param name="clientId">The client identifier.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public virtual GedcomxApplicationState AuthenticateViaOAuth2Password(String username, String password, String clientId)
{
return AuthenticateViaOAuth2Password(username, password, clientId, null);
}
/// <summary>
/// Authenticates this session via OAuth2 password.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <param name="clientId">The client identifier.</param>
/// <param name="clientSecret">The client secret.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public virtual GedcomxApplicationState AuthenticateViaOAuth2Password(String username, String password, String clientId, String clientSecret)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "password");
formData.Add("username", username);
formData.Add("password", password);
formData.Add("client_id", clientId);
if (clientSecret != null)
{
formData.Add("client_secret", clientSecret);
}
return AuthenticateViaOAuth2(formData);
}
/// <summary>
/// Authenticates this session via OAuth2 authentication code.
/// </summary>
/// <param name="authCode">The authentication code.</param>
/// <param name="redirect">The redirect.</param>
/// <param name="clientId">The client identifier.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public GedcomxApplicationState AuthenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId)
{
return AuthenticateViaOAuth2Password(authCode, authCode, clientId, null);
}
/// <summary>
/// Authenticates this session via OAuth2 authentication code.
/// </summary>
/// <param name="authCode">The authentication code.</param>
/// <param name="redirect">The redirect.</param>
/// <param name="clientId">The client identifier.</param>
/// <param name="clientSecret">The client secret.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public GedcomxApplicationState AuthenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId, String clientSecret)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "authorization_code");
formData.Add("code", authCode);
formData.Add("redirect_uri", redirect);
formData.Add("client_id", clientId);
if (clientSecret != null)
{
formData.Add("client_secret", clientSecret);
}
return AuthenticateViaOAuth2(formData);
}
/// <summary>
/// Authenticates this session via OAuth2 client credentials.
/// </summary>
/// <param name="clientId">The client identifier.</param>
/// <param name="clientSecret">The client secret.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public GedcomxApplicationState AuthenticateViaOAuth2ClientCredentials(String clientId, String clientSecret)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "client_credentials");
formData.Add("client_id", clientId);
if (clientSecret != null)
{
formData.Add("client_secret", clientSecret);
}
return AuthenticateViaOAuth2(formData);
}
/// <summary>
/// Creates a state instance without authentication. It will produce an access token, but only good for requests that do not need authentication.
/// </summary>
/// <param name="ipAddress">The ip address.</param>
/// <param name="clientId">The client identifier.</param>
/// <param name="clientSecret">The client secret.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks>
public GedcomxApplicationState UnauthenticatedAccess(string ipAddress, string clientId, string clientSecret = null)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "unauthenticated_session");
formData.Add("client_id", clientId);
formData.Add("ip_address", ipAddress);
if (clientSecret != null)
{
formData.Add("client_secret", clientSecret);
}
return AuthenticateViaOAuth2(formData);
}
/// <summary>
/// Sets the current access token to the one specified. The server is not contacted during this operation.
/// </summary>
/// <param name="accessToken">The access token.</param>
/// <returns>Returns this instance.</returns>
public GedcomxApplicationState AuthenticateWithAccessToken(String accessToken)
{
this.CurrentAccessToken = accessToken;
return this;
}
/// <summary>
/// Authenticates this session via OAuth2.
/// </summary>
/// <param name="formData">The form data.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <exception cref="GedcomxApplicationException">
/// Illegal access token response: no access_token provided.
/// or
/// Unable to obtain an access token.
/// </exception>
public GedcomxApplicationState AuthenticateViaOAuth2(IDictionary<String, String> formData, params IStateTransitionOption[] options)
{
Link tokenLink = this.GetLink(Rel.OAUTH2_TOKEN);
if (tokenLink == null || tokenLink.Href == null)
{
throw new GedcomxApplicationException(String.Format("No OAuth2 token URI supplied for resource at {0}.", GetUri()));
}
IRestRequest request = CreateRequest()
.Accept(MediaTypes.APPLICATION_JSON_TYPE)
.ContentType(MediaTypes.APPLICATION_FORM_URLENCODED_TYPE)
.SetEntity(formData)
.Build(tokenLink.Href, Method.POST);
IRestResponse response = Invoke(request, options);
if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300)
{
var accessToken = JsonConvert.DeserializeObject<IDictionary<string, object>>(response.Content);
String access_token = null;
if (accessToken.ContainsKey("access_token"))
{
access_token = accessToken["access_token"] as string;
}
if (access_token == null && accessToken.ContainsKey("token"))
{
//workaround to accommodate providers that were built on an older version of the oauth2 specification.
access_token = accessToken["token"] as string;
}
if (access_token == null)
{
throw new GedcomxApplicationException("Illegal access token response: no access_token provided.", response);
}
return AuthenticateWithAccessToken(access_token);
}
else
{
throw new GedcomxApplicationException("Unable to obtain an access token.", response);
}
}
/// <summary>
/// Reads a page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="rel">The rel name to use when looking for the link.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
public GedcomxApplicationState ReadPage(String rel, params IStateTransitionOption[] options)
{
Link link = GetLink(rel);
if (link == null || link.Href == null)
{
return null;
}
IRestRequest request = CreateAuthenticatedRequest();
Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault();
Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault();
if (accept != null)
{
request.Accept(accept.Value as string);
}
if (contentType != null)
{
request.ContentType(contentType.Value as string);
}
request.Build(link.Href, Method.GET);
return Clone(request, Invoke(request, options), this.Client);
}
/// <summary>
/// Reads the next page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.NEXT.</remarks>
public GedcomxApplicationState ReadNextPage(params IStateTransitionOption[] options)
{
return ReadPage(Rel.NEXT, options);
}
/// <summary>
/// Reads the previous page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.PREVIOUS.</remarks>
public GedcomxApplicationState ReadPreviousPage(params IStateTransitionOption[] options)
{
return ReadPage(Rel.PREVIOUS, options);
}
/// <summary>
/// Reads the first page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.FIRST.</remarks>
public GedcomxApplicationState ReadFirstPage(params IStateTransitionOption[] options)
{
return ReadPage(Rel.FIRST, options);
}
/// <summary>
/// Reads the last page of results (usually of type <see cref="Gx.Atom.Feed"/>).
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns>
/// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.LAST.</remarks>
public GedcomxApplicationState ReadLastPage(params IStateTransitionOption[] options)
{
return ReadPage(Rel.LAST, options);
}
/// <summary>
/// Creates an authenticated feed request by attaching the authentication token and specifying the accept type.
/// </summary>
/// <returns>A REST API requeset (with appropriate authentication headers).</returns>
protected IRestRequest CreateAuthenticatedFeedRequest()
{
return CreateAuthenticatedRequest().Accept(MediaTypes.ATOM_GEDCOMX_JSON_MEDIA_TYPE);
}
/// <summary>
/// Reads the contributor for the current state instance.
/// </summary>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns>
public AgentState ReadContributor(params IStateTransitionOption[] options)
{
var scope = MainDataElement;
if (scope is IAttributable)
{
return ReadContributor((IAttributable)scope, options);
}
else
{
return null;
}
}
/// <summary>
/// Reads the contributor for the specified <see cref="IAttributable"/>.
/// </summary>
/// <param name="attributable">The attributable.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns>
public AgentState ReadContributor(IAttributable attributable, params IStateTransitionOption[] options)
{
Attribution attribution = attributable.Attribution;
if (attribution == null)
{
return null;
}
return ReadContributor(attribution.Contributor, options);
}
/// <summary>
/// Reads the contributor for the specified <see cref="ResourceReference"/>.
/// </summary>
/// <param name="contributor">The contributor.</param>
/// <param name="options">The options to apply before executing the REST API call.</param>
/// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns>
public AgentState ReadContributor(ResourceReference contributor, params IStateTransitionOption[] options)
{
if (contributor == null || contributor.Resource == null)
{
return null;
}
IRestRequest request = CreateAuthenticatedGedcomxRequest().Build(contributor.Resource, Method.GET);
return this.stateFactory.NewAgentState(request, Invoke(request, options), this.Client, this.CurrentAccessToken);
}
/// <summary>
/// Gets the headers of the current REST API response.
/// </summary>
/// <value>
/// The headers of the current REST API response.
/// </value>
public IList<Parameter> Headers
{
get
{
return Response.Headers;
}
}
/// <summary>
/// Gets the URI representing this current state instance.
/// </summary>
/// <returns>The URI representing this current state instance</returns>
public string GetSelfUri()
{
String selfRel = SelfRel;
Link link = null;
if (selfRel != null)
{
link = this.GetLink(selfRel);
}
link = link == null ? this.GetLink(Rel.SELF) : link;
String self = link == null ? null : link.Href == null ? null : link.Href;
return self == null ? GetUri() : self;
}
/// <summary>
/// Gets the rel name for the current state instance. This is expected to be overridden.
/// </summary>
/// <value>
/// The rel name for the current state instance
/// </value>
public virtual String SelfRel
{
get
{
return null;
}
}
}
/// <summary>
/// This is the base class for all state instances with generic specific functionality.
/// </summary>
/// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam>
public abstract class GedcomxApplicationState<T> : GedcomxApplicationState where T : class, new()
{
/// <summary>
/// Gets the entity represented by this state (if applicable). Not all responses produce entities.
/// </summary>
/// <value>
/// The entity represented by this state.
/// </value>
public T Entity { get; private set; }
/// <summary>
/// Returns the entity from the REST API response.
/// </summary>
/// <param name="response">The REST API response.</param>
/// <returns>The entity from the REST API response.</returns>
protected virtual T LoadEntity(IRestResponse response)
{
T result = null;
if (response != null)
{
result = response.ToIRestResponse<T>().Data;
}
return result;
}
/// <summary>
/// Gets the main data element represented by this state instance.
/// </summary>
/// <value>
/// The main data element represented by this state instance.
/// </value>
protected override ISupportsLinks MainDataElement
{
get
{
return (ISupportsLinks)Entity;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="GedcomxApplicationState{T}"/> class.
/// </summary>
/// <param name="request">The REST API request.</param>
/// <param name="response">The REST API response.</param>
/// <param name="client">The REST API client.</param>
/// <param name="accessToken">The access token.</param>
/// <param name="stateFactory">The state factory.</param>
protected GedcomxApplicationState(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, StateFactory stateFactory)
: base(request, response, client, accessToken, stateFactory)
{
this.Entity = LoadEntityConditionally(this.Response);
List<Link> links = LoadLinks(this.Response, this.Entity, this.Request.RequestFormat);
this.Links = new List<Link>();
this.Links.AddRange(links);
}
/// <summary>
/// Loads the entity from the REST API response if the response should have data.
/// </summary>
/// <param name="response">The REST API response.</param>
/// <returns>Conditional returns the entity from the REST API response if the response should have data.</returns>
/// <remarks>The REST API response should have data if the invoking request was not a HEAD or OPTIONS request and the response status is OK.</remarks>
protected virtual T LoadEntityConditionally(IRestResponse response)
{
if (Request.Method != Method.HEAD && Request.Method != Method.OPTIONS && response.StatusCode == HttpStatusCode.OK)
{
return LoadEntity(response);
}
else
{
return null;
}
}
/// <summary>
/// Invokes the specified REST API request and returns a state instance of the REST API response.
/// </summary>
/// <param name="request">The REST API request to execute.</param>
/// <returns>The state instance of the REST API response.</returns>
public GedcomxApplicationState Inject(IRestRequest request)
{
return Clone(request, Invoke(request), this.Client);
}
/// <summary>
/// Loads all links from a REST API response and entity object, whether from the header, response body, or any other properties available to extract useful links for this state instance.
/// </summary>
/// <param name="response">The REST API response.</param>
/// <param name="entity">The entity to also consider for finding links.</param>
/// <param name="contentFormat">The content format (JSON or XML) of the REST API response data.</param>
/// <returns>A list of all links discovered from the REST API response and entity object.</returns>
protected List<Link> LoadLinks(IRestResponse response, T entity, DataFormat contentFormat)
{
List<Link> links = new List<Link>();
var location = response.Headers.FirstOrDefault(x => x.Name == "Location");
//if there's a location, we'll consider it a "self" link.
if (location != null && location.Value != null)
{
links.Add(new Link() { Rel = Rel.SELF, Href = location.Value.ToString() });
}
//initialize links with link headers
foreach (var header in response.Headers.Where(x => x.Name == "Link" && x.Value != null).SelectMany(x => linkHeaderParser.Parse(response.ResponseUri, x.Value.ToString())))
{
Link link = new Link() { Rel = header.Relation, Href = header.Target.ToString() };
link.Template = header.LinkExtensions.Any(x => x.Key == "template") ? header.GetLinkExtension("template") : null;
link.Title = header.Title;
link.Accept = header.LinkExtensions.Any(x => x.Key == "accept") ? header.GetLinkExtension("accept") : null;
link.Allow = header.LinkExtensions.Any(x => x.Key == "allow") ? header.GetLinkExtension("allow") : null;
link.Hreflang = header.HrefLang.Select(x => x.Name).FirstOrDefault();
link.Type = header.LinkExtensions.Any(x => x.Key == "type") ? header.GetLinkExtension("type") : null;
links.Add(link);
}
//load the links from the main data element
ISupportsLinks mainElement = MainDataElement;
if (mainElement != null && mainElement.Links != null)
{
links.AddRange(mainElement.Links);
}
//load links at the document level
var collection = entity as ISupportsLinks;
if (entity != mainElement && collection != null && collection.Links != null)
{
links.AddRange(collection.Links);
}
return links;
}
}
}
| |
using System;
using System.Diagnostics;
using SharpFlame.Core.Domain;
using SharpFlame.Mapping;
using SharpFlame.Mapping.Tools;
using SharpFlame.Maths;
namespace SharpFlame
{
public class clsBrush
{
public struct sPosNum
{
public XYInt Normal;
public XYInt Alignment;
}
private double _Radius;
public enum enumShape
{
Circle,
Square
}
private enumShape _Shape = enumShape.Circle;
public sBrushTiles Tiles;
public bool Alignment
{
get { return _Alignment; }
}
private bool _Alignment;
public double Radius
{
get { return _Radius; }
set
{
if ( _Radius == value )
{
return;
}
_Radius = value;
CreateTiles();
}
}
public enumShape Shape
{
get { return _Shape; }
set
{
if ( _Shape == value )
{
return;
}
_Shape = value;
CreateTiles();
}
}
private void CreateTiles()
{
double AlignmentOffset = _Radius - (int)_Radius;
double RadiusB = (int)(_Radius + 0.25D);
_Alignment = AlignmentOffset >= 0.25D & AlignmentOffset < 0.75D;
switch ( _Shape )
{
case enumShape.Circle:
Tiles.CreateCircle(RadiusB, 1.0D, _Alignment);
break;
case enumShape.Square:
Tiles.CreateSquare(RadiusB, 1.0D, _Alignment);
break;
}
}
public clsBrush(double InitialRadius, enumShape InitialShape)
{
_Radius = InitialRadius;
_Shape = InitialShape;
CreateTiles();
}
public void PerformActionMapTiles(clsAction Tool, sPosNum Centre)
{
PerformAction(Tool, Centre, new XYInt(Tool.Map.Terrain.TileSize.X - 1, Tool.Map.Terrain.TileSize.Y - 1));
}
public void PerformActionMapVertices(clsAction Tool, sPosNum Centre)
{
PerformAction(Tool, Centre, Tool.Map.Terrain.TileSize);
}
public void PerformActionMapSectors(clsAction Tool, sPosNum Centre)
{
PerformAction(Tool, Centre, new XYInt(Tool.Map.SectorCount.X - 1, Tool.Map.SectorCount.Y - 1));
}
public XYInt GetPosNum(sPosNum PosNum)
{
if ( _Alignment )
{
return PosNum.Alignment;
}
else
{
return PosNum.Normal;
}
}
private void PerformAction(clsAction Action, sPosNum PosNum, XYInt LastValidNum)
{
int XNum = 0;
int X = 0;
int Y = 0;
XYInt Centre = new XYInt(0, 0);
if ( Action.Map == null )
{
Debugger.Break();
return;
}
Centre = GetPosNum(PosNum);
Action.Effect = 1.0D;
for ( Y = MathUtil.Clamp_int(Tiles.YMin + Centre.Y, 0, LastValidNum.Y) - Centre.Y;
Y <= MathUtil.Clamp_int(Tiles.YMax + Centre.Y, 0, LastValidNum.Y) - Centre.Y;
Y++ )
{
Action.PosNum.Y = Centre.Y + Y;
XNum = Y - Tiles.YMin;
for ( X = MathUtil.Clamp_int(Tiles.XMin[XNum] + Centre.X, 0, LastValidNum.X) - Centre.X;
X <= MathUtil.Clamp_int(Convert.ToInt32(Tiles.XMax[XNum] + Centre.X), 0, LastValidNum.X) - Centre.X;
X++ )
{
Action.PosNum.X = Centre.X + X;
if ( Action.UseEffect )
{
if ( Tiles.ResultRadius > 0.0D )
{
switch ( _Shape )
{
case enumShape.Circle:
if ( _Alignment )
{
Action.Effect =
Convert.ToDouble(1.0D -
(new XYDouble(Action.PosNum.X, Action.PosNum.Y) -
new XYDouble(Centre.X - 0.5D, Centre.Y - 0.5D)).GetMagnitude() /
(Tiles.ResultRadius + 0.5D));
}
else
{
Action.Effect = Convert.ToDouble(1.0D - (Centre - Action.PosNum).ToDoubles().GetMagnitude() / (Tiles.ResultRadius + 0.5D));
}
break;
case enumShape.Square:
if ( _Alignment )
{
Action.Effect = 1.0D -
Math.Max(Math.Abs(Action.PosNum.X - (Centre.X - 0.5D)), Math.Abs(Action.PosNum.Y - (Centre.Y - 0.5D))) /
(Tiles.ResultRadius + 0.5D);
}
else
{
Action.Effect = 1.0D -
Math.Max(Math.Abs(Action.PosNum.X - Centre.X), Math.Abs(Action.PosNum.Y - Centre.Y)) /
(Tiles.ResultRadius + 0.5D);
}
break;
}
}
}
Action.ActionPerform();
}
}
}
}
public struct sBrushTiles
{
public int[] XMin;
public int[] XMax;
public int YMin;
public int YMax;
public double ResultRadius;
public void CreateCircle(double Radius, double TileSize, bool Alignment)
{
int X = 0;
int Y = 0;
double dblX = 0;
double dblY = 0;
double RadiusB = 0;
double RadiusC = 0;
int A = 0;
int B = 0;
RadiusB = Radius / TileSize;
if ( Alignment )
{
RadiusB += 1.0D;
Y = (int)RadiusB;
YMin = Convert.ToInt32(- Y);
YMax = Y - 1;
B = YMax - YMin;
XMin = new int[B + 1];
XMax = new int[B + 1];
RadiusC = RadiusB * RadiusB;
for ( Y = YMin; Y <= YMax; Y++ )
{
dblY = Y + 0.5D;
dblX = Math.Sqrt(RadiusC - dblY * dblY) + 0.5D;
A = Y - YMin;
X = (int)dblX;
XMin[A] = Convert.ToInt32(- X);
XMax[A] = X - 1;
}
}
else
{
RadiusB += 0.125D;
Y = (int)RadiusB;
YMin = Convert.ToInt32(- Y);
YMax = Y;
B = YMax - YMin;
XMin = new int[B + 1];
XMax = new int[B + 1];
RadiusC = RadiusB * RadiusB;
for ( Y = YMin; Y <= YMax; Y++ )
{
dblY = Y;
dblX = Math.Sqrt(RadiusC - dblY * dblY);
A = Y - YMin;
X = (int)dblX;
XMin[A] = Convert.ToInt32(- X);
XMax[A] = X;
}
}
ResultRadius = B / 2.0D;
}
public void CreateSquare(double Radius, double TileSize, bool Alignment)
{
int Y = 0;
int A = 0;
int B = 0;
double RadiusB = 0;
RadiusB = Radius / TileSize + 0.5D;
if ( Alignment )
{
RadiusB += 0.5D;
A = (int)RadiusB;
YMin = Convert.ToInt32(- A);
YMax = A - 1;
}
else
{
A = (int)RadiusB;
YMin = Convert.ToInt32(- A);
YMax = A;
}
B = YMax - YMin;
XMin = new int[B + 1];
XMax = new int[B + 1];
for ( Y = 0; Y <= B; Y++ )
{
XMin[Y] = YMin;
XMax[Y] = YMax;
}
ResultRadius = B / 2.0D;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Security;
using System.Diagnostics;
#if !NET_NATIVE
namespace System.Runtime.Serialization
{
internal class CodeGenerator
{
/// <SecurityNote>
/// Critical - Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
[SecurityCritical]
private static MethodInfo s_getTypeFromHandle;
private static MethodInfo GetTypeFromHandle
{
/// <SecurityNote>
/// Critical - fetches the critical getTypeFromHandle field
/// Safe - get-only properties only needs to be protected for write; initialized in getter if null.
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_getTypeFromHandle == null)
{
s_getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle");
Debug.Assert(s_getTypeFromHandle != null);
}
return s_getTypeFromHandle;
}
}
/// <SecurityNote>
/// Critical - Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
[SecurityCritical]
private static MethodInfo s_objectEquals;
private static MethodInfo ObjectEquals
{
/// <SecurityNote>
/// Critical - fetches the critical objectEquals field
/// Safe - get-only properties only needs to be protected for write; initialized in getter if null.
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_objectEquals == null)
{
s_objectEquals = Globals.TypeOfObject.GetMethod("Equals", BindingFlags.Public | BindingFlags.Static);
Debug.Assert(s_objectEquals != null);
}
return s_objectEquals;
}
}
/// <SecurityNote>
/// Critical - Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
[SecurityCritical]
private static MethodInfo s_arraySetValue;
private static MethodInfo ArraySetValue
{
/// <SecurityNote>
/// Critical - fetches the critical arraySetValue field
/// Safe - get-only properties only needs to be protected for write; initialized in getter if null.
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_arraySetValue == null)
{
s_arraySetValue = typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) });
Debug.Assert(s_arraySetValue != null);
}
return s_arraySetValue;
}
}
#if !NET_NATIVE
[SecurityCritical]
private static MethodInfo s_objectToString;
private static MethodInfo ObjectToString
{
[SecuritySafeCritical]
get
{
if (s_objectToString == null)
{
s_objectToString = typeof(object).GetMethod("ToString", Array.Empty<Type>());
Debug.Assert(s_objectToString != null);
}
return s_objectToString;
}
}
private static MethodInfo s_stringFormat;
private static MethodInfo StringFormat
{
[SecuritySafeCritical]
get
{
if (s_stringFormat == null)
{
s_stringFormat = typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) });
Debug.Assert(s_stringFormat != null);
}
return s_stringFormat;
}
}
#endif
private Type _delegateType;
#if USE_REFEMIT
AssemblyBuilder assemblyBuilder;
ModuleBuilder moduleBuilder;
TypeBuilder typeBuilder;
static int typeCounter;
MethodBuilder methodBuilder;
#else
/// <SecurityNote>
/// Critical - Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
[SecurityCritical]
private static Module s_serializationModule;
private static Module SerializationModule
{
/// <SecurityNote>
/// Critical - fetches the critical serializationModule field
/// Safe - get-only properties only needs to be protected for write; initialized in getter if null.
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_serializationModule == null)
{
s_serializationModule = typeof(CodeGenerator).GetTypeInfo().Module; // could to be replaced by different dll that has SkipVerification set to false
}
return s_serializationModule;
}
}
private DynamicMethod _dynamicMethod;
#endif
private ILGenerator _ilGen;
private List<ArgBuilder> _argList;
private Stack<object> _blockStack;
private Label _methodEndLabel;
private Dictionary<LocalBuilder, string> _localNames = new Dictionary<LocalBuilder, string>();
private enum CodeGenTrace { None, Save, Tron };
private CodeGenTrace _codeGenTrace;
#if !NET_NATIVE
private LocalBuilder _stringFormatArray;
#endif
internal CodeGenerator()
{
//Defaulting to None as thats the default value in WCF
_codeGenTrace = CodeGenTrace.None;
}
#if !USE_REFEMIT
internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess)
{
_dynamicMethod = dynamicMethod;
_ilGen = _dynamicMethod.GetILGenerator();
_delegateType = delegateType;
InitILGeneration(methodName, argTypes);
}
#endif
internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess)
{
MethodInfo signature = delegateType.GetMethod("Invoke");
ParameterInfo[] parameters = signature.GetParameters();
Type[] paramTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramTypes[i] = parameters[i].ParameterType;
BeginMethod(signature.ReturnType, methodName, paramTypes, allowPrivateMemberAccess);
_delegateType = delegateType;
}
[SecuritySafeCritical]
private void BeginMethod(Type returnType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess)
{
#if USE_REFEMIT
string typeName = "Type" + (typeCounter++);
InitAssemblyBuilder(typeName + "." + methodName);
this.typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public);
this.methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public|MethodAttributes.Static, returnType, argTypes);
this.ilGen = this.methodBuilder.GetILGenerator();
#else
_dynamicMethod = new DynamicMethod(methodName, returnType, argTypes, SerializationModule, allowPrivateMemberAccess);
_ilGen = _dynamicMethod.GetILGenerator();
#endif
InitILGeneration(methodName, argTypes);
}
private void InitILGeneration(string methodName, Type[] argTypes)
{
_methodEndLabel = _ilGen.DefineLabel();
_blockStack = new Stack<object>();
_argList = new List<ArgBuilder>();
for (int i = 0; i < argTypes.Length; i++)
_argList.Add(new ArgBuilder(i, argTypes[i]));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel("Begin method " + methodName + " {");
}
internal Delegate EndMethod()
{
MarkLabel(_methodEndLabel);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel("} End method");
Ret();
Delegate retVal = null;
#if USE_REFEMIT
Type type = typeBuilder.CreateType();
MethodInfo method = type.GetMethod(methodBuilder.Name);
retVal = Delegate.CreateDelegate(delegateType, method);
methodBuilder = null;
#else
retVal = _dynamicMethod.CreateDelegate(_delegateType);
_dynamicMethod = null;
#endif
_delegateType = null;
_ilGen = null;
_blockStack = null;
_argList = null;
return retVal;
}
internal MethodInfo CurrentMethod
{
get
{
#if USE_REFEMIT
return methodBuilder;
#else
return _dynamicMethod;
#endif
}
}
internal ArgBuilder GetArg(int index)
{
return (ArgBuilder)_argList[index];
}
internal Type GetVariableType(object var)
{
if (var is ArgBuilder)
return ((ArgBuilder)var).ArgType;
else if (var is LocalBuilder)
return ((LocalBuilder)var).LocalType;
else
return var.GetType();
}
internal LocalBuilder DeclareLocal(Type type, string name, object initialValue)
{
LocalBuilder local = DeclareLocal(type, name);
Load(initialValue);
Store(local);
return local;
}
internal LocalBuilder DeclareLocal(Type type, string name)
{
return DeclareLocal(type, name, false);
}
internal LocalBuilder DeclareLocal(Type type, string name, bool isPinned)
{
LocalBuilder local = _ilGen.DeclareLocal(type, isPinned);
if (_codeGenTrace != CodeGenTrace.None)
{
_localNames[local] = name;
EmitSourceComment("Declare local '" + name + "' of type " + type);
}
return local;
}
internal void Set(LocalBuilder local, object value)
{
Load(value);
Store(local);
}
internal object For(LocalBuilder local, object start, object end)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end);
if (forState.Index != null)
{
Load(start);
Stloc(forState.Index);
Br(forState.TestLabel);
}
MarkLabel(forState.BeginLabel);
_blockStack.Push(forState);
return forState;
}
internal void EndFor()
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
if (forState == null)
ThrowMismatchException(stackTop);
if (forState.Index != null)
{
Ldloc(forState.Index);
Ldc(1);
Add();
Stloc(forState.Index);
MarkLabel(forState.TestLabel);
Ldloc(forState.Index);
Load(forState.End);
if (GetVariableType(forState.End).IsArray)
Ldlen();
Blt(forState.BeginLabel);
}
else
Br(forState.BeginLabel);
if (forState.RequiresEndLabel)
MarkLabel(forState.EndLabel);
}
internal void Break(object forState)
{
InternalBreakFor(forState, OpCodes.Br);
}
internal void IfFalseBreak(object forState)
{
InternalBreakFor(forState, OpCodes.Brfalse);
}
internal void InternalBreakFor(object userForState, OpCode branchInstruction)
{
foreach (object block in _blockStack)
{
ForState forState = block as ForState;
if (forState != null && (object)forState == userForState)
{
if (!forState.RequiresEndLabel)
{
forState.EndLabel = DefineLabel();
forState.RequiresEndLabel = true;
}
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(branchInstruction + " " + forState.EndLabel.GetHashCode());
_ilGen.Emit(branchInstruction, forState.EndLabel);
break;
}
}
}
internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType,
LocalBuilder enumerator, MethodInfo getCurrentMethod)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), enumerator);
Br(forState.TestLabel);
MarkLabel(forState.BeginLabel);
Call(enumerator, getCurrentMethod);
ConvertValue(elementType, GetVariableType(local));
Stloc(local);
_blockStack.Push(forState);
}
internal void EndForEach(MethodInfo moveNextMethod)
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
if (forState == null)
ThrowMismatchException(stackTop);
MarkLabel(forState.TestLabel);
object enumerator = forState.End;
Call(enumerator, moveNextMethod);
Brtrue(forState.BeginLabel);
if (forState.RequiresEndLabel)
MarkLabel(forState.EndLabel);
}
internal void IfNotDefaultValue(object value)
{
Type type = GetVariableType(value);
TypeCode typeCode = type.GetTypeCode();
if ((typeCode == TypeCode.Object && type.GetTypeInfo().IsValueType) ||
typeCode == TypeCode.DateTime || typeCode == TypeCode.Decimal)
{
LoadDefaultValue(type);
ConvertValue(type, Globals.TypeOfObject);
Load(value);
ConvertValue(type, Globals.TypeOfObject);
Call(ObjectEquals);
IfNot();
}
else
{
LoadDefaultValue(type);
Load(value);
If(Cmp.NotEqualTo);
}
}
internal void If()
{
InternalIf(false);
}
internal void IfNot()
{
InternalIf(true);
}
private OpCode GetBranchCode(Cmp cmp)
{
switch (cmp)
{
case Cmp.LessThan:
return OpCodes.Bge;
case Cmp.EqualTo:
return OpCodes.Bne_Un;
case Cmp.LessThanOrEqualTo:
return OpCodes.Bgt;
case Cmp.GreaterThan:
return OpCodes.Ble;
case Cmp.NotEqualTo:
return OpCodes.Beq;
default:
DiagnosticUtility.DebugAssert(cmp == Cmp.GreaterThanOrEqualTo, "Unexpected cmp");
return OpCodes.Blt;
}
}
internal void If(Cmp cmpOp)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void If(object value1, Cmp cmpOp, object value2)
{
Load(value1);
Load(value2);
If(cmpOp);
}
internal void Else()
{
IfState ifState = PopIfState();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
ifState.ElseBegin = ifState.EndIf;
_blockStack.Push(ifState);
}
internal void ElseIf(object value1, Cmp cmpOp, object value2)
{
IfState ifState = (IfState)_blockStack.Pop();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
Load(value1);
Load(value2);
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void EndIf()
{
IfState ifState = PopIfState();
if (!ifState.ElseBegin.Equals(ifState.EndIf))
MarkLabel(ifState.ElseBegin);
MarkLabel(ifState.EndIf);
}
internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount)
{
if (methodInfo.GetParameters().Length != expectedCount)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount)));
}
internal void Call(object thisObj, MethodInfo methodInfo)
{
VerifyParameterCount(methodInfo, 0);
LoadThis(thisObj, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1)
{
VerifyParameterCount(methodInfo, 1);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2)
{
VerifyParameterCount(methodInfo, 2);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3)
{
VerifyParameterCount(methodInfo, 3);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4)
{
VerifyParameterCount(methodInfo, 4);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5)
{
VerifyParameterCount(methodInfo, 5);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
LoadParam(param5, 5, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6)
{
VerifyParameterCount(methodInfo, 6);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
LoadParam(param5, 5, methodInfo);
LoadParam(param6, 6, methodInfo);
Call(methodInfo);
}
internal void Call(MethodInfo methodInfo)
{
if (methodInfo.IsVirtual && !methodInfo.DeclaringType.GetTypeInfo().IsValueType)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Callvirt, methodInfo);
}
else if (methodInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, methodInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, methodInfo);
}
}
internal void Call(ConstructorInfo ctor)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, ctor);
}
internal void New(ConstructorInfo constructorInfo)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Newobj, constructorInfo);
}
internal void InitObj(Type valueType)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Initobj " + valueType);
_ilGen.Emit(OpCodes.Initobj, valueType);
}
internal void NewArray(Type elementType, object len)
{
Load(len);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Newarr " + elementType);
_ilGen.Emit(OpCodes.Newarr, elementType);
}
internal void LoadArrayElement(object obj, object arrayIndex)
{
Type objType = GetVariableType(obj).GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
{
Ldelema(objType);
Ldobj(objType);
}
else
Ldelem(objType);
}
internal void StoreArrayElement(object obj, object arrayIndex, object value)
{
Type arrayType = GetVariableType(obj);
if (arrayType == Globals.TypeOfArray)
{
Call(obj, ArraySetValue, value, arrayIndex);
}
else
{
Type objType = arrayType.GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
Ldelema(objType);
Load(value);
ConvertValue(GetVariableType(value), objType);
if (IsStruct(objType))
Stobj(objType);
else
Stelem(objType);
}
}
private static bool IsStruct(Type objType)
{
return objType.GetTypeInfo().IsValueType && !objType.GetTypeInfo().IsPrimitive;
}
internal Type LoadMember(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Ldsfld, fieldInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Ldfld, fieldInfo);
}
}
else if (memberInfo is PropertyInfo)
{
PropertyInfo property = memberInfo as PropertyInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property)));
Call(getMethod);
}
}
else if (memberInfo is MethodInfo)
{
MethodInfo method = (MethodInfo)memberInfo;
memberType = method.ReturnType;
Call(method);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown", memberInfo.DeclaringType, memberInfo.Name)));
EmitStackTop(memberType);
return memberType;
}
internal void StoreMember(MemberInfo memberInfo)
{
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
if (fieldInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Stsfld, fieldInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Stfld, fieldInfo);
}
}
else if (memberInfo is PropertyInfo)
{
PropertyInfo property = memberInfo as PropertyInfo;
if (property != null)
{
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property)));
Call(setMethod);
}
}
else if (memberInfo is MethodInfo)
Call((MethodInfo)memberInfo);
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown")));
}
internal void LoadDefaultValue(Type type)
{
if (type.GetTypeInfo().IsValueType)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
Ldc(false);
break;
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
Ldc(0);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
Ldc(0L);
break;
case TypeCode.Single:
Ldc(0.0F);
break;
case TypeCode.Double:
Ldc(0.0);
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
default:
LocalBuilder zero = DeclareLocal(type, "zero");
LoadAddress(zero);
InitObj(type);
Load(zero);
break;
}
}
else
Load(null);
}
internal void Load(object obj)
{
if (obj == null)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldnull");
_ilGen.Emit(OpCodes.Ldnull);
}
else if (obj is ArgBuilder)
Ldarg((ArgBuilder)obj);
else if (obj is LocalBuilder)
Ldloc((LocalBuilder)obj);
else
Ldc(obj);
}
internal void Store(object var)
{
if (var is ArgBuilder)
Starg((ArgBuilder)var);
else if (var is LocalBuilder)
Stloc((LocalBuilder)var);
else
{
DiagnosticUtility.DebugAssert("Data can only be stored into ArgBuilder or LocalBuilder.");
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CanOnlyStoreIntoArgOrLocGot0, DataContract.GetClrTypeFullName(var.GetType()))));
}
}
internal void Dec(object var)
{
Load(var);
Load(1);
Subtract();
Store(var);
}
internal void LoadAddress(object obj)
{
if (obj is ArgBuilder)
LdargAddress((ArgBuilder)obj);
else if (obj is LocalBuilder)
LdlocAddress((LocalBuilder)obj);
else
Load(obj);
}
internal void ConvertAddress(Type source, Type target)
{
InternalConvert(source, target, true);
}
internal void ConvertValue(Type source, Type target)
{
InternalConvert(source, target, false);
}
internal void Castclass(Type target)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Castclass " + target);
_ilGen.Emit(OpCodes.Castclass, target);
}
internal void Box(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Box " + type);
_ilGen.Emit(OpCodes.Box, type);
}
internal void Unbox(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Unbox " + type);
_ilGen.Emit(OpCodes.Unbox, type);
}
private OpCode GetLdindOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Boolean:
return OpCodes.Ldind_I1; // TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Ldind_I2; // TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Ldind_I1; // TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Ldind_U1; // TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Ldind_I2; // TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Ldind_U2; // TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Ldind_I4; // TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Ldind_U4; // TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Ldind_I8; // TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Ldind_I8; // TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Ldind_R4; // TypeCode.Single:
case TypeCode.Double:
return OpCodes.Ldind_R8; // TypeCode.Double:
case TypeCode.String:
return OpCodes.Ldind_Ref; // TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Ldobj(Type type)
{
OpCode opCode = GetLdindOpCode(type.GetTypeCode());
if (!opCode.Equals(OpCodes.Nop))
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldobj " + type);
_ilGen.Emit(OpCodes.Ldobj, type);
}
}
internal void Stobj(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stobj " + type);
_ilGen.Emit(OpCodes.Stobj, type);
}
internal void Ceq()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ceq");
_ilGen.Emit(OpCodes.Ceq);
}
internal void Throw()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Throw");
_ilGen.Emit(OpCodes.Throw);
}
internal void Ldtoken(Type t)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldtoken " + t);
_ilGen.Emit(OpCodes.Ldtoken, t);
}
internal void Ldc(object o)
{
Type valueType = o.GetType();
if (o is Type)
{
Ldtoken((Type)o);
Call(GetTypeFromHandle);
}
else if (valueType.GetTypeInfo().IsEnum)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceComment("Ldc " + o.GetType() + "." + o);
Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null));
}
else
{
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
Ldc((bool)o);
break;
case TypeCode.Char:
DiagnosticUtility.DebugAssert("Char is not a valid schema primitive and should be treated as int in DataContract");
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.CharIsInvalidPrimitive)));
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture));
break;
case TypeCode.Int32:
Ldc((int)o);
break;
case TypeCode.UInt32:
Ldc((int)(uint)o);
break;
case TypeCode.UInt64:
Ldc((long)(ulong)o);
break;
case TypeCode.Int64:
Ldc((long)o);
break;
case TypeCode.Single:
Ldc((float)o);
break;
case TypeCode.Double:
Ldc((double)o);
break;
case TypeCode.String:
Ldstr((string)o);
break;
case TypeCode.Object:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.Empty:
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownConstantType, DataContract.GetClrTypeFullName(valueType))));
}
}
}
internal void Ldc(bool boolVar)
{
if (boolVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 1");
_ilGen.Emit(OpCodes.Ldc_I4_1);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 0");
_ilGen.Emit(OpCodes.Ldc_I4_0);
}
}
internal void Ldc(int intVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 " + intVar);
switch (intVar)
{
case -1:
_ilGen.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
_ilGen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
_ilGen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
_ilGen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
_ilGen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
_ilGen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
_ilGen.Emit(OpCodes.Ldc_I4_8);
break;
default:
_ilGen.Emit(OpCodes.Ldc_I4, intVar);
break;
}
}
internal void Ldc(long l)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i8 " + l);
_ilGen.Emit(OpCodes.Ldc_I8, l);
}
internal void Ldc(float f)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.r4 " + f);
_ilGen.Emit(OpCodes.Ldc_R4, f);
}
internal void Ldc(double d)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.r8 " + d);
_ilGen.Emit(OpCodes.Ldc_R8, d);
}
internal void Ldstr(string strVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldstr " + strVar);
_ilGen.Emit(OpCodes.Ldstr, strVar);
}
internal void LdlocAddress(LocalBuilder localBuilder)
{
if (localBuilder.LocalType.GetTypeInfo().IsValueType)
Ldloca(localBuilder);
else
Ldloc(localBuilder);
}
internal void Ldloc(LocalBuilder localBuilder)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldloc " + _localNames[localBuilder]);
_ilGen.Emit(OpCodes.Ldloc, localBuilder);
EmitStackTop(localBuilder.LocalType);
}
internal void Stloc(LocalBuilder local)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stloc " + _localNames[local]);
EmitStackTop(local.LocalType);
_ilGen.Emit(OpCodes.Stloc, local);
}
internal void Ldloca(LocalBuilder localBuilder)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldloca " + _localNames[localBuilder]);
_ilGen.Emit(OpCodes.Ldloca, localBuilder);
EmitStackTop(localBuilder.LocalType);
}
internal void LdargAddress(ArgBuilder argBuilder)
{
if (argBuilder.ArgType.GetTypeInfo().IsValueType)
Ldarga(argBuilder);
else
Ldarg(argBuilder);
}
internal void Ldarg(ArgBuilder arg)
{
Ldarg(arg.Index);
}
internal void Starg(ArgBuilder arg)
{
Starg(arg.Index);
}
internal void Ldarg(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldarg " + slot);
switch (slot)
{
case 0:
_ilGen.Emit(OpCodes.Ldarg_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldarg_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldarg_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldarg_3);
break;
default:
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarg_S, slot);
else
_ilGen.Emit(OpCodes.Ldarg, slot);
break;
}
}
internal void Starg(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Starg " + slot);
if (slot <= 255)
_ilGen.Emit(OpCodes.Starg_S, slot);
else
_ilGen.Emit(OpCodes.Starg, slot);
}
internal void Ldarga(ArgBuilder argBuilder)
{
Ldarga(argBuilder.Index);
}
internal void Ldarga(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldarga " + slot);
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarga_S, slot);
else
_ilGen.Emit(OpCodes.Ldarga, slot);
}
internal void Ldlen()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldlen");
_ilGen.Emit(OpCodes.Ldlen);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Conv.i4");
_ilGen.Emit(OpCodes.Conv_I4);
}
private OpCode GetLdelemOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Object:
return OpCodes.Ldelem_Ref;// TypeCode.Object:
case TypeCode.Boolean:
return OpCodes.Ldelem_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Ldelem_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Ldelem_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Ldelem_U1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Ldelem_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Ldelem_U2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Ldelem_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Ldelem_U4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Ldelem_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Ldelem_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Ldelem_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Ldelem_R8;// TypeCode.Double:
case TypeCode.String:
return OpCodes.Ldelem_Ref;// TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Ldelem(Type arrayElementType)
{
if (arrayElementType.GetTypeInfo().IsEnum)
{
Ldelem(Enum.GetUnderlyingType(arrayElementType));
}
else
{
OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType))));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
EmitStackTop(arrayElementType);
}
}
internal void Ldelema(Type arrayElementType)
{
OpCode opCode = OpCodes.Ldelema;
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode, arrayElementType);
EmitStackTop(arrayElementType);
}
private OpCode GetStelemOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Object:
return OpCodes.Stelem_Ref;// TypeCode.Object:
case TypeCode.Boolean:
return OpCodes.Stelem_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Stelem_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Stelem_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Stelem_I1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Stelem_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Stelem_I2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Stelem_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Stelem_I4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Stelem_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Stelem_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Stelem_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Stelem_R8;// TypeCode.Double:
case TypeCode.String:
return OpCodes.Stelem_Ref;// TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Stelem(Type arrayElementType)
{
if (arrayElementType.GetTypeInfo().IsEnum)
Stelem(Enum.GetUnderlyingType(arrayElementType));
else
{
OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported, DataContract.GetClrTypeFullName(arrayElementType))));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
EmitStackTop(arrayElementType);
_ilGen.Emit(opCode);
}
}
internal Label DefineLabel()
{
return _ilGen.DefineLabel();
}
internal void MarkLabel(Label label)
{
_ilGen.MarkLabel(label);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel(label.GetHashCode() + ":");
}
internal void Add()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Add");
_ilGen.Emit(OpCodes.Add);
}
internal void Subtract()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Sub");
_ilGen.Emit(OpCodes.Sub);
}
internal void And()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("And");
_ilGen.Emit(OpCodes.And);
}
internal void Or()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Or");
_ilGen.Emit(OpCodes.Or);
}
internal void Not()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Not");
_ilGen.Emit(OpCodes.Not);
}
internal void Ret()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ret");
_ilGen.Emit(OpCodes.Ret);
}
internal void Br(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Br " + label.GetHashCode());
_ilGen.Emit(OpCodes.Br, label);
}
internal void Blt(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Blt " + label.GetHashCode());
_ilGen.Emit(OpCodes.Blt, label);
}
internal void Brfalse(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Brfalse " + label.GetHashCode());
_ilGen.Emit(OpCodes.Brfalse, label);
}
internal void Brtrue(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Brtrue " + label.GetHashCode());
_ilGen.Emit(OpCodes.Brtrue, label);
}
internal void Pop()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Pop");
_ilGen.Emit(OpCodes.Pop);
}
internal void Dup()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Dup");
_ilGen.Emit(OpCodes.Dup);
}
private void LoadThis(object thisObj, MethodInfo methodInfo)
{
if (thisObj != null && !methodInfo.IsStatic)
{
LoadAddress(thisObj);
ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType);
}
}
private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo)
{
Load(arg);
if (arg != null)
ConvertValue(GetVariableType(arg), methodInfo.GetParameters()[oneBasedArgIndex - 1].ParameterType);
}
private void InternalIf(bool negate)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
if (negate)
Brtrue(ifState.ElseBegin);
else
Brfalse(ifState.ElseBegin);
_blockStack.Push(ifState);
}
private OpCode GetConvOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Boolean:
return OpCodes.Conv_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Conv_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Conv_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Conv_U1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Conv_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Conv_U2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Conv_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Conv_U4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Conv_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Conv_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Conv_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Conv_R8;// TypeCode.Double:
default:
return OpCodes.Nop;
}
}
private void InternalConvert(Type source, Type target, bool isAddress)
{
if (target == source)
return;
if (target.GetTypeInfo().IsValueType)
{
if (source.GetTypeInfo().IsValueType)
{
OpCode opCode = GetConvOpCode(target.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target))));
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
}
}
else if (source.IsAssignableFrom(target))
{
Unbox(target);
if (!isAddress)
Ldobj(target);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
else if (target.IsAssignableFrom(source))
{
if (source.GetTypeInfo().IsValueType)
{
if (isAddress)
Ldobj(source);
Box(source);
}
}
else if (source.IsAssignableFrom(target))
{
Castclass(target);
}
else if (target.GetTypeInfo().IsInterface || source.GetTypeInfo().IsInterface)
{
Castclass(target);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
private IfState PopIfState()
{
object stackTop = _blockStack.Pop();
IfState ifState = stackTop as IfState;
if (ifState == null)
ThrowMismatchException(stackTop);
return ifState;
}
#if USE_REFEMIT
[SecuritySafeCritical]
void InitAssemblyBuilder(string methodName)
{
AssemblyName name = new AssemblyName();
name.Name = "Microsoft.GeneratedCode."+methodName;
//Add SecurityCritical and SecurityTreatAsSafe attributes to the generated method
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name + ".dll", false);
}
#endif
private void ThrowMismatchException(object expected)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString())));
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceInstruction(string line)
{
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceLabel(string line)
{
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceComment(string comment)
{
}
internal void EmitStackTop(Type stackTopType)
{
if (_codeGenTrace != CodeGenTrace.Tron)
return;
}
internal Label[] Switch(int labelCount)
{
SwitchState switchState = new SwitchState(DefineLabel(), DefineLabel());
Label[] caseLabels = new Label[labelCount];
for (int i = 0; i < caseLabels.Length; i++)
caseLabels[i] = DefineLabel();
_ilGen.Emit(OpCodes.Switch, caseLabels);
Br(switchState.DefaultLabel);
_blockStack.Push(switchState);
return caseLabels;
}
internal void Case(Label caseLabel1, string caseLabelName)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("case " + caseLabelName + "{");
MarkLabel(caseLabel1);
}
internal void EndCase()
{
object stackTop = _blockStack.Peek();
SwitchState switchState = stackTop as SwitchState;
if (switchState == null)
ThrowMismatchException(stackTop);
Br(switchState.EndOfSwitchLabel);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("} //end case ");
}
internal void EndSwitch()
{
object stackTop = _blockStack.Pop();
SwitchState switchState = stackTop as SwitchState;
if (switchState == null)
ThrowMismatchException(stackTop);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("} //end switch");
if (!switchState.DefaultDefined)
MarkLabel(switchState.DefaultLabel);
MarkLabel(switchState.EndOfSwitchLabel);
}
private static MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod;
internal void ElseIfIsEmptyString(LocalBuilder strLocal)
{
IfState ifState = (IfState)_blockStack.Pop();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
Load(strLocal);
Call(s_stringLength);
Load(0);
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(Cmp.EqualTo), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void IfNotIsEmptyString(LocalBuilder strLocal)
{
Load(strLocal);
Call(s_stringLength);
Load(0);
If(Cmp.NotEqualTo);
}
#if !NET_NATIVE
internal void BeginWhileCondition()
{
Label startWhile = DefineLabel();
MarkLabel(startWhile);
_blockStack.Push(startWhile);
}
internal void BeginWhileBody(Cmp cmpOp)
{
Label startWhile = (Label)_blockStack.Pop();
If(cmpOp);
_blockStack.Push(startWhile);
}
internal void EndWhile()
{
Label startWhile = (Label)_blockStack.Pop();
Br(startWhile);
EndIf();
}
internal void CallStringFormat(string msg, params object[] values)
{
NewArray(typeof(object), values.Length);
if (_stringFormatArray == null)
_stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray");
Stloc(_stringFormatArray);
for (int i = 0; i < values.Length; i++)
StoreArrayElement(_stringFormatArray, i, values[i]);
Load(msg);
Load(_stringFormatArray);
Call(StringFormat);
}
internal void ToString(Type type)
{
if (type != Globals.TypeOfString)
{
if (type.GetTypeInfo().IsValueType)
{
Box(type);
}
Call(ObjectToString);
}
}
#endif
}
internal class ArgBuilder
{
internal int Index;
internal Type ArgType;
internal ArgBuilder(int index, Type argType)
{
this.Index = index;
this.ArgType = argType;
}
}
internal class ForState
{
private LocalBuilder _indexVar;
private Label _beginLabel;
private Label _testLabel;
private Label _endLabel;
private bool _requiresEndLabel;
private object _end;
internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
{
_indexVar = indexVar;
_beginLabel = beginLabel;
_testLabel = testLabel;
_end = end;
}
internal LocalBuilder Index
{
get
{
return _indexVar;
}
}
internal Label BeginLabel
{
get
{
return _beginLabel;
}
}
internal Label TestLabel
{
get
{
return _testLabel;
}
}
internal Label EndLabel
{
get
{
return _endLabel;
}
set
{
_endLabel = value;
}
}
internal bool RequiresEndLabel
{
get
{
return _requiresEndLabel;
}
set
{
_requiresEndLabel = value;
}
}
internal object End
{
get
{
return _end;
}
}
}
internal enum Cmp
{
LessThan,
EqualTo,
LessThanOrEqualTo,
GreaterThan,
NotEqualTo,
GreaterThanOrEqualTo
}
internal class IfState
{
private Label _elseBegin;
private Label _endIf;
internal Label EndIf
{
get
{
return _endIf;
}
set
{
_endIf = value;
}
}
internal Label ElseBegin
{
get
{
return _elseBegin;
}
set
{
_elseBegin = value;
}
}
}
internal class SwitchState
{
private Label _defaultLabel;
private Label _endOfSwitchLabel;
private bool _defaultDefined;
internal SwitchState(Label defaultLabel, Label endOfSwitchLabel)
{
_defaultLabel = defaultLabel;
_endOfSwitchLabel = endOfSwitchLabel;
_defaultDefined = false;
}
internal Label DefaultLabel
{
get
{
return _defaultLabel;
}
}
internal Label EndOfSwitchLabel
{
get
{
return _endOfSwitchLabel;
}
}
internal bool DefaultDefined
{
get
{
return _defaultDefined;
}
set
{
_defaultDefined = value;
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
internal static class IOInputs
{
// see: http://msdn.microsoft.com/en-us/library/aa365247.aspx
private static readonly char[] s_invalidFileNameChars = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
new char[] { '\"', '<', '>', '|', '\0', (Char)1, (Char)2, (Char)3, (Char)4, (Char)5, (Char)6, (Char)7, (Char)8, (Char)9, (Char)10, (Char)11, (Char)12, (Char)13, (Char)14, (Char)15, (Char)16, (Char)17, (Char)18, (Char)19, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25, (Char)26, (Char)27, (Char)28, (Char)29, (Char)30, (Char)31, '*', '?' } :
new char[] { '\0' };
public static bool SupportsSettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } }
public static bool SupportsGettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } }
public static bool CaseSensitive { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } }
public static bool CaseInsensitive { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } }
// Max path length (minus trailing \0). Unix values vary system to system; just using really long values here likely to be more than on the average system.
public static readonly int MaxPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 259 : 10000;
// Same as MaxPath on Unix
public static readonly int MaxLongPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MaxExtendedPath : MaxPath;
// Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move.
// Does not include the trailing \0.
// We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction.
public static readonly int MaxDirectory = 247;
// Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0.
public static readonly int MaxExtendedPath = short.MaxValue - 1;
public const int MaxComponent = 255;
public const string ExtendedPrefix = @"\\?\";
public const string ExtendedUncPrefix = @"\\?\UNC\";
public static IEnumerable<string> GetValidPathComponentNames()
{
yield return Path.GetRandomFileName();
yield return "!@#$%^&";
yield return "\x65e5\x672c\x8a9e";
yield return "A";
yield return " A";
yield return " A";
yield return "FileName";
yield return "FileName.txt";
yield return " FileName";
yield return " FileName.txt";
yield return " FileName";
yield return " FileName.txt";
yield return "This is a valid component name";
yield return "This is a valid component name.txt";
yield return "V1.0.0.0000";
}
public static IEnumerable<string> GetControlWhiteSpace()
{
yield return "\t";
yield return "\t\t";
yield return "\t\t\t";
yield return "\n";
yield return "\n\n";
yield return "\n\n\n";
yield return "\t\n";
yield return "\t\n\t\n";
yield return "\n\t\n";
yield return "\n\t\n\t";
}
public static IEnumerable<string> GetSimpleWhiteSpace()
{
yield return " ";
yield return " ";
yield return " ";
yield return " ";
yield return " ";
}
public static IEnumerable<string> GetWhiteSpace()
{
return GetControlWhiteSpace().Concat(GetSimpleWhiteSpace());
}
public static IEnumerable<string> GetUncPathsWithoutShareName()
{
foreach (char slash in new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar })
{
string slashes = new string(slash, 2);
yield return slashes;
yield return slashes + " ";
yield return slashes + new string(slash, 5);
yield return slashes + "S";
yield return slashes + "S ";
yield return slashes + "LOCALHOST";
yield return slashes + "LOCALHOST " + slash;
yield return slashes + "LOCALHOST " + new string(slash, 2);
yield return slashes + "LOCALHOST" + slash + " ";
yield return slashes + "LOCALHOST" + slash + slash + " ";
}
}
public static IEnumerable<string> GetPathsWithReservedDeviceNames()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
foreach (string deviceName in GetReservedDeviceNames())
{
yield return deviceName;
yield return Path.Combine(root, deviceName);
yield return Path.Combine(root, "Directory", deviceName);
yield return Path.Combine(new string(Path.DirectorySeparatorChar, 2), "LOCALHOST", deviceName);
}
}
public static IEnumerable<string> GetPathsWithAlternativeDataStreams()
{
yield return @"AA:";
yield return @"AAA:";
yield return @"AA:A";
yield return @"AAA:A";
yield return @"AA:AA";
yield return @"AAA:AA";
yield return @"AA:AAA";
yield return @"AAA:AAA";
yield return @"AA:FileName";
yield return @"AAA:FileName";
yield return @"AA:FileName.txt";
yield return @"AAA:FileName.txt";
yield return @"A:FileName.txt:";
yield return @"AA:FileName.txt:AA";
yield return @"AAA:FileName.txt:AAA";
yield return @"C:\:";
yield return @"C:\:FileName";
yield return @"C:\:FileName.txt";
yield return @"C:\fileName:";
yield return @"C:\fileName:FileName.txt";
yield return @"C:\fileName:FileName.txt:";
yield return @"C:\fileName:FileName.txt:AA";
yield return @"C:\fileName:FileName.txt:AAA";
yield return @"ftp://fileName:FileName.txt:AAA";
}
public static IEnumerable<string> GetPathsWithInvalidColons()
{
// Windows specific. We document that these return NotSupportedException.
yield return @":";
yield return @" :";
yield return @" :";
yield return @"C::";
yield return @"C::FileName";
yield return @"C::FileName.txt";
yield return @"C::FileName.txt:";
yield return @"C::FileName.txt::";
yield return @":f";
yield return @":filename";
yield return @"file:";
yield return @"file:file";
yield return @"http:";
yield return @"http:/";
yield return @"http://";
yield return @"http://www";
yield return @"http://www.microsoft.com";
yield return @"http://www.microsoft.com/index.html";
yield return @"http://server";
yield return @"http://server/";
yield return @"http://server/home";
yield return @"file://";
yield return @"file:///C|/My Documents/ALetter.html";
}
public static IEnumerable<string> GetPathsWithInvalidCharacters()
{
// NOTE: That I/O treats "file"/http" specially and throws ArgumentException.
// Otherwise, it treats all other urls as alternative data streams
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // alternate data streams, drive labels, etc.
{
yield return "\0";
yield return "middle\0path";
yield return "trailing\0";
yield return @"\\?\";
yield return @"\\?\UNC\";
yield return @"\\?\UNC\LOCALHOST";
}
else
{
yield return "\0";
yield return "middle\0path";
yield return "trailing\0";
}
foreach (char c in s_invalidFileNameChars)
{
yield return c.ToString();
}
}
public static IEnumerable<string> GetPathsWithComponentLongerThanMaxComponent()
{
// While paths themselves can be up to and including 32,000 characters, most volumes
// limit each component of the path to a total of 255 characters.
string component = new string('s', MaxComponent + 1);
yield return String.Format(@"C:\{0}", component);
yield return String.Format(@"C:\{0}\Filename.txt", component);
yield return String.Format(@"C:\{0}\Filename.txt\", component);
yield return String.Format(@"\\{0}\Share", component);
yield return String.Format(@"\\LOCALHOST\{0}", component);
yield return String.Format(@"\\LOCALHOST\{0}\FileName.txt", component);
yield return String.Format(@"\\LOCALHOST\Share\{0}", component);
}
public static IEnumerable<string> GetPathsLongerThanMaxDirectory(string rootPath)
{
yield return GetLongPath(rootPath, MaxDirectory + 1);
yield return GetLongPath(rootPath, MaxDirectory + 2);
yield return GetLongPath(rootPath, MaxDirectory + 3);
}
public static IEnumerable<string> GetPathsLongerThanMaxPath(string rootPath, bool useExtendedSyntax = false)
{
yield return GetLongPath(rootPath, MaxPath + 1, useExtendedSyntax);
yield return GetLongPath(rootPath, MaxPath + 2, useExtendedSyntax);
yield return GetLongPath(rootPath, MaxPath + 3, useExtendedSyntax);
}
public static IEnumerable<string> GetPathsLongerThanMaxLongPath(string rootPath, bool useExtendedSyntax = false)
{
yield return GetLongPath(rootPath, MaxExtendedPath + 1 - (useExtendedSyntax ? 0 : ExtendedPrefix.Length), useExtendedSyntax);
yield return GetLongPath(rootPath, MaxExtendedPath + 2 - (useExtendedSyntax ? 0 : ExtendedPrefix.Length), useExtendedSyntax);
}
private static string GetLongPath(string rootPath, int characterCount, bool extended = false)
{
return IOServices.GetPath(rootPath, characterCount, extended).FullPath;
}
public static IEnumerable<string> GetReservedDeviceNames()
{ // See: http://msdn.microsoft.com/en-us/library/aa365247.aspx
yield return "CON";
yield return "AUX";
yield return "NUL";
yield return "PRN";
yield return "COM1";
yield return "COM2";
yield return "COM3";
yield return "COM4";
yield return "COM5";
yield return "COM6";
yield return "COM7";
yield return "COM8";
yield return "COM9";
yield return "LPT1";
yield return "LPT2";
yield return "LPT3";
yield return "LPT4";
yield return "LPT5";
yield return "LPT6";
yield return "LPT7";
yield return "LPT8";
yield return "LPT9";
}
}
| |
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Alphaleonis.Vsx
{
/// <summary>
/// Base class for a single file code generator.
/// </summary>
[ComVisible(true)]
public abstract class BaseCodeGenerator : IVsSingleFileGenerator, IObjectWithSite
{
#region Private Fields
private IVsGeneratorProgress m_progress;
private string m_codeFileNamespace = String.Empty;
private string m_codeFilePath = String.Empty;
private ServiceProvider m_serviceProvider;
#endregion
#region IVsSingleFileGenerator Members
/// <summary>
/// Implements the IVsSingleFileGenerator.DefaultExtension method.
/// Returns the extension of the generated file
/// </summary>
/// <param name="pbstrDefaultExtension">Out parameter, will hold the extension that is to be given to the output file name. The returned extension must include a leading period</param>
/// <returns>S_OK if successful, E_FAIL if not</returns>
int IVsSingleFileGenerator.DefaultExtension(out string pbstrDefaultExtension)
{
try
{
pbstrDefaultExtension = GetDefaultExtension();
return VSConstants.S_OK;
}
catch (Exception)
{
pbstrDefaultExtension = string.Empty;
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Implements the IVsSingleFileGenerator.Generate method.
/// Executes the transformation and returns the newly generated output file, whenever a custom tool is loaded, or the input file is saved
/// </summary>
/// <param name="wszInputFilePath">The full path of the input file. May be a null reference (Nothing in Visual Basic) in future releases of Visual Studio, so generators should not rely on this value</param>
/// <param name="bstrInputFileContents">The contents of the input file. This is either a UNICODE BSTR (if the input file is text) or a binary BSTR (if the input file is binary). If the input file is a text file, the project system automatically converts the BSTR to UNICODE</param>
/// <param name="wszDefaultNamespace">This parameter is meaningful only for custom tools that generate code. It represents the namespace into which the generated code will be placed. If the parameter is not a null reference (Nothing in Visual Basic) and not empty, the custom tool can use the following syntax to enclose the generated code</param>
/// <param name="rgbOutputFileContents">[out] Returns an array of bytes to be written to the generated file. You must include UNICODE or UTF-8 signature bytes in the returned byte array, as this is a raw stream. The memory for rgbOutputFileContents must be allocated using the .NET Framework call, System.Runtime.InteropServices.AllocCoTaskMem, or the equivalent Win32 system call, CoTaskMemAlloc. The project system is responsible for freeing this memory</param>
/// <param name="pcbOutput">[out] Returns the count of bytes in the rgbOutputFileContent array</param>
/// <param name="pGenerateProgress">A reference to the IVsGeneratorProgress interface through which the generator can report its progress to the project system</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns E_FAIL</returns>
int IVsSingleFileGenerator.Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
{
if (bstrInputFileContents == null)
{
throw new ArgumentNullException(bstrInputFileContents);
}
m_codeFilePath = wszInputFilePath;
m_codeFileNamespace = wszDefaultNamespace;
m_progress = pGenerateProgress;
byte[] bytes = GenerateCode(wszInputFilePath, bstrInputFileContents);
if (bytes == null)
{
// This signals that GenerateCode() has failed. Tasklist items have been put up in GenerateCode()
rgbOutputFileContents = null;
pcbOutput = 0;
// Return E_FAIL to inform Visual Studio that the generator has failed (so that no file gets generated)
return VSConstants.E_FAIL;
}
else
{
// The contract between IVsSingleFileGenerator implementors and consumers is that
// any output returned from IVsSingleFileGenerator.Generate() is returned through
// memory allocated via CoTaskMemAlloc(). Therefore, we have to convert the
// byte[] array returned from GenerateCode() into an unmanaged blob.
int outputLength = bytes.Length;
rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
Marshal.Copy(bytes, 0, rgbOutputFileContents[0], outputLength);
pcbOutput = (uint)outputLength;
return VSConstants.S_OK;
}
}
#endregion
#region Properties
/// <summary>
/// Namespace for the file
/// </summary>
protected string FileNamespace
{
get
{
return m_codeFileNamespace;
}
}
/// <summary>
/// File-path for the input file
/// </summary>
protected string InputFilePath
{
get
{
return m_codeFilePath;
}
}
/// <summary>
/// Interface to the VS shell object we use to tell our progress while we are generating
/// </summary>
internal IVsGeneratorProgress Progress
{
get
{
return m_progress;
}
}
#endregion
#region Abstract Methods
/// <summary>
/// Gets the default extension for this generator
/// </summary>
/// <returns>String with the default extension for this generator</returns>
protected abstract string GetDefaultExtension();
/// <summary>
/// The method that does the actual work of generating code given the input file
/// </summary>
/// <param name="inputFileContent">File contents as a string</param>
/// <returns>The generated code file as a byte-array</returns>
protected abstract byte[] GenerateCode(string inputFilePath, string inputFileContent);
#endregion
#region Protected Methods
/// <summary>Method that will communicate an error via the shell callback mechanism.</summary>
/// <param name="message">Text displayed to the user.</param>
/// <param name="line">Line number of error.</param>
/// <param name="column">Column number of error.</param>
protected virtual void ReportError(string message, int line, int column)
{
ThreadHelper.ThrowIfNotOnUIThread();
IVsGeneratorProgress progress = Progress;
if (progress != null)
{
progress.GeneratorError(0, 0, message, (uint)line, (uint)column);
}
}
protected virtual void ReportError(string message, object location)
{
IVsGeneratorProgress progress = Progress;
ThreadHelper.ThrowIfNotOnUIThread();
EnvDTE.CodeElement codeElement = location as EnvDTE.CodeElement;
if (progress != null)
{
var startPoint = codeElement == null ? null : ((EnvDTE.CodeElement)location).StartPoint;
progress.GeneratorError(0, 0, message, startPoint == null ? (uint)0xFFFFFFFF : (uint)startPoint.Line, startPoint == null ? (uint)0xFFFFFFFF : (uint)startPoint.DisplayColumn);
}
}
protected virtual void ReportWarning(string message, object location)
{
IVsGeneratorProgress progress = Progress;
ThreadHelper.ThrowIfNotOnUIThread();
EnvDTE.CodeElement codeElement = location as EnvDTE.CodeElement;
if (progress != null)
{
var startPoint = codeElement == null ? null : ((EnvDTE.CodeElement)location).StartPoint;
progress.GeneratorError(1, 0, message, startPoint == null ? (uint)0xFFFFFFFF : (uint)startPoint.Line, startPoint == null ? (uint)0xFFFFFFFF : (uint)startPoint.DisplayColumn);
}
}
/// <summary>Method that will communicate a warning via the shell callback mechanism.</summary>
/// <param name="message">Text displayed to the user.</param>
/// <param name="line">Line number of warning.</param>
/// <param name="column">Column number of warning.</param>
protected virtual void ReportWarning(string message, int line, int column)
{
ThreadHelper.ThrowIfNotOnUIThread();
IVsGeneratorProgress progress = Progress;
if (progress != null)
{
progress.GeneratorError(1, 0, message, (uint)line, (uint)column);
}
}
/// <summary>Sets an index that specifies how much of the generation has been completed.</summary>
/// <param name="current">Index that specifies how much of the generation has been completed. This value can range from zero to <paramref name="total"/>.</param>
/// <param name="total">The maximum value for <paramref name="current"/>.</param>
protected virtual void ReportProgress(int current, int total)
{
ThreadHelper.ThrowIfNotOnUIThread();
IVsGeneratorProgress progress = Progress;
if (progress != null)
{
progress.Progress((uint)current, (uint)total);
}
}
#region IObjectWithSite Members
public object Site { get; private set; }
void IObjectWithSite.GetSite(ref Guid riid, out IntPtr ppvSite)
{
IntPtr pUnk = Marshal.GetIUnknownForObject(Site);
IntPtr intPointer = IntPtr.Zero;
Marshal.QueryInterface(pUnk, ref riid, out intPointer);
ppvSite = intPointer;
}
void IObjectWithSite.SetSite(object pUnkSite)
{
Site = pUnkSite;
}
private ServiceProvider SiteServiceProvider
{
get
{
ThreadHelper.ThrowIfNotOnUIThread();
if (m_serviceProvider == null && Site != null)
{
m_serviceProvider = new ServiceProvider(Site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
}
return m_serviceProvider;
}
}
//protected TService GetService<TRegistration, TService>() where TService : class
//{
// var serviceProvider = Site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
// if (serviceProvider != null)
// {
// var sp = new Microsoft.VisualStudio.Shell.ServiceProvider(serviceProvider);
// return sp.GetService<TRegistration, TService>();
// }
// return default(TService);
//}
protected object GetService(Guid serviceGuid)
{
ThreadHelper.ThrowIfNotOnUIThread();
return SiteServiceProvider.GetService(serviceGuid);
}
/// <summary>
/// Method to get a service by its Type
/// </summary>
/// <param name="serviceType">Type of service to retrieve</param>
/// <returns>An object that implements the requested service</returns>
protected object GetService(Type serviceType)
{
ThreadHelper.ThrowIfNotOnUIThread();
return SiteServiceProvider.GetService(serviceType);
}
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading.Tasks;
using TestTypes;
[ServiceContract]
public interface IWcfService
{
[OperationContract]
Message MessageRequestReply(Message message);
[OperationContract]
String Echo(String message);
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoComplex")]
ComplexCompositeType EchoComplex(ComplexCompositeType message);
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoWithTimeout")]
String EchoWithTimeout(String message, TimeSpan serviceOperationTimeout);
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoWithTimeout")]
Task<String> EchoWithTimeoutAsync(String message, TimeSpan serviceOperationTimeout);
[OperationContract(Action = "http://tempuri.org/IWcfService/GetDataUsingDataContract")]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
[FaultContract(typeof(FaultDetail), Action = "http://tempuri.org/IWcfService/TestFaultFaultDetailFault", Name = "FaultDetail", Namespace = "http://www.contoso.com/wcfnamespace")]
void TestFault(string faultMsg);
[OperationContract]
[FaultContract(typeof(int), Action = "http://tempuri.org/IWcfService/TestFaultIntFault", Name = "IntFault", Namespace = "http://www.contoso.com/wcfnamespace")]
void TestFaultInt(int faultCode);
[OperationContract]
[FaultContract(typeof(FaultDetail), Action = "http://tempuri.org/IWcfService/TestFaultFaultDetailFault", Name = "FaultDetail", Namespace = "http://www.contoso.com/wcfnamespace")]
[FaultContract(typeof(FaultDetail2), Action = "http://tempuri.org/IWcfService/TestFaultFaultDetailFault2", Name = "FaultDetail2", Namespace = "http://www.contoso.com/wcfnamespace")]
void TestFaults(string faultMsg, bool throwFaultDetail);
[OperationContract]
[FaultContract(typeof(FaultDetail), Action = "http://tempuri.org/IWcfService/TestFaultFaultDetailFault", Name = "FaultDetail", Namespace = "http://www.contoso.com/wcfnamespace")]
[ServiceKnownType(typeof(KnownTypeA))]
[ServiceKnownType(typeof(FaultDetail))]
object[] TestFaultWithKnownType(string faultMsg, object[] objects);
[OperationContract]
void ThrowInvalidOperationException(string message);
[OperationContract]
void NotExistOnServer();
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoHttpMessageProperty")]
TestHttpRequestMessageProperty EchoHttpRequestMessageProperty();
[OperationContract(Action = "http://tempuri.org/IWcfService/GetRestartServiceEndpoint")]
string GetRestartServiceEndpoint();
[OperationContract(Action = "http://tempuri.org/IWcfService/GetRequestCustomHeader", ReplyAction = "*")]
string GetRequestCustomHeader(string customHeaderName, string customHeaderNamespace);
[OperationContract(Action = "http://tempuri.org/IWcfService/GetIncomingMessageHeaders", ReplyAction = "*")]
Dictionary<string, string> GetIncomingMessageHeaders();
[OperationContract]
Stream GetStreamFromString(string data);
[OperationContract]
string GetStringFromStream(Stream stream);
[OperationContractAttribute(Action = "http://tempuri.org/IWcfService/EchoStream", ReplyAction = "http://tempuri.org/IWcfService/EchoStreamResponse")]
Stream EchoStream(Stream stream);
[OperationContractAttribute(Action = "http://tempuri.org/IWcfService/EchoStream", ReplyAction = "http://tempuri.org/IWcfService/EchoStreamResponse")]
Task<Stream> EchoStreamAsync(Stream stream);
[OperationContract]
void ReturnContentType(string contentType);
[OperationContract]
bool IsHttpKeepAliveDisabled();
[OperationContract]
Dictionary<string, string> GetRequestHttpHeaders();
}
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[ServiceContract]
public interface IWcfDecompService
{
[OperationContract]
bool IsDecompressionEnabled();
}
[ServiceContract]
public interface IWcfProjectNRestartService
{
[OperationContract]
string RestartService();
}
[ServiceContract(ConfigurationName = "IWcfService")]
public interface IWcfServiceXmlGenerated
{
[OperationContractAttribute(Action = "http://tempuri.org/IWcfService/EchoXmlSerializerFormat", ReplyAction = "http://tempuri.org/IWcfService/EchoXmlSerializerFormatResponse"),
XmlSerializerFormat]
string EchoXmlSerializerFormat(string message);
[OperationContractAttribute(Action = "http://tempuri.org/IWcfService/EchoXmlSerializerFormatSupportFaults", ReplyAction = "http://tempuri.org/IWcfService/EchoXmlSerializerFormatSupportFaultsResponse"),
XmlSerializerFormat(SupportFaults = true)]
string EchoXmlSerializerFormatSupportFaults(string message, bool pleaseThrowException);
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoXmlSerializerFormatUsingRpc", ReplyAction = "http://tempuri.org/IWcfService/EchoXmlSerializerFormatUsingRpcResponse"),
XmlSerializerFormat(Style = OperationFormatStyle.Rpc)]
string EchoXmlSerializerFormatUsingRpc(string message);
[OperationContractAttribute(Action = "http://tempuri.org/IWcfService/EchoXmlSerializerFormat", ReplyAction = "http://tempuri.org/IWcfService/EchoXmlSerializerFormatResponse"),
XmlSerializerFormat]
Task<string> EchoXmlSerializerFormatAsync(string message);
[OperationContract(Action = "http://tempuri.org/IWcfService/GetDataUsingXmlSerializer"),
XmlSerializerFormat]
XmlCompositeType GetDataUsingXmlSerializer(XmlCompositeType composite);
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoXmlVeryComplexType"),
XmlSerializerFormat]
XmlVeryComplexType EchoXmlVeryComplexType(XmlVeryComplexType complex);
}
[ServiceContract(ConfigurationName = "IWcfSoapService")]
public interface IWcfSoapService
{
[OperationContract(Action = "http://tempuri.org/IWcfService/CombineStringXmlSerializerFormatSoap", ReplyAction = "http://tempuri.org/IWcfService/CombineStringXmlSerializerFormatSoapResponse")]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, SupportFaults = true, Use = OperationFormatUse.Encoded)]
string CombineStringXmlSerializerFormatSoap(string message1, string message2);
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoComositeTypeXmlSerializerFormatSoap", ReplyAction = "http://tempuri.org/IWcfService/EchoComositeTypeXmlSerializerFormatSoapResponse")]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, SupportFaults = true, Use = OperationFormatUse.Encoded)]
SoapComplexType EchoComositeTypeXmlSerializerFormatSoap(SoapComplexType c);
[OperationContract(Action = "http://tempuri.org/IWcfService/ProcessCustomerData", ReplyAction = "http://tempuri.org/IWcfSoapService/ProcessCustomerDataResponse")]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, SupportFaults = true, Use = OperationFormatUse.Encoded)]
[ServiceKnownType(typeof(AdditionalData))]
[return: MessageParameter(Name = "ProcessCustomerDataReturn")]
string ProcessCustomerData(CustomerObject CustomerData);
[OperationContract(Action = "http://tempuri.org/IWcfService/Ping", ReplyAction = "http://tempuri.org/IWcfSoapService/PingResponse")]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, SupportFaults = true, Use = OperationFormatUse.Encoded)]
PingEncodedResponse Ping(PingEncodedRequest request);
}
// This type share the same name space with IWcfServiceXmlGenerated.
// And this type contains a method which is also defined in IWcfServiceXmlGenerated.
[ServiceContract(ConfigurationName = "IWcfService")]
public interface ISameNamespaceWithIWcfServiceXmlGenerated
{
[OperationContractAttribute(Action = "http://tempuri.org/IWcfService/EchoXmlSerializerFormat", ReplyAction = "http://tempuri.org/IWcfService/EchoXmlSerializerFormatResponse"),
XmlSerializerFormat]
string EchoXmlSerializerFormat(string message);
}
[System.ServiceModel.ServiceContractAttribute(ConfigurationName = "IWcfService")]
public interface IWcfServiceGenerated
{
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IWcfService/MessageRequestReply", ReplyAction = "http://tempuri.org/IWcfService/MessageRequestReplyResponse")]
System.ServiceModel.Channels.Message MessageRequestReply(System.ServiceModel.Channels.Message request);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IWcfService/MessageRequestReply", ReplyAction = "http://tempuri.org/IWcfService/MessageRequestReplyResponse")]
System.Threading.Tasks.Task<System.ServiceModel.Channels.Message> MessageRequestReplyAsync(System.ServiceModel.Channels.Message request);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IWcfService/Echo", ReplyAction = "http://tempuri.org/IWcfService/EchoResponse")]
string Echo(string message);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IWcfService/Echo", ReplyAction = "http://tempuri.org/IWcfService/EchoResponse")]
System.Threading.Tasks.Task<string> EchoAsync(string message);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IWcfService/EchoMessageParameter", ReplyAction = "http://tempuri.org/IWcfService/EchoMessageParameterResponse")]
[return: System.ServiceModel.MessageParameterAttribute(Name = "result")]
string EchoMessageParameter(string name);
}
[System.ServiceModel.ServiceContractAttribute(ConfigurationName = "IWcfService")]
public interface IWcfServiceBeginEndGenerated
{
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IWcfService/MessageRequestReply", ReplyAction = "http://tempuri.org/IWcfService/MessageRequestReplyResponse")]
System.ServiceModel.Channels.Message MessageRequestReply(System.ServiceModel.Channels.Message request);
[System.ServiceModel.OperationContractAttribute(AsyncPattern = true, Action = "http://tempuri.org/IWcfService/MessageRequestReply", ReplyAction = "http://tempuri.org/IWcfService/MessageRequestReplyResponse")]
System.IAsyncResult BeginMessageRequestReply(System.ServiceModel.Channels.Message request, System.AsyncCallback callback, object asyncState);
System.ServiceModel.Channels.Message EndMessageRequestReply(System.IAsyncResult result);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IWcfService/Echo", ReplyAction = "http://tempuri.org/IWcfService/EchoResponse")]
string Echo(string message);
[System.ServiceModel.OperationContractAttribute(AsyncPattern = true, Action = "http://tempuri.org/IWcfService/Echo", ReplyAction = "http://tempuri.org/IWcfService/EchoResponse")]
System.IAsyncResult BeginEcho(string message, System.AsyncCallback callback, object asyncState);
string EndEcho(System.IAsyncResult result);
}
// Dummy interface used for ContractDescriptionTests
[ServiceContract]
public interface IDescriptionTestsService
{
[OperationContract]
Message MessageRequestReply(Message message);
[OperationContract]
String Echo(String message);
}
// Dummy interface used for ContractDescriptionTests
// This code is deliberately not cleaned up after svcutil to test that we work with the raw Add Service Reference code.
[System.ServiceModel.ServiceContractAttribute(ConfigurationName = "IDescriptionTestsService")]
public interface IDescriptionTestsServiceGenerated
{
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IDescriptionTestsService/MessageRequestReply", ReplyAction = "http://tempuri.org/IDescriptionTestsService/MessageRequestReplyResponse")]
System.ServiceModel.Channels.Message MessageRequestReply(System.ServiceModel.Channels.Message request);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IDescriptionTestsService/MessageRequestReply", ReplyAction = "http://tempuri.org/IDescriptionTestsService/MessageRequestReplyResponse")]
System.Threading.Tasks.Task<System.ServiceModel.Channels.Message> MessageRequestReplyAsync(System.ServiceModel.Channels.Message request);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IDescriptionTestsService/Echo", ReplyAction = "http://tempuri.org/IDescriptionTestsService/EchoResponse")]
string Echo(string message);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IDescriptionTestsService/Echo", ReplyAction = "http://tempuri.org/IDescriptionTestsService/EchoResponse")]
System.Threading.Tasks.Task<string> EchoAsync(string message);
}
// Dummy interface used for ContractDescriptionTests
// This code is deliberately not cleaned up after svcutil to test that we work with the raw Add Service Reference code.
[System.ServiceModel.ServiceContractAttribute(ConfigurationName = "IDescriptionTestsService")]
public interface IDescriptionTestsServiceBeginEndGenerated
{
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IDescriptionTestsService/MessageRequestReply", ReplyAction = "http://tempuri.org/IDescriptionTestsService/MessageRequestReplyResponse")]
System.ServiceModel.Channels.Message MessageRequestReply(System.ServiceModel.Channels.Message request);
[System.ServiceModel.OperationContractAttribute(AsyncPattern = true, Action = "http://tempuri.org/IDescriptionTestsService/MessageRequestReply", ReplyAction = "http://tempuri.org/IDescriptionTestsService/MessageRequestReplyResponse")]
System.IAsyncResult BeginMessageRequestReply(System.ServiceModel.Channels.Message request, System.AsyncCallback callback, object asyncState);
System.ServiceModel.Channels.Message EndMessageRequestReply(System.IAsyncResult result);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IDescriptionTestsService/Echo", ReplyAction = "http://tempuri.org/IDescriptionTestsService/EchoResponse")]
string Echo(string message);
[System.ServiceModel.OperationContractAttribute(AsyncPattern = true, Action = "http://tempuri.org/IDescriptionTestsService/Echo", ReplyAction = "http://tempuri.org/IDescriptionTestsService/EchoResponse")]
System.IAsyncResult BeginEcho(string message, System.AsyncCallback callback, object asyncState);
string EndEcho(System.IAsyncResult result);
}
// Manually constructed service interface to validate MessageContract operations.
// This interface closely matches the one found at http://app.thefreedictionary.com/w8feedback.asmx
// This was done to test that we would work with that real world app.
[ServiceContract(Namespace = "http://app.my.com/MyFeedback", ConfigurationName = "TFDFeedbackService.MyFeedbackSoap")]
public interface IFeedbackService
{
[OperationContract(Action = "http://app.my.com/MyFeedback/Feedback", ReplyAction = "*")]
Task<FeedbackResponse> FeedbackAsync(FeedbackRequest request);
}
[ServiceContract]
public interface IUser
{
[OperationContract(Action = "http://tempuri.org/IWcfService/UserGetAuthToken")]
ResultObject<string> UserGetAuthToken();
[OperationContract(Action = "http://tempuri.org/IWcfService/ValidateMessagePropertyHeaders")]
Dictionary<string, string> ValidateMessagePropertyHeaders();
}
[ServiceContract]
public interface IWcfRestartService
{
[OperationContract]
String RestartService(Guid uniqueIdentifier);
[OperationContract]
String NonRestartService(Guid uniqueIdentifier);
}
[ServiceContract]
public interface IWcfCustomUserNameService
{
[OperationContract(Action = "http://tempuri.org/IWcfCustomUserNameService/Echo")]
String Echo(String message);
}
[ServiceContract(
Name = "SampleDuplexHello",
Namespace = "http://microsoft.wcf.test",
CallbackContract = typeof(IHelloCallbackContract)
)]
public interface IDuplexHello
{
[OperationContract(IsOneWay = true)]
void Hello(string greeting);
}
public interface IHelloCallbackContract
{
[OperationContract(IsOneWay = true)]
void Reply(string responseToGreeting);
}
[ServiceContract(CallbackContract = typeof(IWcfDuplexServiceCallback))]
public interface IWcfDuplexService
{
[OperationContract]
void Ping(Guid guid);
}
public interface IWcfDuplexServiceCallback
{
[OperationContract]
void OnPingCallback(Guid guid);
}
[ServiceContract(CallbackContract = typeof(IWcfDuplexTaskReturnCallback))]
public interface IWcfDuplexTaskReturnService
{
[OperationContract]
Task<Guid> Ping(Guid guid);
[OperationContract]
[FaultContract(typeof(FaultDetail), Name = "FaultDetail",
Action = "http://tempuri.org/IWcfDuplexTaskReturnService/FaultPingFaultDetailFault")]
Task<Guid> FaultPing(Guid guid);
}
public interface IWcfDuplexTaskReturnCallback
{
[OperationContract]
Task<Guid> ServicePingCallback(Guid guid);
[OperationContract]
[FaultContract(typeof(FaultDetail), Name = "FaultDetail",
Action = "http://tempuri.org/IWcfDuplexTaskReturnCallback/ServicePingFaultCallbackFaultDetailFault")]
Task<Guid> ServicePingFaultCallback(Guid guid);
}
// ********************************************************************************
[ServiceContract(CallbackContract = typeof(IWcfDuplexService_DataContract_Callback))]
public interface IWcfDuplexService_DataContract
{
[OperationContract]
void Ping_DataContract(Guid guid);
}
public interface IWcfDuplexService_DataContract_Callback
{
[OperationContract]
void OnDataContractPingCallback(ComplexCompositeTypeDuplexCallbackOnly complexCompositeType);
}
// ********************************************************************************
[ServiceContract(CallbackContract = typeof(IWcfDuplexService_Xml_Callback))]
public interface IWcfDuplexService_Xml
{
[OperationContract]
void Ping_Xml(Guid guid);
}
public interface IWcfDuplexService_Xml_Callback
{
[OperationContract, XmlSerializerFormat]
void OnXmlPingCallback(XmlCompositeTypeDuplexCallbackOnly xmlCompositeType);
}
[ServiceContract(CallbackContract = typeof(IWcfDuplexService_CallbackConcurrencyMode_Callback))]
public interface IWcfDuplexService_CallbackConcurrencyMode
{
[OperationContract]
Task DoWorkAsync();
}
public interface IWcfDuplexService_CallbackConcurrencyMode_Callback
{
[OperationContract]
Task CallWithWaitAsync(int delayTime);
}
// WebSocket Interfaces
[ServiceContract]
public interface IWSRequestReplyService
{
[OperationContract]
void UploadData(string data);
[OperationContract]
string DownloadData();
[OperationContract]
void UploadStream(Stream stream);
[OperationContract]
Stream DownloadStream();
[OperationContract]
Stream DownloadCustomizedStream(TimeSpan readThrottle, TimeSpan streamDuration);
[OperationContract]
void ThrowingOperation(Exception exceptionToThrow);
[OperationContract]
string DelayOperation(TimeSpan delay);
// Logging
[OperationContract]
List<string> GetLog();
}
[ServiceContract(CallbackContract = typeof(IPushCallback))]
public interface IWSDuplexService
{
// Request-Reply operations
[OperationContract]
string GetExceptionString();
[OperationContract]
void UploadData(string data);
[OperationContract]
string DownloadData();
[OperationContract(IsOneWay = true)]
void UploadStream(Stream stream);
[OperationContract]
Stream DownloadStream();
// Duplex operations
[OperationContract(IsOneWay = true)]
void StartPushingData();
[OperationContract(IsOneWay = true)]
void StopPushingData();
[OperationContract(IsOneWay = true)]
void StartPushingStream();
[OperationContract(IsOneWay = true)]
void StartPushingStreamLongWait();
[OperationContract(IsOneWay = true)]
void StopPushingStream();
// Logging
[OperationContract(IsOneWay = true)]
void GetLog();
}
public interface IPushCallback
{
[OperationContract(IsOneWay = true)]
void ReceiveData(string data);
[OperationContract(IsOneWay = true)]
void ReceiveStream(Stream stream);
[OperationContract(IsOneWay = true)]
void ReceiveLog(List<string> log);
}
// ********************************************************************************
[ServiceContract]
public interface IServiceContractIntOutService
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginRequest(string stringRequest, AsyncCallback callback, object asyncState);
void EndRequest(out int intResponse, IAsyncResult result);
}
[ServiceContract]
public interface IServiceContractUniqueTypeOutService
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginRequest(string stringRequest, AsyncCallback callback, object asyncState);
void EndRequest(out UniqueType uniqueTypeResponse, IAsyncResult result);
}
[ServiceContract]
public interface IServiceContractIntRefService
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginRequest(string stringRequest, ref int referencedInteger, AsyncCallback callback, object asyncState);
void EndRequest(ref int referencedInteger, IAsyncResult result);
}
[ServiceContract]
public interface IServiceContractUniqueTypeRefService
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginRequest(string stringRequest, ref UniqueType uniqueTypeResponse, AsyncCallback callback, object asyncState);
void EndRequest(ref UniqueType uniqueTypeResponse, IAsyncResult result);
}
[ServiceContract]
public interface IServiceContractUniqueTypeOutSyncService
{
[OperationContract]
void Request(string stringRequest, out UniqueType uniqueTypeResponse);
[OperationContract]
void Request2(out UniqueType uniqueTypeResponse, string stringRequest);
}
[ServiceContract]
public interface IServiceContractUniqueTypeRefSyncService
{
[OperationContract]
void Request(string stringRequest, ref UniqueType uniqueTypeResponse);
}
[ServiceContract]
public interface ILoginService
{
[OperationContract(Action = "http://www.contoso.com/MtcRequest/loginRequest", ReplyAction = "http://www.contoso.com/MtcRequest/loginResponse")]
[XmlSerializerFormat]
LoginResponse Login(LoginRequest request);
}
[ServiceContract(Namespace = "http://www.contoso.com/IXmlMessageContarctTestService")]
public interface IXmlMessageContarctTestService
{
[OperationContract(
Action = "http://www.contoso.com/IXmlMessageContarctTestService/EchoMessageResponseWithMessageHeader",
ReplyAction = "*")]
[XmlSerializerFormat(SupportFaults = true)]
XmlMessageContractTestResponse EchoMessageResponseWithMessageHeader(XmlMessageContractTestRequest request);
[OperationContract(
Action = "http://www.contoso.com/IXmlMessageContarctTestService/EchoMessageResquestWithMessageHeader",
ReplyAction = "*")]
[XmlSerializerFormat(SupportFaults = true)]
XmlMessageContractTestResponse EchoMessageResquestWithMessageHeader(XmlMessageContractTestRequestWithMessageHeader request);
}
[ServiceContract]
public interface IWcfAspNetCompatibleService
{
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoCookie", ReplyAction = "http://tempuri.org/IWcfService/EchoCookieResponse")]
string EchoCookie();
[OperationContract(Action = "http://tempuri.org/IWcfService/EchoTimeAndSetCookie", ReplyAction = "http://tempuri.org/IIWcfService/EchoTimeAndSetCookieResponse")]
string EchoTimeAndSetCookie(string name);
}
[ServiceContract(ConfigurationName = "IWcfService")]
public interface IWcfServiceXml_OperationContext
{
[XmlSerializerFormat]
[ServiceKnownType(typeof(MesssageHeaderCreateHeaderWithXmlSerializerTestType))]
[OperationContract(Action = "http://tempuri.org/IWcfService/GetIncomingMessageHeadersMessage", ReplyAction = "*")]
string GetIncomingMessageHeadersMessage(string customHeaderName, string customHeaderNS);
}
[ServiceContract]
public interface IWcfChannelExtensibilityContract
{
[OperationContract(IsOneWay = true)]
void ReportWindSpeed(int speed);
}
[ServiceContract]
public interface IVerifyWebSockets
{
[OperationContract()]
bool ValidateWebSocketsUsed();
}
[ServiceContract]
public interface IDataContractResolverService
{
[OperationContract(Action = "http://tempuri.org/IDataContractResolverService/GetAllEmployees")]
List<Employee> GetAllEmployees();
[OperationContract(Action = "http://tempuri.org/IDataContractResolverService/AddEmployee")]
void AddEmployee(Employee employee);
}
[ServiceContract(SessionMode = SessionMode.Required)]
public interface ISessionTestsDefaultService
{
[OperationContract(IsInitiating = true, IsTerminating = false)]
int MethodAInitiating(int a);
[OperationContract(IsInitiating = false, IsTerminating = false)]
int MethodBNonInitiating(int b);
[OperationContract(IsInitiating = false, IsTerminating = true)]
SessionTestsCompositeType MethodCTerminating();
}
[ServiceContract(SessionMode = SessionMode.Required)]
public interface ISessionTestsShortTimeoutService : ISessionTestsDefaultService
{
}
[ServiceContract(CallbackContract = typeof(ISessionTestsDuplexCallback), SessionMode = SessionMode.Required)]
public interface ISessionTestsDuplexService
{
[OperationContract]
int NonTerminatingMethodCallingDuplexCallbacks(
int callsToClientCallbackToMake,
int callsToTerminatingClientCallbackToMake,
int callsToClientSideOnlyTerminatingClientCallbackToMake,
int callsToNonTerminatingMethodToMakeInsideClientCallback,
int callsToTerminatingMethodToMakeInsideClientCallback);
[OperationContract]
int TerminatingMethodCallingDuplexCallbacks(
int callsToClientCallbackToMake,
int callsToTerminatingClientCallbackToMake,
int callsToClientSideOnlyTerminatingClientCallbackToMake,
int callsToNonTerminatingMethodToMakeInsideClientCallback,
int callsToTerminatingMethodToMakeInsideClientCallback);
[OperationContract(IsInitiating = true, IsTerminating = false)]
int NonTerminatingMethod();
[OperationContract(IsInitiating = true, IsTerminating = true)]
int TerminatingMethod();
}
[ServiceContract(SessionMode = SessionMode.Required)]
public interface ISessionTestsDuplexCallback
{
[OperationContract(IsInitiating = true, IsTerminating = false)]
int ClientCallback(int callsToNonTerminatingMethodToMake, int callsToTerminatingMethodToMake);
[OperationContract(IsInitiating = true, IsTerminating = true)]
int TerminatingClientCallback(int callsToNonTerminatingMethodToMake, int callsToTerminatingMethodToMake);
[OperationContract(IsInitiating = true, IsTerminating = true)]
int ClientSideOnlyTerminatingClientCallback(int callsToNonTerminatingMethodToMake, int callsToTerminatingMethodToMake);
}
[ServiceContract, XmlSerializerFormat]
public interface IXmlSFAttribute
{
[OperationContract, XmlSerializerFormat(SupportFaults = true)]
[FaultContract(typeof(FaultDetailWithXmlSerializerFormatAttribute),
Action = "http://tempuri.org/IWcfService/FaultDetailWithXmlSerializerFormatAttribute",
Name = "FaultDetailWithXmlSerializerFormatAttribute",
Namespace = "http://www.contoso.com/wcfnamespace")]
void TestXmlSerializerSupportsFaults_True();
[OperationContract, XmlSerializerFormat]
[FaultContract(typeof(FaultDetailWithXmlSerializerFormatAttribute),
Action = "http://tempuri.org/IWcfService/FaultDetailWithXmlSerializerFormatAttribute",
Name = "FaultDetailWithXmlSerializerFormatAttribute",
Namespace = "http://www.contoso.com/wcfnamespace")]
void TestXmlSerializerSupportsFaults_False();
}
[ServiceContract(Namespace = "http://contoso.com/calc")]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public interface ICalculatorRpcEnc
{
[OperationContract]
int Sum2(int i, int j);
[OperationContract]
int Sum(IntParams par);
[OperationContract]
float Divide(FloatParams par);
[OperationContract]
string Concatenate(IntParams par);
[OperationContract]
void AddIntParams(Guid guid, IntParams par);
[OperationContract]
IntParams GetAndRemoveIntParams(Guid guid);
[OperationContract]
DateTime ReturnInputDateTime(DateTime dt);
[OperationContract]
byte[] CreateSet(ByteParams par);
}
[ServiceContract(Namespace = "http://contoso.com/calc")]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public interface ICalculatorRpcLit
{
[OperationContract]
int Sum2(int i, int j);
[OperationContract]
int Sum(IntParams par);
[OperationContract]
float Divide(FloatParams par);
[OperationContract]
string Concatenate(IntParams par);
[OperationContract]
void AddIntParams(Guid guid, IntParams par);
[OperationContract]
IntParams GetAndRemoveIntParams(Guid guid);
[OperationContract]
DateTime ReturnInputDateTime(DateTime dt);
[OperationContract]
byte[] CreateSet(ByteParams par);
}
[ServiceContract(Namespace = "http://contoso.com/calc")]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public interface ICalculatorDocLit
{
[OperationContract]
int Sum2(int i, int j);
[OperationContract]
int Sum(IntParams par);
[OperationContract]
float Divide(FloatParams par);
[OperationContract]
string Concatenate(IntParams par);
[OperationContract]
void AddIntParams(Guid guid, IntParams par);
[OperationContract]
IntParams GetAndRemoveIntParams(Guid guid);
[OperationContract]
DateTime ReturnInputDateTime(DateTime dt);
[OperationContract]
byte[] CreateSet(ByteParams par);
}
[ServiceContract]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public interface IHelloWorldRpcEnc
{
[OperationContract]
void AddString(Guid guid, string testString);
[OperationContract]
string GetAndRemoveString(Guid guid);
}
[ServiceContract]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public interface IHelloWorldRpcLit
{
[OperationContract]
void AddString(Guid guid, string testString);
[OperationContract]
string GetAndRemoveString(Guid guid);
}
[ServiceContract]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public interface IHelloWorldDocLit
{
[OperationContract]
void AddString(Guid guid, string testString);
[OperationContract]
string GetAndRemoveString(Guid guid);
}
[ServiceContract]
public interface IEchoRpcEncWithHeadersService
{
[OperationContract(Action = "http://tempuri.org/Echo", ReplyAction = "*")]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
EchoResponse Echo(EchoRequest request);
}
[System.Xml.Serialization.SoapType(Namespace = "http://tempuri.org/")]
public partial class StringHeader
{
public string HeaderValue { get; set; }
}
[MessageContract(WrapperName = "Echo", WrapperNamespace = "http://contoso.com/", IsWrapped = true)]
public partial class EchoRequest
{
[MessageHeader]
public StringHeader StringHeader;
[MessageBodyMember(Namespace = "", Order = 0)]
public string message;
}
[MessageContract(WrapperName = "EchoResponse", WrapperNamespace = "http://tempuri.org/", IsWrapped = true)]
public partial class EchoResponse
{
[MessageHeader]
public StringHeader StringHeader;
[MessageBodyMember(Namespace = "", Order = 0)]
public string EchoResult;
}
public class IntParams
{
public int P1;
public int P2;
}
public class FloatParams
{
public float P1;
public float P2;
}
public class ByteParams
{
public byte P1;
public byte P2;
}
// ********************************************************************************
[ServiceContract]
public interface IWcfReliableService
{
[OperationContract]
Task<int> GetNextNumberAsync();
[OperationContract]
Task<string> EchoAsync(string echo);
}
[ServiceContract]
public interface IOneWayWcfReliableService
{
[OperationContract(IsOneWay = true)]
Task OneWayAsync(string text);
}
[ServiceContract(CallbackContract = typeof(IWcfReliableDuplexService))]
public interface IWcfReliableDuplexService
{
[OperationContract]
Task<string> DuplexEchoAsync(string echo);
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Construction;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
/// <summary>
/// An API for loading msbuild project files.
/// </summary>
public class MSBuildProjectLoader
{
// the workspace that the projects and solutions are intended to be loaded into.
private readonly Workspace _workspace;
// used to protect access to the following mutable state
private readonly NonReentrantLock _dataGuard = new NonReentrantLock();
private ImmutableDictionary<string, string> _properties;
private readonly Dictionary<string, string> _extensionToLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Create a new instance of an <see cref="MSBuildProjectLoader"/>.
/// </summary>
public MSBuildProjectLoader(Workspace workspace, ImmutableDictionary<string, string> properties = null)
{
_workspace = workspace;
_properties = properties ?? ImmutableDictionary<string, string>.Empty;
}
/// <summary>
/// The MSBuild properties used when interpreting project files.
/// These are the same properties that are passed to msbuild via the /property:<n>=<v> command line argument.
/// </summary>
public ImmutableDictionary<string, string> Properties
{
get { return _properties; }
}
/// <summary>
/// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects.
/// If the referenced project is already opened, the metadata will not be loaded.
/// If the metadata assembly cannot be found the referenced project will be opened instead.
/// </summary>
public bool LoadMetadataForReferencedProjects { get; set; } = false;
/// <summary>
/// Determines if unrecognized projects are skipped when solutions or projects are opened.
///
/// An project is unrecognized if it either has
/// a) an invalid file path,
/// b) a non-existent project file,
/// c) has an unrecognized file extension or
/// d) a file extension associated with an unsupported language.
///
/// If unrecognized projects cannot be skipped a corresponding exception is thrown.
/// </summary>
public bool SkipUnrecognizedProjects { get; set; } = true;
/// <summary>
/// Associates a project file extension with a language name.
/// </summary>
public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language)
{
if (language == null)
{
throw new ArgumentNullException(nameof(language));
}
if (projectFileExtension == null)
{
throw new ArgumentNullException(nameof(projectFileExtension));
}
using (_dataGuard.DisposableWait())
{
_extensionToLanguageMap[projectFileExtension] = language;
}
}
private const string SolutionDirProperty = "SolutionDir";
private void SetSolutionProperties(string solutionFilePath)
{
// When MSBuild is building an individual project, it doesn't define $(SolutionDir).
// However when building an .sln file, or when working inside Visual Studio,
// $(SolutionDir) is defined to be the directory where the .sln file is located.
// Some projects out there rely on $(SolutionDir) being set (although the best practice is to
// use MSBuildProjectDirectory which is always defined).
if (!string.IsNullOrEmpty(solutionFilePath))
{
string solutionDirectory = Path.GetDirectoryName(solutionFilePath);
if (!solutionDirectory.EndsWith(@"\", StringComparison.Ordinal))
{
solutionDirectory += @"\";
}
if (Directory.Exists(solutionDirectory))
{
_properties = _properties.SetItem(SolutionDirProperty, solutionDirectory);
}
}
}
/// <summary>
/// Loads the <see cref="SolutionInfo"/> for the specified solution file, including all projects referenced by the solution file and
/// all the projects referenced by the project files.
/// </summary>
public async Task<SolutionInfo> LoadSolutionInfoAsync(
string solutionFilePath,
CancellationToken cancellationToken = default(CancellationToken))
{
if (solutionFilePath == null)
{
throw new ArgumentNullException(nameof(solutionFilePath));
}
var absoluteSolutionPath = this.GetAbsoluteSolutionPath(solutionFilePath, Directory.GetCurrentDirectory());
using (_dataGuard.DisposableWait(cancellationToken))
{
this.SetSolutionProperties(absoluteSolutionPath);
}
VersionStamp version = default(VersionStamp);
Microsoft.Build.Construction.SolutionFile solutionFile = Microsoft.Build.Construction.SolutionFile.Parse(absoluteSolutionPath);
var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw;
// a list to accumulate all the loaded projects
var loadedProjects = new LoadState(null);
// load all the projects
foreach (var project in solutionFile.ProjectsInOrder)
{
cancellationToken.ThrowIfCancellationRequested();
if (project.ProjectType != SolutionProjectType.SolutionFolder)
{
var projectAbsolutePath = TryGetAbsolutePath(project.AbsolutePath, reportMode);
if (projectAbsolutePath != null)
{
IProjectFileLoader loader;
if (TryGetLoaderFromProjectPath(projectAbsolutePath, reportMode, out loader))
{
// projects get added to 'loadedProjects' as side-effect
// never prefer metadata when loading solution, all projects get loaded if they can.
var tmp = await GetOrLoadProjectAsync(projectAbsolutePath, loader, preferMetadata: false, loadedProjects: loadedProjects, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}
}
// construct workspace from loaded project infos
return SolutionInfo.Create(SolutionId.CreateNewId(debugName: absoluteSolutionPath), version, absoluteSolutionPath, loadedProjects.Projects);
}
internal string GetAbsoluteSolutionPath(string path, string baseDirectory)
{
string absolutePath;
try
{
absolutePath = GetAbsolutePath(path, baseDirectory);
}
catch (Exception)
{
throw new InvalidOperationException(string.Format(WorkspacesResources.Invalid_solution_file_path_colon_0, path));
}
if (!File.Exists(absolutePath))
{
throw new FileNotFoundException(string.Format(WorkspacesResources.Solution_file_not_found_colon_0, absolutePath));
}
return absolutePath;
}
/// <summary>
/// Loads the <see cref="ProjectInfo"/> from the specified project file and all referenced projects.
/// The first <see cref="ProjectInfo"/> in the result corresponds to the specified project file.
/// </summary>
public async Task<ImmutableArray<ProjectInfo>> LoadProjectInfoAsync(
string projectFilePath,
ImmutableDictionary<string, ProjectId> projectPathToProjectIdMap = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (projectFilePath == null)
{
throw new ArgumentNullException(nameof(projectFilePath));
}
string fullPath;
this.TryGetAbsoluteProjectPath(projectFilePath, Directory.GetCurrentDirectory(), ReportMode.Throw, out fullPath);
IProjectFileLoader loader;
this.TryGetLoaderFromProjectPath(projectFilePath, ReportMode.Throw, out loader);
var loadedProjects = new LoadState(projectPathToProjectIdMap);
var id = await this.LoadProjectAsync(fullPath, loader, this.LoadMetadataForReferencedProjects, loadedProjects, cancellationToken).ConfigureAwait(false);
var result = loadedProjects.Projects.Reverse().ToImmutableArray();
Debug.Assert(result[0].Id == id);
return result;
}
private class LoadState
{
private Dictionary<ProjectId, ProjectInfo> _projectIdToProjectInfoMap
= new Dictionary<ProjectId, ProjectInfo>();
private List<ProjectInfo> _projectInfoList
= new List<ProjectInfo>();
private readonly Dictionary<string, ProjectId> _projectPathToProjectIdMap
= new Dictionary<string, ProjectId>();
public LoadState(IReadOnlyDictionary<string, ProjectId> projectPathToProjectIdMap)
{
if (projectPathToProjectIdMap != null)
{
_projectPathToProjectIdMap.AddRange(projectPathToProjectIdMap);
}
}
public void Add(ProjectInfo info)
{
_projectIdToProjectInfoMap.Add(info.Id, info);
_projectInfoList.Add(info);
}
public bool TryGetValue(ProjectId id, out ProjectInfo info)
{
return _projectIdToProjectInfoMap.TryGetValue(id, out info);
}
public IReadOnlyList<ProjectInfo> Projects
{
get { return _projectInfoList; }
}
public ProjectId GetProjectId(string fullProjectPath)
{
ProjectId id;
_projectPathToProjectIdMap.TryGetValue(fullProjectPath, out id);
return id;
}
public ProjectId GetOrCreateProjectId(string fullProjectPath)
{
ProjectId id;
if (!_projectPathToProjectIdMap.TryGetValue(fullProjectPath, out id))
{
id = ProjectId.CreateNewId(debugName: fullProjectPath);
_projectPathToProjectIdMap.Add(fullProjectPath, id);
}
return id;
}
}
private async Task<ProjectId> GetOrLoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, LoadState loadedProjects, CancellationToken cancellationToken)
{
var projectId = loadedProjects.GetProjectId(projectFilePath);
if (projectId == null)
{
projectId = await this.LoadProjectAsync(projectFilePath, loader, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false);
}
return projectId;
}
private async Task<ProjectId> LoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, LoadState loadedProjects, CancellationToken cancellationToken)
{
Debug.Assert(projectFilePath != null);
Debug.Assert(loader != null);
var projectId = loadedProjects.GetOrCreateProjectId(projectFilePath);
var projectName = Path.GetFileNameWithoutExtension(projectFilePath);
var projectFile = await loader.LoadProjectFileAsync(projectFilePath, _properties, cancellationToken).ConfigureAwait(false);
var projectFileInfo = await projectFile.GetProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);
var projectDirectory = Path.GetDirectoryName(projectFilePath);
var outputFilePath = projectFileInfo.OutputFilePath;
var outputDirectory = Path.GetDirectoryName(outputFilePath);
VersionStamp version;
if (!string.IsNullOrEmpty(projectFilePath) && File.Exists(projectFilePath))
{
version = VersionStamp.Create(File.GetLastWriteTimeUtc(projectFilePath));
}
else
{
version = VersionStamp.Create();
}
// translate information from command line args
var commandLineParser = _workspace.Services.GetLanguageServices(loader.Language).GetService<ICommandLineParserService>();
var metadataService = _workspace.Services.GetService<IMetadataService>();
var analyzerService = _workspace.Services.GetService<IAnalyzerService>();
var commandLineArgs = commandLineParser.Parse(
arguments: projectFileInfo.CommandLineArgs,
baseDirectory: projectDirectory,
isInteractive: false,
sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory());
// we only support file paths in /r command line arguments
var resolver = new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory));
var metadataReferences = commandLineArgs.ResolveMetadataReferences(resolver);
var analyzerLoader = analyzerService.GetLoader();
foreach (var path in commandLineArgs.AnalyzerReferences.Select(r => r.FilePath))
{
analyzerLoader.AddDependencyLocation(path);
}
var analyzerReferences = commandLineArgs.ResolveAnalyzerReferences(analyzerLoader);
var defaultEncoding = commandLineArgs.Encoding;
// docs & additional docs
var docFileInfos = projectFileInfo.Documents.ToImmutableArrayOrEmpty();
var additionalDocFileInfos = projectFileInfo.AdditionalDocuments.ToImmutableArrayOrEmpty();
// check for duplicate documents
var allDocFileInfos = docFileInfos.AddRange(additionalDocFileInfos);
CheckDocuments(allDocFileInfos, projectFilePath, projectId);
var docs = new List<DocumentInfo>();
foreach (var docFileInfo in docFileInfos)
{
string name;
ImmutableArray<string> folders;
GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders);
docs.Add(DocumentInfo.Create(
DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath),
name,
folders,
projectFile.GetSourceCodeKind(docFileInfo.FilePath),
new FileTextLoader(docFileInfo.FilePath, defaultEncoding),
docFileInfo.FilePath,
docFileInfo.IsGenerated));
}
var additionalDocs = new List<DocumentInfo>();
foreach (var docFileInfo in additionalDocFileInfos)
{
string name;
ImmutableArray<string> folders;
GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders);
additionalDocs.Add(DocumentInfo.Create(
DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath),
name,
folders,
SourceCodeKind.Regular,
new FileTextLoader(docFileInfo.FilePath, defaultEncoding),
docFileInfo.FilePath,
docFileInfo.IsGenerated));
}
// project references
var resolvedReferences = await ResolveProjectReferencesAsync(
projectId, projectFilePath, projectFileInfo.ProjectReferences, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false);
// add metadata references for project refs converted to metadata refs
metadataReferences = metadataReferences.Concat(resolvedReferences.MetadataReferences);
// if the project file loader couldn't figure out an assembly name, make one using the project's file path.
var assemblyName = commandLineArgs.CompilationName;
if (string.IsNullOrWhiteSpace(assemblyName))
{
assemblyName = Path.GetFileNameWithoutExtension(projectFilePath);
// if this is still unreasonable, use a fixed name.
if (string.IsNullOrWhiteSpace(assemblyName))
{
assemblyName = "assembly";
}
}
// make sure that doc-comments at least get parsed.
var parseOptions = commandLineArgs.ParseOptions;
if (parseOptions.DocumentationMode == DocumentationMode.None)
{
parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Parse);
}
// add all the extra options that are really behavior overrides
var compOptions = commandLineArgs.CompilationOptions
.WithXmlReferenceResolver(new XmlFileResolver(projectDirectory))
.WithSourceReferenceResolver(new SourceFileResolver(ImmutableArray<string>.Empty, projectDirectory))
// TODO: https://github.com/dotnet/roslyn/issues/4967
.WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray<string>.Empty, projectDirectory)))
.WithStrongNameProvider(new DesktopStrongNameProvider(ImmutableArray.Create(projectDirectory, outputFilePath)))
.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
loadedProjects.Add(
ProjectInfo.Create(
projectId,
version,
projectName,
assemblyName,
loader.Language,
projectFilePath,
outputFilePath,
compilationOptions: compOptions,
parseOptions: parseOptions,
documents: docs,
projectReferences: resolvedReferences.ProjectReferences,
metadataReferences: metadataReferences,
analyzerReferences: analyzerReferences,
additionalDocuments: additionalDocs,
isSubmission: false,
hostObjectType: null));
return projectId;
}
private static readonly char[] s_directorySplitChars = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
private static void GetDocumentNameAndFolders(string logicalPath, out string name, out ImmutableArray<string> folders)
{
var pathNames = logicalPath.Split(s_directorySplitChars, StringSplitOptions.RemoveEmptyEntries);
if (pathNames.Length > 0)
{
if (pathNames.Length > 1)
{
folders = pathNames.Take(pathNames.Length - 1).ToImmutableArray();
}
else
{
folders = ImmutableArray.Create<string>();
}
name = pathNames[pathNames.Length - 1];
}
else
{
name = logicalPath;
folders = ImmutableArray.Create<string>();
}
}
private void CheckDocuments(IEnumerable<DocumentFileInfo> docs, string projectFilePath, ProjectId projectId)
{
var paths = new HashSet<string>();
foreach (var doc in docs)
{
if (paths.Contains(doc.FilePath))
{
_workspace.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Warning, string.Format(WorkspacesResources.Duplicate_source_file_0_in_project_1, doc.FilePath, projectFilePath), projectId));
}
paths.Add(doc.FilePath);
}
}
private class ResolvedReferences
{
public readonly List<ProjectReference> ProjectReferences = new List<ProjectReference>();
public readonly List<MetadataReference> MetadataReferences = new List<MetadataReference>();
}
private async Task<ResolvedReferences> ResolveProjectReferencesAsync(
ProjectId thisProjectId,
string thisProjectPath,
IReadOnlyList<ProjectFileReference> projectFileReferences,
bool preferMetadata,
LoadState loadedProjects,
CancellationToken cancellationToken)
{
var resolvedReferences = new ResolvedReferences();
var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw;
foreach (var projectFileReference in projectFileReferences)
{
string fullPath;
if (TryGetAbsoluteProjectPath(projectFileReference.Path, Path.GetDirectoryName(thisProjectPath), reportMode, out fullPath))
{
// if the project is already loaded, then just reference the one we have
var existingProjectId = loadedProjects.GetProjectId(fullPath);
if (existingProjectId != null)
{
resolvedReferences.ProjectReferences.Add(new ProjectReference(existingProjectId, projectFileReference.Aliases));
continue;
}
IProjectFileLoader loader;
TryGetLoaderFromProjectPath(fullPath, ReportMode.Ignore, out loader);
// get metadata if preferred or if loader is unknown
if (preferMetadata || loader == null)
{
var projectMetadata = await this.GetProjectMetadata(fullPath, projectFileReference.Aliases, _properties, cancellationToken).ConfigureAwait(false);
if (projectMetadata != null)
{
resolvedReferences.MetadataReferences.Add(projectMetadata);
continue;
}
}
// must load, so we really need loader
if (TryGetLoaderFromProjectPath(fullPath, reportMode, out loader))
{
// load the project
var projectId = await this.GetOrLoadProjectAsync(fullPath, loader, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false);
// If that other project already has a reference on us, this will cause a circularity.
// This check doesn't need to be in the "already loaded" path above, since in any circularity this path
// must be taken at least once.
if (ProjectAlreadyReferencesProject(loadedProjects, projectId, targetProject: thisProjectId))
{
// We'll try to make this metadata if we can
var projectMetadata = await this.GetProjectMetadata(fullPath, projectFileReference.Aliases, _properties, cancellationToken).ConfigureAwait(false);
if (projectMetadata != null)
{
resolvedReferences.MetadataReferences.Add(projectMetadata);
}
continue;
}
else
{
resolvedReferences.ProjectReferences.Add(new ProjectReference(projectId, projectFileReference.Aliases));
continue;
}
}
}
else
{
fullPath = projectFileReference.Path;
}
// cannot find metadata and project cannot be loaded, so leave a project reference to a non-existent project.
var id = loadedProjects.GetOrCreateProjectId(fullPath);
resolvedReferences.ProjectReferences.Add(new ProjectReference(id, projectFileReference.Aliases));
}
return resolvedReferences;
}
/// <summary>
/// Returns true if the project identified by <paramref name="fromProject"/> has a reference (even indirectly)
/// on the project identified by <paramref name="targetProject"/>.
/// </summary>
private bool ProjectAlreadyReferencesProject(LoadState loadedProjects, ProjectId fromProject, ProjectId targetProject)
{
ProjectInfo info;
return loadedProjects.TryGetValue(fromProject, out info) && info.ProjectReferences.Any(pr => pr.ProjectId == targetProject ||
ProjectAlreadyReferencesProject(loadedProjects, pr.ProjectId, targetProject));
}
/// <summary>
/// Gets a MetadataReference to a project's output assembly.
/// </summary>
private async Task<MetadataReference> GetProjectMetadata(string projectFilePath, ImmutableArray<string> aliases, IDictionary<string, string> globalProperties, CancellationToken cancellationToken)
{
// use loader service to determine output file for project if possible
string outputFilePath = null;
try
{
outputFilePath = await ProjectFileLoader.GetOutputFilePathAsync(projectFilePath, globalProperties, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
_workspace.OnWorkspaceFailed(new WorkspaceDiagnostic(WorkspaceDiagnosticKind.Failure, e.Message));
}
if (outputFilePath != null && File.Exists(outputFilePath))
{
if (Workspace.TestHookStandaloneProjectsDoNotHoldReferences)
{
var documentationService = _workspace.Services.GetService<IDocumentationProviderService>();
var docProvider = documentationService.GetDocumentationProvider(outputFilePath);
var metadata = AssemblyMetadata.CreateFromImage(File.ReadAllBytes(outputFilePath));
return metadata.GetReference(
documentation: docProvider,
aliases: aliases,
display: outputFilePath);
}
else
{
var metadataService = _workspace.Services.GetService<IMetadataService>();
return metadataService.GetReference(outputFilePath, new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases));
}
}
return null;
}
private string TryGetAbsolutePath(string path, ReportMode mode)
{
try
{
path = Path.GetFullPath(path);
}
catch (Exception)
{
ReportFailure(mode, string.Format(WorkspacesResources.Invalid_project_file_path_colon_0, path));
return null;
}
if (!File.Exists(path))
{
ReportFailure(
mode,
string.Format(WorkspacesResources.Project_file_not_found_colon_0, path),
msg => new FileNotFoundException(msg));
return null;
}
return path;
}
internal bool TryGetLoaderFromProjectPath(string projectFilePath, out IProjectFileLoader loader)
{
return TryGetLoaderFromProjectPath(projectFilePath, ReportMode.Ignore, out loader);
}
private bool TryGetLoaderFromProjectPath(string projectFilePath, ReportMode mode, out IProjectFileLoader loader)
{
using (_dataGuard.DisposableWait())
{
// otherwise try to figure it out from extension
var extension = Path.GetExtension(projectFilePath);
if (extension.Length > 0 && extension[0] == '.')
{
extension = extension.Substring(1);
}
string language;
if (_extensionToLanguageMap.TryGetValue(extension, out language))
{
if (_workspace.Services.SupportedLanguages.Contains(language))
{
loader = _workspace.Services.GetLanguageServices(language).GetService<IProjectFileLoader>();
}
else
{
loader = null;
this.ReportFailure(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language));
return false;
}
}
else
{
loader = ProjectFileLoader.GetLoaderForProjectFileExtension(_workspace, extension);
if (loader == null)
{
this.ReportFailure(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectFilePath, Path.GetExtension(projectFilePath)));
return false;
}
}
// since we have both C# and VB loaders in this same library, it no longer indicates whether we have full language support available.
if (loader != null)
{
language = loader.Language;
// check for command line parser existing... if not then error.
var commandLineParser = _workspace.Services.GetLanguageServices(language).GetService<ICommandLineParserService>();
if (commandLineParser == null)
{
loader = null;
this.ReportFailure(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language));
return false;
}
}
return loader != null;
}
}
private bool TryGetAbsoluteProjectPath(string path, string baseDirectory, ReportMode mode, out string absolutePath)
{
try
{
absolutePath = GetAbsolutePath(path, baseDirectory);
}
catch (Exception)
{
ReportFailure(mode, string.Format(WorkspacesResources.Invalid_project_file_path_colon_0, path));
absolutePath = null;
return false;
}
if (!File.Exists(absolutePath))
{
ReportFailure(
mode,
string.Format(WorkspacesResources.Project_file_not_found_colon_0, absolutePath),
msg => new FileNotFoundException(msg));
return false;
}
return true;
}
private static string GetAbsolutePath(string path, string baseDirectoryPath)
{
return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path);
}
private enum ReportMode
{
Throw,
Log,
Ignore
}
private void ReportFailure(ReportMode mode, string message, Func<string, Exception> createException = null)
{
switch (mode)
{
case ReportMode.Throw:
if (createException != null)
{
throw createException(message);
}
else
{
throw new InvalidOperationException(message);
}
case ReportMode.Log:
_workspace.OnWorkspaceFailed(new WorkspaceDiagnostic(WorkspaceDiagnosticKind.Failure, message));
break;
case ReportMode.Ignore:
default:
break;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Roslyn.Utilities;
using ShellInterop = Microsoft.VisualStudio.Shell.Interop;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
using VsThreading = Microsoft.VisualStudio.Threading;
using Document = Microsoft.CodeAnalysis.Document;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue
{
internal sealed class VsENCRebuildableProjectImpl
{
private readonly AbstractProject _vsProject;
// number of projects that are in the debug state:
private static int s_debugStateProjectCount;
// number of projects that are in the break state:
private static int s_breakStateProjectCount;
// projects that entered the break state:
private static readonly List<KeyValuePair<ProjectId, ProjectReadOnlyReason>> s_breakStateEnteredProjects = new List<KeyValuePair<ProjectId, ProjectReadOnlyReason>>();
// active statements of projects that entered the break state:
private static readonly List<VsActiveStatement> s_pendingActiveStatements = new List<VsActiveStatement>();
private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker;
internal static readonly TraceLog log = new TraceLog(2048, "EnC");
private static Solution s_breakStateEntrySolution;
private static EncDebuggingSessionInfo s_encDebuggingSessionInfo;
private readonly IEditAndContinueWorkspaceService _encService;
private readonly IActiveStatementTrackingService _trackingService;
private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider;
private readonly IDebugEncNotify _debugEncNotify;
private readonly INotificationService _notifications;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
#region Per Project State
private bool _changesApplied;
// maps VS Active Statement Id, which is unique within this project, to our id
private Dictionary<uint, ActiveStatementId> _activeStatementIds;
private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
private HashSet<uint> _activeMethods;
private List<VsExceptionRegion> _exceptionRegions;
private EmitBaseline _committedBaseline;
private EmitBaseline _pendingBaseline;
private Project _projectBeingEmitted;
private ImmutableArray<DocumentId> _documentsWithEmitError;
/// <summary>
/// Initialized when the project switches to debug state.
/// Null if the project has no output file or we can't read the MVID.
/// </summary>
private ModuleMetadata _metadata;
private ISymUnmanagedReader _pdbReader;
private IntPtr _pdbReaderObjAsStream;
#endregion
private bool IsDebuggable
{
get { return _metadata != null; }
}
internal VsENCRebuildableProjectImpl(AbstractProject project)
{
_vsProject = project;
_encService = _vsProject.Workspace.Services.GetService<IEditAndContinueWorkspaceService>();
_trackingService = _vsProject.Workspace.Services.GetService<IActiveStatementTrackingService>();
_notifications = _vsProject.Workspace.Services.GetService<INotificationService>();
_debugEncNotify = (IDebugEncNotify)project.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger));
var componentModel = (IComponentModel)project.ServiceProvider.GetService(typeof(SComponentModel));
_diagnosticProvider = componentModel.GetService<EditAndContinueDiagnosticUpdateSource>();
_editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
Debug.Assert(_encService != null);
Debug.Assert(_trackingService != null);
Debug.Assert(_diagnosticProvider != null);
Debug.Assert(_editorAdaptersFactoryService != null);
}
// called from an edit filter if an edit of a read-only buffer is attempted:
internal bool OnEdit(DocumentId documentId)
{
SessionReadOnlyReason sessionReason;
ProjectReadOnlyReason projectReason;
if (_encService.IsProjectReadOnly(documentId.ProjectId, out sessionReason, out projectReason))
{
OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason);
return true;
}
return false;
}
private void OnReadOnlyDocumentEditAttempt(
DocumentId documentId,
SessionReadOnlyReason sessionReason,
ProjectReadOnlyReason projectReason)
{
if (sessionReason == SessionReadOnlyReason.StoppedAtException)
{
_debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState();
return;
}
var visualStudioWorkspace = _vsProject.Workspace as VisualStudioWorkspaceImpl;
var hostProject = visualStudioWorkspace?.GetHostProject(documentId.ProjectId) as AbstractRoslynProject;
if (hostProject?.EditAndContinueImplOpt?._metadata != null)
{
_debugEncNotify.NotifyEncEditDisallowedByProject(hostProject.Hierarchy);
return;
}
// NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586).
string message;
if (sessionReason == SessionReadOnlyReason.Running)
{
message = "Changes are not allowed while code is running.";
}
else
{
Debug.Assert(sessionReason == SessionReadOnlyReason.None);
switch (projectReason)
{
case ProjectReadOnlyReason.MetadataNotAvailable:
message = "Changes are not allowed if the project wasn't built when debugging started.";
break;
case ProjectReadOnlyReason.NotLoaded:
message = "Changes are not allowed if the assembly has not been loaded.";
break;
default:
throw ExceptionUtilities.UnexpectedValue(projectReason);
}
}
_notifications.SendNotification(message, title: FeaturesResources.EditAndContinue, severity: NotificationSeverity.Error);
}
/// <summary>
/// Since we can't await asynchronous operations we need to wait for them to complete.
/// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to
/// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext
/// that doesn't pump messages. We need to make sure though that the async methods we wait for
/// don't dispatch to foreground thread, otherwise we would end up in a deadlock.
/// </summary>
private static VsThreading.SpecializedSyncContext NonReentrantContext
{
get
{
return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default);
}
}
public bool HasCustomMetadataEmitter()
{
return true;
}
/// <summary>
/// Invoked when the debugger transitions from Design mode to Run mode or Break mode.
/// </summary>
public int StartDebuggingPE()
{
try
{
log.Write("Enter Debug Mode: project '{0}'", _vsProject.DisplayName);
// EnC service is global (per solution), but the debugger calls this for each project.
// Avoid starting the debug session if it has already been started.
if (_encService.DebuggingSession == null)
{
Debug.Assert(s_debugStateProjectCount == 0);
Debug.Assert(s_breakStateProjectCount == 0);
Debug.Assert(s_breakStateEnteredProjects.Count == 0);
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run);
_encService.StartDebuggingSession(_vsProject.Workspace.CurrentSolution);
s_encDebuggingSessionInfo = new EncDebuggingSessionInfo();
s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_encService, _editorAdaptersFactoryService, _vsProject);
}
string outputPath = _vsProject.TryGetObjOutputPath();
// The project doesn't produce a debuggable binary or we can't read it.
// Continue on since the debugger ignores HResults and we need to handle subsequent calls.
if (outputPath != null)
{
try
{
InjectFault_MvidRead();
_metadata = ModuleMetadata.CreateFromStream(new FileStream(outputPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete));
_metadata.GetModuleVersionId();
}
catch (FileNotFoundException)
{
// If the project isn't referenced by the project being debugged it might not be built.
// In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state.
log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _vsProject.DisplayName, outputPath);
_metadata = null;
}
catch (Exception e)
{
log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _vsProject.DisplayName, outputPath, e.Message);
_metadata = null;
var descriptor = new DiagnosticDescriptor("Metadata", "Metadata", ServicesVSResources.ErrorWhileReading, DiagnosticCategory.EditAndContinue, DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue);
_diagnosticProvider.ReportDiagnostics(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId, _vsProject.Id, _encService.DebuggingSession.InitialSolution,
new[]
{
Diagnostic.Create(descriptor, Location.None, outputPath, e.Message)
});
}
}
else
{
log.Write("StartDebuggingPE: project has no output path '{0}'", _vsProject.DisplayName);
_metadata = null;
}
if (_metadata != null)
{
// The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID.
// However a project that's initially not loaded (but it might be in future) enters
// both the debug and break states.
s_debugStateProjectCount++;
}
_activeMethods = new HashSet<uint>();
_exceptionRegions = new List<VsExceptionRegion>();
_activeStatementIds = new Dictionary<uint, ActiveStatementId>();
// The HResult is ignored by the debugger.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
public int StopDebuggingPE()
{
try
{
log.Write("Exit Debug Mode: project '{0}'", _vsProject.DisplayName);
Debug.Assert(s_breakStateEnteredProjects.Count == 0);
// Clear the solution stored while projects were entering break mode.
// It should be cleared as soon as all tracked projects enter the break mode
// but if the entering break mode fails for some projects we should avoid leaking the solution.
Debug.Assert(s_breakStateEntrySolution == null);
s_breakStateEntrySolution = null;
// EnC service is global (per solution), but the debugger calls this for each project.
// Avoid ending the debug session if it has already been ended.
if (_encService.DebuggingSession != null)
{
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design);
_encService.EndDebuggingSession();
LogEncSession();
s_encDebuggingSessionInfo = null;
s_readOnlyDocumentTracker.Dispose();
s_readOnlyDocumentTracker = null;
}
if (_metadata != null)
{
_metadata.Dispose();
_metadata = null;
s_debugStateProjectCount--;
}
else
{
// an error might have been reported:
_diagnosticProvider.ClearDiagnostics(_encService.DebuggingSession, _vsProject.Workspace, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId, _vsProject.Id, documentId: null);
}
_activeMethods = null;
_exceptionRegions = null;
_committedBaseline = null;
_activeStatementIds = null;
Debug.Assert((_pdbReaderObjAsStream == IntPtr.Zero) || (_pdbReader == null));
if (_pdbReader != null)
{
Marshal.ReleaseComObject(_pdbReader);
_pdbReader = null;
}
// The HResult is ignored by the debugger.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static void LogEncSession()
{
var sessionId = DebugLogMessage.GetNextId();
Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo));
foreach (var editSession in s_encDebuggingSessionInfo.EditSessions)
{
var editSessionId = DebugLogMessage.GetNextId();
Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession));
if (editSession.EmitDeltaErrorIds != null)
{
foreach (var error in editSession.EmitDeltaErrorIds)
{
Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error));
}
}
foreach (var rudeEdit in editSession.RudeEdits)
{
Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits));
}
}
}
/// <summary>
/// Get MVID and file name of the project's output file.
/// </summary>
/// <remarks>
/// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project.
/// The path seems to be unused.
///
/// The output file path might be different from the path of the module loaded into the process.
/// For example, the binary produced by the C# compiler is stores in obj directory,
/// and then copied to bin directory from which it is loaded to the debuggee.
///
/// The binary produced by the compiler can also be rewritten by post-processing tools.
/// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session
/// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though.
/// </remarks>
public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName)
{
Debug.Assert(_encService.DebuggingSession != null);
if (_metadata == null)
{
return VSConstants.E_FAIL;
}
if (pMVID != null && pMVID.Length != 0)
{
pMVID[0] = _metadata.GetModuleVersionId();
}
if (pbstrPEName != null && pbstrPEName.Length != 0)
{
var outputPath = _vsProject.TryGetObjOutputPath();
Debug.Assert(outputPath != null);
pbstrPEName[0] = Path.GetFileName(outputPath);
}
return VSConstants.S_OK;
}
/// <summary>
/// Called by the debugger when entering a Break state.
/// </summary>
/// <param name="encBreakReason">Reason for transition to Break state.</param>
/// <param name="pActiveStatements">Statements active when the debuggee is stopped.</param>
/// <param name="cActiveStatements">Length of <paramref name="pActiveStatements"/>.</param>
public int EnterBreakStateOnPE(Interop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements)
{
try
{
using (NonReentrantContext)
{
log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _vsProject.DisplayName, pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : "");
Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0));
Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount);
Debug.Assert(s_breakStateProjectCount > 0 || _exceptionRegions.Count == 0);
Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count);
Debug.Assert(IsDebuggable);
if (s_breakStateEntrySolution == null)
{
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break);
s_breakStateEntrySolution = _vsProject.Workspace.CurrentSolution;
// TODO: This is a workaround for a debugger bug in which not all projects exit the break state.
// Reset the project count.
s_breakStateProjectCount = 0;
}
ProjectReadOnlyReason state;
if (pActiveStatements != null)
{
AddActiveStatements(s_breakStateEntrySolution, pActiveStatements);
state = ProjectReadOnlyReason.None;
}
else
{
// unfortunately the debugger doesn't provide details:
state = ProjectReadOnlyReason.NotLoaded;
}
// If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding
// to the project in the debuggee. We won't include such projects in the edit session.
s_breakStateEnteredProjects.Add(KeyValuePair.Create(_vsProject.Id, state));
s_breakStateProjectCount++;
// EnC service is global, but the debugger calls this for each project.
// Avoid starting the edit session until all projects enter break state.
if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount)
{
Debug.Assert(_encService.EditSession == null);
Debug.Assert(s_pendingActiveStatements.TrueForAll(s => s.Owner._activeStatementIds.Count == 0));
var byDocument = new Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>>();
// note: fills in activeStatementIds of projects that own the active statements:
GroupActiveStatements(s_pendingActiveStatements, byDocument);
// When stopped at exception: All documents are read-only, but the files might be changed outside of VS.
// So we start an edit session as usual and report a rude edit for all changes we see.
bool stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION;
var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects);
_encService.StartEditSession(s_breakStateEntrySolution, byDocument, projectStates, stoppedAtException);
_trackingService.StartTracking(_encService.EditSession);
s_readOnlyDocumentTracker.UpdateWorkspaceDocuments();
// When tracking is started the tagger is notified and the active statements are highlighted.
// Add the handler that notifies the debugger *after* that initial tagger notification,
// so that it's not triggered unless an actual change in leaf AS occurs.
_trackingService.TrackingSpansChanged += TrackingSpansChanged;
}
}
// The debugger ignores the result.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
finally
{
// TODO: This is a workaround for a debugger bug.
// Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception.
if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount)
{
// we don't need these anymore:
s_pendingActiveStatements.Clear();
s_breakStateEnteredProjects.Clear();
s_breakStateEntrySolution = null;
}
}
}
private void TrackingSpansChanged(bool leafChanged)
{
//log.Write("Tracking spans changed: {0}", leafChanged);
//if (leafChanged)
//{
// // fire and forget:
// Application.Current.Dispatcher.InvokeAsync(() =>
// {
// log.Write("Notifying debugger of active statement change.");
// var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger));
// debugNotify.NotifyEncUpdateCurrentStatement();
// });
//}
}
private struct VsActiveStatement
{
public readonly DocumentId DocumentId;
public readonly uint StatementId;
public readonly ActiveStatementSpan Span;
public readonly VsENCRebuildableProjectImpl Owner;
public VsActiveStatement(VsENCRebuildableProjectImpl owner, uint statementId, DocumentId documentId, ActiveStatementSpan span)
{
this.Owner = owner;
this.StatementId = statementId;
this.DocumentId = documentId;
this.Span = span;
}
}
private struct VsExceptionRegion
{
public readonly uint ActiveStatementId;
public readonly int Ordinal;
public readonly uint MethodToken;
public readonly LinePositionSpan Span;
public VsExceptionRegion(uint activeStatementId, int ordinal, uint methodToken, LinePositionSpan span)
{
this.ActiveStatementId = activeStatementId;
this.Span = span;
this.MethodToken = methodToken;
this.Ordinal = ordinal;
}
}
// See InternalApis\vsl\inc\encbuild.idl
private const int TEXT_POSITION_ACTIVE_STATEMENT = 1;
private void AddActiveStatements(Solution solution, ShellInterop.ENC_ACTIVE_STATEMENT[] vsActiveStatements)
{
Debug.Assert(_activeMethods.Count == 0);
Debug.Assert(_exceptionRegions.Count == 0);
foreach (var vsActiveStatement in vsActiveStatements)
{
log.DebugWrite("+AS[{0}]: {1} {2} {3} {4} '{5}'",
vsActiveStatement.id,
vsActiveStatement.tsPosition.iStartLine,
vsActiveStatement.tsPosition.iStartIndex,
vsActiveStatement.tsPosition.iEndLine,
vsActiveStatement.tsPosition.iEndIndex,
vsActiveStatement.filename);
// TODO (tomat):
// Active statement is in user hidden code. The only information that we have from the debugger
// is the method token. We don't need to track the statement (it's not in user code anyways),
// but we should probably track the list of such methods in order to preserve their local variables.
// Not sure what's exactly the scenario here, perhaps modifying async method/iterator?
// Dev12 just ignores these.
if (vsActiveStatement.posType != TEXT_POSITION_ACTIVE_STATEMENT)
{
continue;
}
var flags = (ActiveStatementFlags)vsActiveStatement.ASINFO;
// Finds a document id in the solution with the specified file path.
DocumentId documentId = solution.GetDocumentIdsWithFilePath(vsActiveStatement.filename)
.Where(dId => dId.ProjectId == _vsProject.Id).SingleOrDefault();
if (documentId != null)
{
var document = solution.GetDocument(documentId);
Debug.Assert(document != null);
SourceText source = document.GetTextAsync(default(CancellationToken)).Result;
LinePositionSpan lineSpan = vsActiveStatement.tsPosition.ToLinePositionSpan();
// If the PDB is out of sync with the source we might get bad spans.
var sourceLines = source.Lines;
if (lineSpan.End.Line >= sourceLines.Count || sourceLines.GetPosition(lineSpan.End) > sourceLines[sourceLines.Count - 1].EndIncludingLineBreak)
{
log.Write("AS out of bounds (line count is {0})", source.Lines.Count);
continue;
}
SyntaxNode syntaxRoot = document.GetSyntaxRootAsync(default(CancellationToken)).Result;
var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>();
s_pendingActiveStatements.Add(new VsActiveStatement(
this,
vsActiveStatement.id,
document.Id,
new ActiveStatementSpan(flags, lineSpan)));
bool isLeaf = (flags & ActiveStatementFlags.LeafFrame) != 0;
var ehRegions = analyzer.GetExceptionRegions(source, syntaxRoot, lineSpan, isLeaf);
for (int i = 0; i < ehRegions.Length; i++)
{
_exceptionRegions.Add(new VsExceptionRegion(
vsActiveStatement.id,
i,
vsActiveStatement.methodToken,
ehRegions[i]));
}
}
_activeMethods.Add(vsActiveStatement.methodToken);
}
}
private static void GroupActiveStatements(
IEnumerable<VsActiveStatement> activeStatements,
Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>> byDocument)
{
var spans = new List<ActiveStatementSpan>();
foreach (var grouping in activeStatements.GroupBy(s => s.DocumentId))
{
var documentId = grouping.Key;
foreach (var activeStatement in grouping.OrderBy(s => s.Span.Span.Start))
{
int ordinal = spans.Count;
// register vsid with the project that owns the active statement:
activeStatement.Owner._activeStatementIds.Add(activeStatement.StatementId, new ActiveStatementId(documentId, ordinal));
spans.Add(activeStatement.Span);
}
byDocument.Add(documentId, spans.AsImmutable());
spans.Clear();
}
}
/// <summary>
/// Returns the number of exception regions around current active statements.
/// This is called when the project is entering a break right after
/// <see cref="EnterBreakStateOnPE"/> and prior to <see cref="GetExceptionSpans"/>.
/// </summary>
/// <remarks>
/// Called by EnC manager.
/// </remarks>
public int GetExceptionSpanCount(out uint pcExceptionSpan)
{
pcExceptionSpan = (uint)_exceptionRegions.Count;
return VSConstants.S_OK;
}
/// <summary>
/// Returns information about exception handlers in the source.
/// </summary>
/// <remarks>
/// Called by EnC manager.
/// </remarks>
public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched)
{
Debug.Assert(celt == rgelt.Length);
Debug.Assert(celt == _exceptionRegions.Count);
for (int i = 0; i < _exceptionRegions.Count; i++)
{
rgelt[i] = new ShellInterop.ENC_EXCEPTION_SPAN()
{
id = (uint)i,
methodToken = _exceptionRegions[i].MethodToken,
tsPosition = _exceptionRegions[i].Span.ToVsTextSpan()
};
}
pceltFetched = celt;
return VSConstants.S_OK;
}
/// <summary>
/// Called by the debugger whenever it needs to determine a position of an active statement.
/// E.g. the user clicks on a frame in a call stack.
/// </summary>
/// <remarks>
/// Called when applying change, when setting current IP, a notification is received from
/// <see cref="IDebugEncNotify.NotifyEncUpdateCurrentStatement"/>, etc.
/// In addition this API is exposed on IDebugENC2 COM interface so it can be used anytime by other components.
/// </remarks>
public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(IsDebuggable);
var session = _encService.EditSession;
var ids = _activeStatementIds;
// Can be called anytime, even outside of an edit/debug session.
// We might not have an active statement available if PDB got out of sync with the source.
ActiveStatementId id;
if (session == null || ids == null || !ids.TryGetValue(vsId, out id))
{
log.Write("GetCurrentActiveStatementPosition failed for AS {0}.", vsId);
return VSConstants.E_FAIL;
}
Document document = _vsProject.Workspace.CurrentSolution.GetDocument(id.DocumentId);
SourceText text = document.GetTextAsync(default(CancellationToken)).Result;
// Try to get spans from the tracking service first.
// We might get an imprecise result if the document analysis hasn't been finished yet and
// the active statement has structurally changed, but that's ok. The user won't see an updated tag
// for the statement until the analysis finishes anyways.
TextSpan span;
LinePositionSpan lineSpan;
if (_trackingService.TryGetSpan(id, text, out span) && span.Length > 0)
{
lineSpan = text.Lines.GetLinePositionSpan(span);
}
else
{
var activeSpans = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)).ActiveStatements;
if (activeSpans.IsDefault)
{
// The document has syntax errors and the tracking span is gone.
log.Write("Position not available for AS {0} due to syntax errors", vsId);
return VSConstants.E_FAIL;
}
lineSpan = activeSpans[id.Ordinal];
}
ptsNewPosition[0] = lineSpan.ToVsTextSpan();
log.DebugWrite("AS position: {0} {1} {2}", vsId, lineSpan,
session.BaseActiveStatements[id.DocumentId][id.Ordinal].Flags);
return VSConstants.S_OK;
}
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Returns the state of the changes made to the source.
/// The EnC manager calls this to determine whether there are any changes to the source
/// and if so whether there are any rude edits.
/// </summary>
public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1);
// GetENCBuildState is called outside of edit session (at least) in following cases:
// 1) when the debugger is determining whether a source file checksum matches the one in PDB.
// 2) when the debugger is setting the next statement and a change is pending
// See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange):
//
// pENC2->ExitBreakState();
// >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true);
// pENC2->EnterBreakState(m_pSession, GetEncBreakReason());
//
// The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur.
if (_changesApplied || _encService.EditSession == null)
{
_lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
}
else
{
// Fetch the latest snapshot of the project and get an analysis summary for any changes
// made since the break mode was entered.
var currentProject = _vsProject.Workspace.CurrentSolution.GetProject(_vsProject.Id);
if (currentProject == null)
{
// If the project has yet to be loaded into the solution (which may be the case,
// since they are loaded on-demand), then it stands to reason that it has not yet
// been modified.
// TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary.
_lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
log.Write($"Project '{_vsProject.DisplayName}' has not yet been loaded into the solution");
}
else
{
_projectBeingEmitted = currentProject;
_lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted);
}
_encService.EditSession.LogBuildState(_lastEditSessionSummary);
}
switch (_lastEditSessionSummary)
{
case ProjectAnalysisSummary.NoChanges:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED;
break;
case ProjectAnalysisSummary.CompilationErrors:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS;
break;
case ProjectAnalysisSummary.RudeEdits:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS;
break;
case ProjectAnalysisSummary.ValidChanges:
case ProjectAnalysisSummary.ValidInsignificantChanges:
// The debugger doesn't distinguish between these two.
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY;
break;
default:
throw ExceptionUtilities.Unreachable;
}
log.Write("EnC state of '{0}' queried: {1}{2}",
_vsProject.DisplayName,
pENCBuildState[0],
_encService.EditSession != null ? "" : " (no session)");
return VSConstants.S_OK;
}
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project)
{
if (!IsDebuggable)
{
return ProjectAnalysisSummary.NoChanges;
}
var cancellationToken = default(CancellationToken);
return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result;
}
public int ExitBreakStateOnPE()
{
try
{
using (NonReentrantContext)
{
// The debugger calls Exit without previously calling Enter if the project's MVID isn't available.
if (!IsDebuggable)
{
return VSConstants.S_OK;
}
log.Write("Exit Break Mode: project '{0}'", _vsProject.DisplayName);
// EnC service is global, but the debugger calls this for each project.
// Avoid ending the edit session if it has already been ended.
if (_encService.EditSession != null)
{
Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount);
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run);
_encService.EditSession.LogEditSession(s_encDebuggingSessionInfo);
_encService.EndEditSession();
_trackingService.EndTracking();
s_readOnlyDocumentTracker.UpdateWorkspaceDocuments();
_trackingService.TrackingSpansChanged -= TrackingSpansChanged;
}
_exceptionRegions.Clear();
_activeMethods.Clear();
_activeStatementIds.Clear();
s_breakStateProjectCount--;
Debug.Assert(s_breakStateProjectCount >= 0);
_changesApplied = false;
_diagnosticProvider.ClearDiagnostics(_encService.DebuggingSession, _vsProject.Workspace, EditAndContinueDiagnosticUpdateSource.EmitErrorId, _vsProject.Id, _documentsWithEmitError);
_documentsWithEmitError = default(ImmutableArray<DocumentId>);
}
// HResult ignored by the debugger
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
public unsafe int BuildForEnc(object pUpdatePE)
{
try
{
log.Write("Applying changes to {0}", _vsProject.DisplayName);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
// Non-debuggable project has no changes.
Debug.Assert(IsDebuggable);
if (_changesApplied)
{
log.Write("Changes already applied to {0}, can't apply again", _vsProject.DisplayName);
throw ExceptionUtilities.Unreachable;
}
// The debugger always calls GetENCBuildState right before BuildForEnc.
Debug.Assert(_projectBeingEmitted != null);
Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted));
// The debugger should have called GetENCBuildState before calling BuildForEnc.
// Unfortunately, there is no way how to tell the debugger that the changes were not significant,
// so we'll to emit an empty delta. See bug 839558.
Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges ||
_lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges);
var updater = (IDebugUpdateInMemoryPE2)pUpdatePE;
if (_committedBaseline == null)
{
var hr = MarshalPdbReader(updater, out _pdbReaderObjAsStream);
if (hr != VSConstants.S_OK)
{
return hr;
}
_committedBaseline = EmitBaseline.CreateInitialBaseline(_metadata, GetBaselineEncDebugInfo);
}
// ISymUnmanagedReader can only be accessed from an MTA thread,
// so dispatch it to one of thread pool threads, which are MTA.
var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default);
Deltas delta;
using (NonReentrantContext)
{
delta = emitTask.Result;
}
// Clear diagnostics, in case the project was built before and failed due to errors.
_diagnosticProvider.ClearDiagnostics(_encService.DebuggingSession, _vsProject.Workspace, EditAndContinueDiagnosticUpdateSource.EmitErrorId, _vsProject.Id, _documentsWithEmitError);
if (!delta.EmitResult.Success)
{
var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error);
_documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(
_encService.DebuggingSession,
EditAndContinueDiagnosticUpdateSource.EmitErrorId,
_vsProject.Id,
_projectBeingEmitted.Solution,
errors);
_encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id));
return VSConstants.E_FAIL;
}
_documentsWithEmitError = default(ImmutableArray<DocumentId>);
SetFileUpdates(updater, delta.LineEdits);
updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length);
updater.SetDeltaPdb(new ComStreamWrapper(delta.Pdb.Stream));
updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length);
updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length);
_pendingBaseline = delta.EmitResult.Baseline;
#if DEBUG
fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0])
{
var reader = new System.Reflection.Metadata.MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length);
var moduleDef = reader.GetModuleDefinition();
log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}",
moduleDef.Generation,
reader.GetGuid(moduleDef.Mvid),
reader.GetGuid(moduleDef.BaseGenerationId),
reader.GetGuid(moduleDef.GenerationId));
}
#endif
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private unsafe void SetFileUpdates(
IDebugUpdateInMemoryPE2 updater,
List<KeyValuePair<DocumentId, ImmutableArray<LineChange>>> edits)
{
int totalEditCount = edits.Sum(e => e.Value.Length);
if (totalEditCount == 0)
{
return;
}
var lineUpdates = new LINEUPDATE[totalEditCount];
fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates)
{
int index = 0;
var fileUpdates = new FILEUPDATE[edits.Count];
for (int f = 0; f < fileUpdates.Length; f++)
{
var documentId = edits[f].Key;
var deltas = edits[f].Value;
fileUpdates[f].FileName = _vsProject.GetDocumentOrAdditionalDocument(documentId).FilePath;
fileUpdates[f].LineUpdateCount = (uint)deltas.Length;
fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index);
for (int l = 0; l < deltas.Length; l++)
{
lineUpdates[index + l].Line = (uint)deltas[l].OldLine;
lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine;
}
index += deltas.Length;
}
// The updater makes a copy of all data, we can release the buffer after the call.
updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length);
}
}
private Deltas EmitProjectDelta()
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, _committedBaseline, default(CancellationToken));
return emitTask.Result;
}
private EditAndContinueMethodDebugInformation GetBaselineEncDebugInfo(MethodDefinitionHandle methodHandle)
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
if (_pdbReader == null)
{
// Unmarshal the symbol reader (being marshalled cross thread from STA -> MTA).
Debug.Assert(_pdbReaderObjAsStream != IntPtr.Zero);
object pdbReaderObjMta;
int hr = NativeMethods.GetObjectForStream(_pdbReaderObjAsStream, out pdbReaderObjMta);
_pdbReaderObjAsStream = IntPtr.Zero;
if (hr != VSConstants.S_OK)
{
log.Write("Error unmarshaling object from stream.");
return default(EditAndContinueMethodDebugInformation);
}
_pdbReader = (ISymUnmanagedReader)pdbReaderObjMta;
}
int methodToken = MetadataTokens.GetToken(methodHandle);
byte[] debugInfo = _pdbReader.GetCustomDebugInfoBytes(methodToken, methodVersion: 1);
if (debugInfo != null)
{
try
{
var localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap);
var lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap);
return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap);
}
catch (Exception e) when (e is InvalidOperationException || e is InvalidDataException)
{
log.Write($"Error reading CDI of method 0x{methodToken:X8}: {e.Message}");
}
}
return default(EditAndContinueMethodDebugInformation);
}
public int EncApplySucceeded(int hrApplyResult)
{
try
{
log.Write("Change applied to {0}", _vsProject.DisplayName);
Debug.Assert(IsDebuggable);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
Debug.Assert(_pendingBaseline != null);
// Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges.
_changesApplied = true;
_committedBaseline = _pendingBaseline;
_pendingBaseline = null;
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Called when changes are being applied.
/// </summary>
/// <param name="exceptionRegionId">
/// The value of <see cref="ShellInterop.ENC_EXCEPTION_SPAN.id"/>.
/// Set by <see cref="GetExceptionSpans(uint, ShellInterop.ENC_EXCEPTION_SPAN[], ref uint)"/> to the index into <see cref="_exceptionRegions"/>.
/// </param>
/// <param name="ptsNewPosition">Output value holder.</param>
public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(IsDebuggable);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
Debug.Assert(ptsNewPosition.Length == 1);
var exceptionRegion = _exceptionRegions[(int)exceptionRegionId];
var session = _encService.EditSession;
var asid = _activeStatementIds[exceptionRegion.ActiveStatementId];
var document = _projectBeingEmitted.GetDocument(asid.DocumentId);
var analysis = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken));
var regions = analysis.ExceptionRegions;
// the method shouldn't be called in presence of errors:
Debug.Assert(!analysis.HasChangesAndErrors);
Debug.Assert(!regions.IsDefault);
// Absence of rude edits guarantees that the exception regions around AS haven't semantically changed.
// Only their spans might have changed.
ptsNewPosition[0] = regions[asid.Ordinal][exceptionRegion.Ordinal].ToVsTextSpan();
}
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static int MarshalPdbReader(IDebugUpdateInMemoryPE2 updater, out IntPtr pdbReaderPointer)
{
// ISymUnmanagedReader can only be accessed from an MTA thread, however, we need
// fetch the IUnknown instance (call IENCSymbolReaderProvider.GetSymbolReader) here
// in the STA. To further complicate things, we need to return synchronously from
// this method. Waiting for the MTA thread to complete so we can return synchronously
// blocks the STA thread, so we need to make sure the CLR doesn't try to marshal
// ISymUnmanagedReader calls made in an MTA back to the STA for execution (if this
// happens we'll be deadlocked). We'll use CoMarshalInterThreadInterfaceInStream to
// achieve this. First, we'll marshal the object in a Stream and pass a Stream pointer
// over to the MTA. In the MTA, we'll get the Stream from the pointer and unmarshal
// the object. The reader object was originally created on an MTA thread, and the
// instance we retrieved in the STA was a proxy. When we unmarshal the Stream in the
// MTA, it "unwraps" the proxy, allowing us to directly call the implementation.
// Another way to achieve this would be for the symbol reader to implement IAgileObject,
// but the symbol reader we use today does not. If that changes, we should consider
// removing this marshal/unmarshal code.
IENCDebugInfo debugInfo;
updater.GetENCDebugInfo(out debugInfo);
var symbolReaderProvider = (IENCSymbolReaderProvider)debugInfo;
object pdbReaderObjSta;
symbolReaderProvider.GetSymbolReader(out pdbReaderObjSta);
int hr = NativeMethods.GetStreamForObject(pdbReaderObjSta, out pdbReaderPointer);
Marshal.ReleaseComObject(pdbReaderObjSta);
return hr;
}
#region Testing
#if DEBUG
// Fault injection:
// If set we'll fail to read MVID of specified projects to test error reporting.
internal static ImmutableArray<string> InjectMvidReadingFailure;
private void InjectFault_MvidRead()
{
if (!InjectMvidReadingFailure.IsDefault && InjectMvidReadingFailure.Contains(_vsProject.DisplayName))
{
throw new IOException("Fault injection");
}
}
#else
[Conditional("DEBUG")]
private void InjectFault_MvidRead()
{
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
internal sealed partial class RenameTrackingTaggerProvider
{
internal enum TriggerIdentifierKind
{
NotRenamable,
RenamableDeclaration,
RenamableReference,
}
/// <summary>
/// Determines whether the original token was a renameable identifier on a background thread
/// </summary>
private class TrackingSession : ForegroundThreadAffinitizedObject
{
private static readonly Task<TriggerIdentifierKind> s_notRenamableTask = Task.FromResult(TriggerIdentifierKind.NotRenamable);
private readonly Task<TriggerIdentifierKind> _isRenamableIdentifierTask;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly CancellationToken _cancellationToken;
private readonly IAsynchronousOperationListener _asyncListener;
private Task<bool> _newIdentifierBindsTask = SpecializedTasks.False;
private readonly string _originalName;
public string OriginalName { get { return _originalName; } }
private readonly ITrackingSpan _trackingSpan;
public ITrackingSpan TrackingSpan { get { return _trackingSpan; } }
private bool _forceRenameOverloads;
public bool ForceRenameOverloads { get { return _forceRenameOverloads; } }
public TrackingSession(StateMachine stateMachine, SnapshotSpan snapshotSpan, IAsynchronousOperationListener asyncListener)
{
AssertIsForeground();
_asyncListener = asyncListener;
_trackingSpan = snapshotSpan.Snapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeInclusive);
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
if (snapshotSpan.Length > 0)
{
// If the snapshotSpan is nonempty, then the session began with a change that
// was touching a word. Asynchronously determine whether that word was a
// renameable identifier. If it is, alert the state machine so it can trigger
// tagging.
_originalName = snapshotSpan.GetText();
_isRenamableIdentifierTask = Task.Factory.SafeStartNewFromAsync(
() => DetermineIfRenamableIdentifierAsync(snapshotSpan, initialCheck: true),
_cancellationToken,
TaskScheduler.Default);
var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateTrackingSessionAfterIsRenamableIdentifierTask");
_isRenamableIdentifierTask.SafeContinueWith(
t => stateMachine.UpdateTrackingSessionIfRenamable(),
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken);
QueueUpdateToStateMachine(stateMachine, _isRenamableIdentifierTask);
}
else
{
// If the snapshotSpan is empty, that means text was added in a location that is
// not touching an existing word, which happens a fair amount when writing new
// code. In this case we already know that the user is not renaming an
// identifier.
_isRenamableIdentifierTask = s_notRenamableTask;
}
}
private void QueueUpdateToStateMachine(StateMachine stateMachine, Task task)
{
var asyncToken = _asyncListener.BeginAsyncOperation($"{GetType().Name}.{nameof(QueueUpdateToStateMachine)}");
task.SafeContinueWith(t =>
{
AssertIsForeground();
if (_isRenamableIdentifierTask.Result != TriggerIdentifierKind.NotRenamable)
{
stateMachine.OnTrackingSessionUpdated(this);
}
},
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken);
}
internal void CheckNewIdentifier(StateMachine stateMachine, ITextSnapshot snapshot)
{
AssertIsForeground();
_newIdentifierBindsTask = _isRenamableIdentifierTask.SafeContinueWithFromAsync(
async t => t.Result != TriggerIdentifierKind.NotRenamable &&
TriggerIdentifierKind.RenamableReference ==
await DetermineIfRenamableIdentifierAsync(
TrackingSpan.GetSpan(snapshot),
initialCheck: false).ConfigureAwait(false),
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.Default);
QueueUpdateToStateMachine(stateMachine, _newIdentifierBindsTask);
}
internal bool IsDefinitelyRenamableIdentifier()
{
// This needs to be able to run on a background thread for the CodeFix
return IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult: false, cancellationToken: CancellationToken.None);
}
public void Cancel()
{
AssertIsForeground();
_cancellationTokenSource.Cancel();
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableIdentifierAsync(SnapshotSpan snapshotSpan, bool initialCheck)
{
AssertIsBackground();
var document = snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var syntaxTree = await document.GetSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false);
var token = syntaxTree.GetTouchingWord(snapshotSpan.Start.Position, syntaxFactsService, _cancellationToken);
// The OriginalName is determined with a simple textual check, so for a
// statement such as "Dim [x = 1" the textual check will return a name of "[x".
// The token found for "[x" is an identifier token, but only due to error
// recovery (the "[x" is actually in the trailing trivia). If the OriginalName
// found through the textual check has a different length than the span of the
// touching word, then we cannot perform a rename.
if (initialCheck && token.Span.Length != this.OriginalName.Length)
{
return TriggerIdentifierKind.NotRenamable;
}
var languageHeuristicsService = document.Project.LanguageServices.GetService<IRenameTrackingLanguageHeuristicsService>();
if (syntaxFactsService.IsIdentifier(token) && languageHeuristicsService.IsIdentifierValidForRenameTracking(token.Text))
{
var semanticModel = await document.GetSemanticModelForNodeAsync(token.Parent, _cancellationToken).ConfigureAwait(false);
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var renameSymbolInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, token, _cancellationToken);
if (!renameSymbolInfo.HasSymbols)
{
return TriggerIdentifierKind.NotRenamable;
}
if (renameSymbolInfo.IsMemberGroup)
{
// This is a reference from a nameof expression. Allow the rename but set the RenameOverloads option
_forceRenameOverloads = true;
return await DetermineIfRenamableSymbolsAsync(renameSymbolInfo.Symbols, document, token).ConfigureAwait(false);
}
else
{
return await DetermineIfRenamableSymbolAsync(renameSymbolInfo.Symbols.Single(), document, token).ConfigureAwait(false);
}
}
}
return TriggerIdentifierKind.NotRenamable;
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableSymbolsAsync(IEnumerable<ISymbol> symbols, Document document, SyntaxToken token)
{
foreach (var symbol in symbols)
{
// Get the source symbol if possible
var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol;
if (!sourceSymbol.Locations.All(loc => loc.IsInSource))
{
return TriggerIdentifierKind.NotRenamable;
}
}
return TriggerIdentifierKind.RenamableReference;
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableSymbolAsync(ISymbol symbol, Document document, SyntaxToken token)
{
// Get the source symbol if possible
var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol;
if (!sourceSymbol.Locations.All(loc => loc.IsInSource))
{
return TriggerIdentifierKind.NotRenamable;
}
return sourceSymbol.Locations.Any(loc => loc == token.GetLocation())
? TriggerIdentifierKind.RenamableDeclaration
: TriggerIdentifierKind.RenamableReference;
}
internal bool CanInvokeRename(
ISyntaxFactsService syntaxFactsService,
IRenameTrackingLanguageHeuristicsService languageHeuristicsService,
bool isSmartTagCheck,
bool waitForResult,
CancellationToken cancellationToken)
{
if (IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult, cancellationToken))
{
var isRenamingDeclaration = _isRenamableIdentifierTask.Result == TriggerIdentifierKind.RenamableDeclaration;
var newName = TrackingSpan.GetText(TrackingSpan.TextBuffer.CurrentSnapshot);
var comparison = isRenamingDeclaration || syntaxFactsService.IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
if (!string.Equals(OriginalName, newName, comparison) &&
syntaxFactsService.IsValidIdentifier(newName) &&
languageHeuristicsService.IsIdentifierValidForRenameTracking(newName))
{
// At this point, we want to allow renaming if the user invoked Ctrl+. explicitly, but we
// want to avoid showing a smart tag if we're renaming a reference that binds to an existing
// symbol.
if (!isSmartTagCheck || isRenamingDeclaration || !NewIdentifierDefinitelyBindsToReference())
{
return true;
}
}
}
return false;
}
private bool NewIdentifierDefinitelyBindsToReference()
{
return _newIdentifierBindsTask.Status == TaskStatus.RanToCompletion && _newIdentifierBindsTask.Result;
}
}
}
}
| |
namespace WindowsUtilities
{
public enum WindowsMessages: int
{
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUERYOPEN = 0x0013,
WM_ENDSESSION = 0x0016,
WM_QUIT = 0x0012,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_DELETEITEM = 0x002D,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_SYNCPAINT = 0x0088,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_NCXBUTTONDBLCLK = 0x00AD,
WM_INPUT = 0x00FF,
WM_KEYFIRST = 0x0100,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_UNICHAR = 0x0109,
WM_KEYLAST_NT501 = 0x0109,
UNICODE_NOCHAR = 0xFFFF,
WM_KEYLAST_PRE501 = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_MENURBUTTONUP = 0x0122,
WM_MENUDRAG = 0x0123,
WM_MENUGETOBJECT = 0x0124,
WM_UNINITMENUPOPUP = 0x0125,
WM_MENUCOMMAND = 0x0126,
WM_CHANGEUISTATE = 0x0127,
WM_UPDATEUISTATE = 0x0128,
WM_QUERYUISTATE = 0x0129,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEFIRST = 0x0200,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_MOUSEWHEEL = 0x020A,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_MOUSELAST_5 = 0x020D,
WM_MOUSELAST_4 = 0x020A,
WM_MOUSELAST_PRE_4 = 0x0209,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_POWERBROADCAST = 0x0218,
WM_DEVICECHANGE = 0x0219,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_REQUEST = 0x0288,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_NCMOUSEHOVER = 0x02A0,
WM_NCMOUSELEAVE = 0x02A2,
WM_WTSSESSION_CHANGE = 0x02B1,
WM_TABLET_FIRST = 0x02c0,
WM_TABLET_LAST = 0x02df,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_APPCOMMAND = 0x0319,
WM_THEMECHANGED = 0x031A,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = 0x8000,
WM_USER = 0x0400,
EM_GETSEL = 0x00B0,
EM_SETSEL = 0x00B1,
EM_GETRECT = 0x00B2,
EM_SETRECT = 0x00B3,
EM_SETRECTNP = 0x00B4,
EM_SCROLL = 0x00B5,
EM_LINESCROLL = 0x00B6,
EM_SCROLLCARET = 0x00B7,
EM_GETMODIFY = 0x00B8,
EM_SETMODIFY = 0x00B9,
EM_GETLINECOUNT = 0x00BA,
EM_LINEINDEX = 0x00BB,
EM_SETHANDLE = 0x00BC,
EM_GETHANDLE = 0x00BD,
EM_GETTHUMB = 0x00BE,
EM_LINELENGTH = 0x00C1,
EM_REPLACESEL = 0x00C2,
EM_GETLINE = 0x00C4,
EM_LIMITTEXT = 0x00C5,
EM_CANUNDO = 0x00C6,
EM_UNDO = 0x00C7,
EM_FMTLINES = 0x00C8,
EM_LINEFROMCHAR = 0x00C9,
EM_SETTABSTOPS = 0x00CB,
EM_SETPASSWORDCHAR = 0x00CC,
EM_EMPTYUNDOBUFFER = 0x00CD,
EM_GETFIRSTVISIBLELINE = 0x00CE,
EM_SETREADONLY = 0x00CF,
EM_SETWORDBREAKPROC = 0x00D0,
EM_GETWORDBREAKPROC = 0x00D1,
EM_GETPASSWORDCHAR = 0x00D2,
EM_SETMARGINS = 0x00D3,
EM_GETMARGINS = 0x00D4,
EM_SETLIMITTEXT = EM_LIMITTEXT,
EM_GETLIMITTEXT = 0x00D5,
EM_POSFROMCHAR = 0x00D6,
EM_CHARFROMPOS = 0x00D7,
EM_SETIMESTATUS = 0x00D8,
EM_GETIMESTATUS = 0x00D9,
BM_GETCHECK= 0x00F0,
BM_SETCHECK= 0x00F1,
BM_GETSTATE= 0x00F2,
BM_SETSTATE= 0x00F3,
BM_SETSTYLE= 0x00F4,
BM_CLICK = 0x00F5,
BM_GETIMAGE= 0x00F6,
BM_SETIMAGE= 0x00F7,
STM_SETICON = 0x0170,
STM_GETICON = 0x0171,
STM_SETIMAGE = 0x0172,
STM_GETIMAGE = 0x0173,
STM_MSGMAX = 0x0174,
DM_GETDEFID = (WM_USER+0),
DM_SETDEFID = (WM_USER+1),
DM_REPOSITION = (WM_USER+2),
LB_ADDSTRING = 0x0180,
LB_INSERTSTRING = 0x0181,
LB_DELETESTRING = 0x0182,
LB_SELITEMRANGEEX= 0x0183,
LB_RESETCONTENT = 0x0184,
LB_SETSEL = 0x0185,
LB_SETCURSEL = 0x0186,
LB_GETSEL = 0x0187,
LB_GETCURSEL = 0x0188,
LB_GETTEXT = 0x0189,
LB_GETTEXTLEN = 0x018A,
LB_GETCOUNT = 0x018B,
LB_SELECTSTRING = 0x018C,
LB_DIR = 0x018D,
LB_GETTOPINDEX = 0x018E,
LB_FINDSTRING = 0x018F,
LB_GETSELCOUNT = 0x0190,
LB_GETSELITEMS = 0x0191,
LB_SETTABSTOPS = 0x0192,
LB_GETHORIZONTALEXTENT = 0x0193,
LB_SETHORIZONTALEXTENT = 0x0194,
LB_SETCOLUMNWIDTH = 0x0195,
LB_ADDFILE = 0x0196,
LB_SETTOPINDEX = 0x0197,
LB_GETITEMRECT = 0x0198,
LB_GETITEMDATA = 0x0199,
LB_SETITEMDATA = 0x019A,
LB_SELITEMRANGE = 0x019B,
LB_SETANCHORINDEX = 0x019C,
LB_GETANCHORINDEX = 0x019D,
LB_SETCARETINDEX = 0x019E,
LB_GETCARETINDEX = 0x019F,
LB_SETITEMHEIGHT = 0x01A0,
LB_GETITEMHEIGHT = 0x01A1,
LB_FINDSTRINGEXACT = 0x01A2,
LB_SETLOCALE = 0x01A5,
LB_GETLOCALE = 0x01A6,
LB_SETCOUNT = 0x01A7,
LB_INITSTORAGE = 0x01A8,
LB_ITEMFROMPOINT = 0x01A9,
LB_MULTIPLEADDSTRING = 0x01B1,
LB_GETLISTBOXINFO= 0x01B2,
LB_MSGMAX_501 = 0x01B3,
LB_MSGMAX_WCE4 = 0x01B1,
LB_MSGMAX_4 = 0x01B0,
LB_MSGMAX_PRE4 = 0x01A8,
CB_GETEDITSEL = 0x0140,
CB_LIMITTEXT = 0x0141,
CB_SETEDITSEL = 0x0142,
CB_ADDSTRING = 0x0143,
CB_DELETESTRING = 0x0144,
CB_DIR = 0x0145,
CB_GETCOUNT = 0x0146,
CB_GETCURSEL = 0x0147,
CB_GETLBTEXT = 0x0148,
CB_GETLBTEXTLEN = 0x0149,
CB_INSERTSTRING = 0x014A,
CB_RESETCONTENT = 0x014B,
CB_FINDSTRING = 0x014C,
CB_SELECTSTRING = 0x014D,
CB_SETCURSEL = 0x014E,
CB_SHOWDROPDOWN = 0x014F,
CB_GETITEMDATA = 0x0150,
CB_SETITEMDATA = 0x0151,
CB_GETDROPPEDCONTROLRECT = 0x0152,
CB_SETITEMHEIGHT = 0x0153,
CB_GETITEMHEIGHT = 0x0154,
CB_SETEXTENDEDUI = 0x0155,
CB_GETEXTENDEDUI = 0x0156,
CB_GETDROPPEDSTATE = 0x0157,
CB_FINDSTRINGEXACT = 0x0158,
CB_SETLOCALE = 0x0159,
CB_GETLOCALE = 0x015A,
CB_GETTOPINDEX = 0x015B,
CB_SETTOPINDEX = 0x015C,
CB_GETHORIZONTALEXTENT = 0x015d,
CB_SETHORIZONTALEXTENT = 0x015e,
CB_GETDROPPEDWIDTH = 0x015f,
CB_SETDROPPEDWIDTH = 0x0160,
CB_INITSTORAGE = 0x0161,
CB_MULTIPLEADDSTRING = 0x0163,
CB_GETCOMBOBOXINFO = 0x0164,
CB_MSGMAX_501 = 0x0165,
CB_MSGMAX_WCE400 = 0x0163,
CB_MSGMAX_400 = 0x0162,
CB_MSGMAX_PRE400 = 0x015B,
SBM_SETPOS = 0x00E0,
SBM_GETPOS = 0x00E1,
SBM_SETRANGE = 0x00E2,
SBM_SETRANGEREDRAW = 0x00E6,
SBM_GETRANGE = 0x00E3,
SBM_ENABLE_ARROWS = 0x00E4,
SBM_SETSCROLLINFO = 0x00E9,
SBM_GETSCROLLINFO = 0x00EA,
SBM_GETSCROLLBARINFO= 0x00EB,
LVM_FIRST = 0x1000,// ListView messages
TV_FIRST = 0x1100,// TreeView messages
HDM_FIRST = 0x1200,// Header messages
TCM_FIRST = 0x1300,// Tab control messages
PGM_FIRST = 0x1400,// Pager control messages
ECM_FIRST = 0x1500,// Edit control messages
BCM_FIRST = 0x1600,// Button control messages
CBM_FIRST = 0x1700,// Combobox control messages
CCM_FIRST = 0x2000,// Common control shared messages
CCM_LAST =(CCM_FIRST + 0x200),
CCM_SETBKCOLOR = (CCM_FIRST + 1),
CCM_SETCOLORSCHEME = (CCM_FIRST + 2),
CCM_GETCOLORSCHEME = (CCM_FIRST + 3),
CCM_GETDROPTARGET = (CCM_FIRST + 4),
CCM_SETUNICODEFORMAT = (CCM_FIRST + 5),
CCM_GETUNICODEFORMAT = (CCM_FIRST + 6),
CCM_SETVERSION = (CCM_FIRST + 0x7),
CCM_GETVERSION = (CCM_FIRST + 0x8),
CCM_SETNOTIFYWINDOW = (CCM_FIRST + 0x9),
CCM_SETWINDOWTHEME = (CCM_FIRST + 0xb),
CCM_DPISCALE = (CCM_FIRST + 0xc),
HDM_GETITEMCOUNT = (HDM_FIRST + 0),
HDM_INSERTITEMA = (HDM_FIRST + 1),
HDM_INSERTITEMW = (HDM_FIRST + 10),
HDM_DELETEITEM = (HDM_FIRST + 2),
HDM_GETITEMA = (HDM_FIRST + 3),
HDM_GETITEMW = (HDM_FIRST + 11),
HDM_SETITEMA = (HDM_FIRST + 4),
HDM_SETITEMW = (HDM_FIRST + 12),
HDM_LAYOUT = (HDM_FIRST + 5),
HDM_HITTEST = (HDM_FIRST + 6),
HDM_GETITEMRECT = (HDM_FIRST + 7),
HDM_SETIMAGELIST = (HDM_FIRST + 8),
HDM_GETIMAGELIST = (HDM_FIRST + 9),
HDM_ORDERTOINDEX = (HDM_FIRST + 15),
HDM_CREATEDRAGIMAGE = (HDM_FIRST + 16),
HDM_GETORDERARRAY = (HDM_FIRST + 17),
HDM_SETORDERARRAY = (HDM_FIRST + 18),
HDM_SETHOTDIVIDER = (HDM_FIRST + 19),
HDM_SETBITMAPMARGIN = (HDM_FIRST + 20),
HDM_GETBITMAPMARGIN = (HDM_FIRST + 21),
HDM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
HDM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
HDM_SETFILTERCHANGETIMEOUT = (HDM_FIRST+22),
HDM_EDITFILTER = (HDM_FIRST+23),
HDM_CLEARFILTER = (HDM_FIRST+24),
TB_ENABLEBUTTON = (WM_USER + 1),
TB_CHECKBUTTON = (WM_USER + 2),
TB_PRESSBUTTON = (WM_USER + 3),
TB_HIDEBUTTON = (WM_USER + 4),
TB_INDETERMINATE = (WM_USER + 5),
TB_MARKBUTTON = (WM_USER + 6),
TB_ISBUTTONENABLED = (WM_USER + 9),
TB_ISBUTTONCHECKED = (WM_USER + 10),
TB_ISBUTTONPRESSED = (WM_USER + 11),
TB_ISBUTTONHIDDEN = (WM_USER + 12),
TB_ISBUTTONINDETERMINATE = (WM_USER + 13),
TB_ISBUTTONHIGHLIGHTED = (WM_USER + 14),
TB_SETSTATE = (WM_USER + 17),
TB_GETSTATE = (WM_USER + 18),
TB_ADDBITMAP = (WM_USER + 19),
TB_ADDBUTTONSA = (WM_USER + 20),
TB_INSERTBUTTONA = (WM_USER + 21),
TB_ADDBUTTONS = (WM_USER + 20),
TB_INSERTBUTTON = (WM_USER + 21),
TB_DELETEBUTTON = (WM_USER + 22),
TB_GETBUTTON = (WM_USER + 23),
TB_BUTTONCOUNT = (WM_USER + 24),
TB_COMMANDTOINDEX = (WM_USER + 25),
TB_SAVERESTOREA = (WM_USER + 26),
TB_SAVERESTOREW = (WM_USER + 76),
TB_CUSTOMIZE = (WM_USER + 27),
TB_ADDSTRINGA = (WM_USER + 28),
TB_ADDSTRINGW = (WM_USER + 77),
TB_GETITEMRECT = (WM_USER + 29),
TB_BUTTONSTRUCTSIZE = (WM_USER + 30),
TB_SETBUTTONSIZE = (WM_USER + 31),
TB_SETBITMAPSIZE = (WM_USER + 32),
TB_AUTOSIZE = (WM_USER + 33),
TB_GETTOOLTIPS = (WM_USER + 35),
TB_SETTOOLTIPS = (WM_USER + 36),
TB_SETPARENT = (WM_USER + 37),
TB_SETROWS = (WM_USER + 39),
TB_GETROWS = (WM_USER + 40),
TB_SETCMDID = (WM_USER + 42),
TB_CHANGEBITMAP = (WM_USER + 43),
TB_GETBITMAP = (WM_USER + 44),
TB_GETBUTTONTEXTA = (WM_USER + 45),
TB_GETBUTTONTEXTW = (WM_USER + 75),
TB_REPLACEBITMAP = (WM_USER + 46),
TB_SETINDENT = (WM_USER + 47),
TB_SETIMAGELIST = (WM_USER + 48),
TB_GETIMAGELIST = (WM_USER + 49),
TB_LOADIMAGES = (WM_USER + 50),
TB_GETRECT = (WM_USER + 51),
TB_SETHOTIMAGELIST = (WM_USER + 52),
TB_GETHOTIMAGELIST = (WM_USER + 53),
TB_SETDISABLEDIMAGELIST = (WM_USER + 54),
TB_GETDISABLEDIMAGELIST = (WM_USER + 55),
TB_SETSTYLE = (WM_USER + 56),
TB_GETSTYLE = (WM_USER + 57),
TB_GETBUTTONSIZE = (WM_USER + 58),
TB_SETBUTTONWIDTH = (WM_USER + 59),
TB_SETMAXTEXTROWS = (WM_USER + 60),
TB_GETTEXTROWS = (WM_USER + 61),
TB_GETOBJECT = (WM_USER + 62),
TB_GETHOTITEM = (WM_USER + 71),
TB_SETHOTITEM = (WM_USER + 72),
TB_SETANCHORHIGHLIGHT = (WM_USER + 73),
TB_GETANCHORHIGHLIGHT = (WM_USER + 74),
TB_MAPACCELERATORA = (WM_USER + 78),
TB_GETINSERTMARK = (WM_USER + 79),
TB_SETINSERTMARK = (WM_USER + 80),
TB_INSERTMARKHITTEST = (WM_USER + 81),
TB_MOVEBUTTON = (WM_USER + 82),
TB_GETMAXSIZE = (WM_USER + 83),
TB_SETEXTENDEDSTYLE = (WM_USER + 84),
TB_GETEXTENDEDSTYLE = (WM_USER + 85),
TB_GETPADDING = (WM_USER + 86),
TB_SETPADDING = (WM_USER + 87),
TB_SETINSERTMARKCOLOR = (WM_USER + 88),
TB_GETINSERTMARKCOLOR = (WM_USER + 89),
TB_SETCOLORSCHEME = CCM_SETCOLORSCHEME,
TB_GETCOLORSCHEME = CCM_GETCOLORSCHEME,
TB_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
TB_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
TB_MAPACCELERATORW = (WM_USER + 90),
TB_GETBITMAPFLAGS = (WM_USER + 41),
TB_GETBUTTONINFOW = (WM_USER + 63),
TB_SETBUTTONINFOW = (WM_USER + 64),
TB_GETBUTTONINFOA = (WM_USER + 65),
TB_SETBUTTONINFOA = (WM_USER + 66),
TB_INSERTBUTTONW = (WM_USER + 67),
TB_ADDBUTTONSW = (WM_USER + 68),
TB_HITTEST = (WM_USER + 69),
TB_SETDRAWTEXTFLAGS = (WM_USER + 70),
TB_GETSTRINGW = (WM_USER + 91),
TB_GETSTRINGA = (WM_USER + 92),
TB_GETMETRICS = (WM_USER + 101),
TB_SETMETRICS = (WM_USER + 102),
TB_SETWINDOWTHEME = CCM_SETWINDOWTHEME,
RB_INSERTBANDA = (WM_USER + 1),
RB_DELETEBAND = (WM_USER + 2),
RB_GETBARINFO = (WM_USER + 3),
RB_SETBARINFO = (WM_USER + 4),
RB_GETBANDINFO = (WM_USER + 5),
RB_SETBANDINFOA = (WM_USER + 6),
RB_SETPARENT = (WM_USER + 7),
RB_HITTEST = (WM_USER + 8),
RB_GETRECT = (WM_USER + 9),
RB_INSERTBANDW = (WM_USER + 10),
RB_SETBANDINFOW = (WM_USER + 11),
RB_GETBANDCOUNT = (WM_USER + 12),
RB_GETROWCOUNT = (WM_USER + 13),
RB_GETROWHEIGHT = (WM_USER + 14),
RB_IDTOINDEX = (WM_USER + 16),
RB_GETTOOLTIPS = (WM_USER + 17),
RB_SETTOOLTIPS = (WM_USER + 18),
RB_SETBKCOLOR = (WM_USER + 19),
RB_GETBKCOLOR = (WM_USER + 20),
RB_SETTEXTCOLOR = (WM_USER + 21),
RB_GETTEXTCOLOR = (WM_USER + 22),
RB_SIZETORECT = (WM_USER + 23),
RB_SETCOLORSCHEME = CCM_SETCOLORSCHEME,
RB_GETCOLORSCHEME = CCM_GETCOLORSCHEME,
RB_BEGINDRAG = (WM_USER + 24),
RB_ENDDRAG = (WM_USER + 25),
RB_DRAGMOVE = (WM_USER + 26),
RB_GETBARHEIGHT = (WM_USER + 27),
RB_GETBANDINFOW = (WM_USER + 28),
RB_GETBANDINFOA = (WM_USER + 29),
RB_MINIMIZEBAND = (WM_USER + 30),
RB_MAXIMIZEBAND = (WM_USER + 31),
RB_GETDROPTARGET = (CCM_GETDROPTARGET),
RB_GETBANDBORDERS = (WM_USER + 34),
RB_SHOWBAND = (WM_USER + 35),
RB_SETPALETTE = (WM_USER + 37),
RB_GETPALETTE = (WM_USER + 38),
RB_MOVEBAND = (WM_USER + 39),
RB_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
RB_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
RB_GETBANDMARGINS = (WM_USER + 40),
RB_SETWINDOWTHEME = CCM_SETWINDOWTHEME,
RB_PUSHCHEVRON = (WM_USER + 43),
TTM_ACTIVATE = (WM_USER + 1),
TTM_SETDELAYTIME = (WM_USER + 3),
TTM_ADDTOOLA = (WM_USER + 4),
TTM_ADDTOOLW = (WM_USER + 50),
TTM_DELTOOLA = (WM_USER + 5),
TTM_DELTOOLW = (WM_USER + 51),
TTM_NEWTOOLRECTA = (WM_USER + 6),
TTM_NEWTOOLRECTW = (WM_USER + 52),
TTM_RELAYEVENT = (WM_USER + 7),
TTM_GETTOOLINFOA = (WM_USER + 8),
TTM_GETTOOLINFOW = (WM_USER + 53),
TTM_SETTOOLINFOA = (WM_USER + 9),
TTM_SETTOOLINFOW = (WM_USER + 54),
TTM_HITTESTA = (WM_USER +10),
TTM_HITTESTW = (WM_USER +55),
TTM_GETTEXTA = (WM_USER +11),
TTM_GETTEXTW = (WM_USER +56),
TTM_UPDATETIPTEXTA = (WM_USER +12),
TTM_UPDATETIPTEXTW = (WM_USER +57),
TTM_GETTOOLCOUNT = (WM_USER +13),
TTM_ENUMTOOLSA = (WM_USER +14),
TTM_ENUMTOOLSW = (WM_USER +58),
TTM_GETCURRENTTOOLA = (WM_USER + 15),
TTM_GETCURRENTTOOLW = (WM_USER + 59),
TTM_WINDOWFROMPOINT = (WM_USER + 16),
TTM_TRACKACTIVATE = (WM_USER + 17),
TTM_TRACKPOSITION = (WM_USER + 18),
TTM_SETTIPBKCOLOR = (WM_USER + 19),
TTM_SETTIPTEXTCOLOR = (WM_USER + 20),
TTM_GETDELAYTIME = (WM_USER + 21),
TTM_GETTIPBKCOLOR = (WM_USER + 22),
TTM_GETTIPTEXTCOLOR = (WM_USER + 23),
TTM_SETMAXTIPWIDTH = (WM_USER + 24),
TTM_GETMAXTIPWIDTH = (WM_USER + 25),
TTM_SETMARGIN = (WM_USER + 26),
TTM_GETMARGIN = (WM_USER + 27),
TTM_POP = (WM_USER + 28),
TTM_UPDATE = (WM_USER + 29),
TTM_GETBUBBLESIZE = (WM_USER + 30),
TTM_ADJUSTRECT = (WM_USER + 31),
TTM_SETTITLEA = (WM_USER + 32),
TTM_SETTITLEW = (WM_USER + 33),
TTM_POPUP = (WM_USER + 34),
TTM_GETTITLE = (WM_USER + 35),
TTM_SETWINDOWTHEME = CCM_SETWINDOWTHEME,
SB_SETTEXTA = (WM_USER+1),
SB_SETTEXTW = (WM_USER+11),
SB_GETTEXTA = (WM_USER+2),
SB_GETTEXTW = (WM_USER+13),
SB_GETTEXTLENGTHA = (WM_USER+3),
SB_GETTEXTLENGTHW = (WM_USER+12),
SB_SETPARTS = (WM_USER+4),
SB_GETPARTS = (WM_USER+6),
SB_GETBORDERS = (WM_USER+7),
SB_SETMINHEIGHT = (WM_USER+8),
SB_SIMPLE = (WM_USER+9),
SB_GETRECT = (WM_USER+10),
SB_ISSIMPLE = (WM_USER+14),
SB_SETICON = (WM_USER+15),
SB_SETTIPTEXTA = (WM_USER+16),
SB_SETTIPTEXTW = (WM_USER+17),
SB_GETTIPTEXTA = (WM_USER+18),
SB_GETTIPTEXTW = (WM_USER+19),
SB_GETICON = (WM_USER+20),
SB_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
SB_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
SB_SETBKCOLOR = CCM_SETBKCOLOR,
SB_SIMPLEID = 0x00ff,
TBM_GETPOS = (WM_USER),
TBM_GETRANGEMIN = (WM_USER+1),
TBM_GETRANGEMAX = (WM_USER+2),
TBM_GETTIC = (WM_USER+3),
TBM_SETTIC = (WM_USER+4),
TBM_SETPOS = (WM_USER+5),
TBM_SETRANGE = (WM_USER+6),
TBM_SETRANGEMIN = (WM_USER+7),
TBM_SETRANGEMAX = (WM_USER+8),
TBM_CLEARTICS = (WM_USER+9),
TBM_SETSEL = (WM_USER+10),
TBM_SETSELSTART = (WM_USER+11),
TBM_SETSELEND = (WM_USER+12),
TBM_GETPTICS = (WM_USER+14),
TBM_GETTICPOS = (WM_USER+15),
TBM_GETNUMTICS = (WM_USER+16),
TBM_GETSELSTART = (WM_USER+17),
TBM_GETSELEND = (WM_USER+18),
TBM_CLEARSEL = (WM_USER+19),
TBM_SETTICFREQ = (WM_USER+20),
TBM_SETPAGESIZE = (WM_USER+21),
TBM_GETPAGESIZE = (WM_USER+22),
TBM_SETLINESIZE = (WM_USER+23),
TBM_GETLINESIZE = (WM_USER+24),
TBM_GETTHUMBRECT = (WM_USER+25),
TBM_GETCHANNELRECT = (WM_USER+26),
TBM_SETTHUMBLENGTH = (WM_USER+27),
TBM_GETTHUMBLENGTH = (WM_USER+28),
TBM_SETTOOLTIPS = (WM_USER+29),
TBM_GETTOOLTIPS = (WM_USER+30),
TBM_SETTIPSIDE = (WM_USER+31),
TBM_SETBUDDY = (WM_USER+32),
TBM_GETBUDDY = (WM_USER+33),
TBM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
TBM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
DL_BEGINDRAG = (WM_USER+133),
DL_DRAGGING = (WM_USER+134),
DL_DROPPED = (WM_USER+135),
DL_CANCELDRAG = (WM_USER+136),
UDM_SETRANGE = (WM_USER+101),
UDM_GETRANGE = (WM_USER+102),
UDM_SETPOS = (WM_USER+103),
UDM_GETPOS = (WM_USER+104),
UDM_SETBUDDY = (WM_USER+105),
UDM_GETBUDDY = (WM_USER+106),
UDM_SETACCEL = (WM_USER+107),
UDM_GETACCEL = (WM_USER+108),
UDM_SETBASE = (WM_USER+109),
UDM_GETBASE = (WM_USER+110),
UDM_SETRANGE32 = (WM_USER+111),
UDM_GETRANGE32 = (WM_USER+112),
UDM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
UDM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
UDM_SETPOS32 = (WM_USER+113),
UDM_GETPOS32 = (WM_USER+114),
PBM_SETRANGE = (WM_USER+1),
PBM_SETPOS = (WM_USER+2),
PBM_DELTAPOS = (WM_USER+3),
PBM_SETSTEP = (WM_USER+4),
PBM_STEPIT = (WM_USER+5),
PBM_SETRANGE32 = (WM_USER+6),
PBM_GETRANGE = (WM_USER+7),
PBM_GETPOS = (WM_USER+8),
PBM_SETBARCOLOR = (WM_USER+9),
PBM_SETBKCOLOR = CCM_SETBKCOLOR,
HKM_SETHOTKEY = (WM_USER+1),
HKM_GETHOTKEY = (WM_USER+2),
HKM_SETRULES = (WM_USER+3),
LVM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
LVM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
LVM_GETBKCOLOR = (LVM_FIRST + 0),
LVM_SETBKCOLOR = (LVM_FIRST + 1),
LVM_GETIMAGELIST = (LVM_FIRST + 2),
LVM_SETIMAGELIST = (LVM_FIRST + 3),
LVM_GETITEMCOUNT = (LVM_FIRST + 4),
LVM_GETITEMA = (LVM_FIRST + 5),
LVM_GETITEMW = (LVM_FIRST + 75),
LVM_SETITEMA = (LVM_FIRST + 6),
LVM_SETITEMW = (LVM_FIRST + 76),
LVM_INSERTITEMA = (LVM_FIRST + 7),
LVM_INSERTITEMW = (LVM_FIRST + 77),
LVM_DELETEITEM = (LVM_FIRST + 8),
LVM_DELETEALLITEMS = (LVM_FIRST + 9),
LVM_GETCALLBACKMASK = (LVM_FIRST + 10),
LVM_SETCALLBACKMASK = (LVM_FIRST + 11),
LVM_FINDITEMA = (LVM_FIRST + 13),
LVM_FINDITEMW = (LVM_FIRST + 83),
LVM_GETITEMRECT = (LVM_FIRST + 14),
LVM_SETITEMPOSITION = (LVM_FIRST + 15),
LVM_GETITEMPOSITION = (LVM_FIRST + 16),
LVM_GETSTRINGWIDTHA = (LVM_FIRST + 17),
LVM_GETSTRINGWIDTHW = (LVM_FIRST + 87),
LVM_HITTEST = (LVM_FIRST + 18),
LVM_ENSUREVISIBLE = (LVM_FIRST + 19),
LVM_SCROLL = (LVM_FIRST + 20),
LVM_REDRAWITEMS = (LVM_FIRST + 21),
LVM_ARRANGE = (LVM_FIRST + 22),
LVM_EDITLABELA = (LVM_FIRST + 23),
LVM_EDITLABELW = (LVM_FIRST + 118),
LVM_GETEDITCONTROL = (LVM_FIRST + 24),
LVM_GETCOLUMNA = (LVM_FIRST + 25),
LVM_GETCOLUMNW = (LVM_FIRST + 95),
LVM_SETCOLUMNA = (LVM_FIRST + 26),
LVM_SETCOLUMNW = (LVM_FIRST + 96),
LVM_INSERTCOLUMNA = (LVM_FIRST + 27),
LVM_INSERTCOLUMNW = (LVM_FIRST + 97),
LVM_DELETECOLUMN = (LVM_FIRST + 28),
LVM_GETCOLUMNWIDTH = (LVM_FIRST + 29),
LVM_SETCOLUMNWIDTH = (LVM_FIRST + 30),
LVM_CREATEDRAGIMAGE = (LVM_FIRST + 33),
LVM_GETVIEWRECT = (LVM_FIRST + 34),
LVM_GETTEXTCOLOR = (LVM_FIRST + 35),
LVM_SETTEXTCOLOR = (LVM_FIRST + 36),
LVM_GETTEXTBKCOLOR = (LVM_FIRST + 37),
LVM_SETTEXTBKCOLOR = (LVM_FIRST + 38),
LVM_GETTOPINDEX = (LVM_FIRST + 39),
LVM_GETCOUNTPERPAGE = (LVM_FIRST + 40),
LVM_GETORIGIN = (LVM_FIRST + 41),
LVM_UPDATE = (LVM_FIRST + 42),
LVM_SETITEMSTATE = (LVM_FIRST + 43),
LVM_GETITEMSTATE = (LVM_FIRST + 44),
LVM_GETITEMTEXTA = (LVM_FIRST + 45),
LVM_GETITEMTEXTW = (LVM_FIRST + 115),
LVM_SETITEMTEXTA = (LVM_FIRST + 46),
LVM_SETITEMTEXTW = (LVM_FIRST + 116),
LVM_SETITEMCOUNT = (LVM_FIRST + 47),
LVM_SORTITEMS = (LVM_FIRST + 48),
LVM_SETITEMPOSITION32 = (LVM_FIRST + 49),
LVM_GETSELECTEDCOUNT = (LVM_FIRST + 50),
LVM_GETITEMSPACING = (LVM_FIRST + 51),
LVM_GETISEARCHSTRINGA = (LVM_FIRST + 52),
LVM_GETISEARCHSTRINGW = (LVM_FIRST + 117),
LVM_SETICONSPACING = (LVM_FIRST + 53),
LVM_SETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 54),
LVM_GETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 55),
LVM_GETSUBITEMRECT = (LVM_FIRST + 56),
LVM_SUBITEMHITTEST = (LVM_FIRST + 57),
LVM_SETCOLUMNORDERARRAY = (LVM_FIRST + 58),
LVM_GETCOLUMNORDERARRAY = (LVM_FIRST + 59),
LVM_SETHOTITEM = (LVM_FIRST + 60),
LVM_GETHOTITEM = (LVM_FIRST + 61),
LVM_SETHOTCURSOR = (LVM_FIRST + 62),
LVM_GETHOTCURSOR = (LVM_FIRST + 63),
LVM_APPROXIMATEVIEWRECT = (LVM_FIRST + 64),
LVM_SETWORKAREAS = (LVM_FIRST + 65),
LVM_GETWORKAREAS = (LVM_FIRST + 70),
LVM_GETNUMBEROFWORKAREAS = (LVM_FIRST + 73),
LVM_GETSELECTIONMARK = (LVM_FIRST + 66),
LVM_SETSELECTIONMARK = (LVM_FIRST + 67),
LVM_SETHOVERTIME = (LVM_FIRST + 71),
LVM_GETHOVERTIME = (LVM_FIRST + 72),
LVM_SETTOOLTIPS = (LVM_FIRST + 74),
LVM_GETTOOLTIPS = (LVM_FIRST + 78),
LVM_SORTITEMSEX = (LVM_FIRST + 81),
LVM_SETBKIMAGEA = (LVM_FIRST + 68),
LVM_SETBKIMAGEW = (LVM_FIRST + 138),
LVM_GETBKIMAGEA = (LVM_FIRST + 69),
LVM_GETBKIMAGEW = (LVM_FIRST + 139),
LVM_SETSELECTEDCOLUMN = (LVM_FIRST + 140),
LVM_SETTILEWIDTH = (LVM_FIRST + 141),
LVM_SETVIEW = (LVM_FIRST + 142),
LVM_GETVIEW = (LVM_FIRST + 143),
LVM_INSERTGROUP = (LVM_FIRST + 145),
LVM_SETGROUPINFO = (LVM_FIRST + 147),
LVM_GETGROUPINFO = (LVM_FIRST + 149),
LVM_REMOVEGROUP = (LVM_FIRST + 150),
LVM_MOVEGROUP = (LVM_FIRST + 151),
LVM_MOVEITEMTOGROUP = (LVM_FIRST + 154),
LVM_SETGROUPMETRICS = (LVM_FIRST + 155),
LVM_GETGROUPMETRICS = (LVM_FIRST + 156),
LVM_ENABLEGROUPVIEW = (LVM_FIRST + 157),
LVM_SORTGROUPS = (LVM_FIRST + 158),
LVM_INSERTGROUPSORTED = (LVM_FIRST + 159),
LVM_REMOVEALLGROUPS = (LVM_FIRST + 160),
LVM_HASGROUP = (LVM_FIRST + 161),
LVM_SETTILEVIEWINFO = (LVM_FIRST + 162),
LVM_GETTILEVIEWINFO = (LVM_FIRST + 163),
LVM_SETTILEINFO = (LVM_FIRST + 164),
LVM_GETTILEINFO = (LVM_FIRST + 165),
LVM_SETINSERTMARK = (LVM_FIRST + 166),
LVM_GETINSERTMARK = (LVM_FIRST + 167),
LVM_INSERTMARKHITTEST = (LVM_FIRST + 168),
LVM_GETINSERTMARKRECT = (LVM_FIRST + 169),
LVM_SETINSERTMARKCOLOR = (LVM_FIRST + 170),
LVM_GETINSERTMARKCOLOR = (LVM_FIRST + 171),
LVM_SETINFOTIP = (LVM_FIRST + 173),
LVM_GETSELECTEDCOLUMN = (LVM_FIRST + 174),
LVM_ISGROUPVIEWENABLED = (LVM_FIRST + 175),
LVM_GETOUTLINECOLOR = (LVM_FIRST + 176),
LVM_SETOUTLINECOLOR = (LVM_FIRST + 177),
LVM_CANCELEDITLABEL = (LVM_FIRST + 179),
LVM_MAPINDEXTOID = (LVM_FIRST + 180),
LVM_MAPIDTOINDEX = (LVM_FIRST + 181),
TVM_INSERTITEMA = (TV_FIRST + 0),
TVM_INSERTITEMW = (TV_FIRST + 50),
TVM_DELETEITEM = (TV_FIRST + 1),
TVM_EXPAND = (TV_FIRST + 2),
TVM_GETITEMRECT = (TV_FIRST + 4),
TVM_GETCOUNT = (TV_FIRST + 5),
TVM_GETINDENT = (TV_FIRST + 6),
TVM_SETINDENT = (TV_FIRST + 7),
TVM_GETIMAGELIST = (TV_FIRST + 8),
TVM_SETIMAGELIST = (TV_FIRST + 9),
TVM_GETNEXTITEM = (TV_FIRST + 10),
TVM_SELECTITEM = (TV_FIRST + 11),
TVM_GETITEMA = (TV_FIRST + 12),
TVM_GETITEMW = (TV_FIRST + 62),
TVM_SETITEMA = (TV_FIRST + 13),
TVM_SETITEMW = (TV_FIRST + 63),
TVM_EDITLABELA = (TV_FIRST + 14),
TVM_EDITLABELW = (TV_FIRST + 65),
TVM_GETEDITCONTROL = (TV_FIRST + 15),
TVM_GETVISIBLECOUNT = (TV_FIRST + 16),
TVM_HITTEST = (TV_FIRST + 17),
TVM_CREATEDRAGIMAGE = (TV_FIRST + 18),
TVM_SORTCHILDREN = (TV_FIRST + 19),
TVM_ENSUREVISIBLE = (TV_FIRST + 20),
TVM_SORTCHILDRENCB = (TV_FIRST + 21),
TVM_ENDEDITLABELNOW = (TV_FIRST + 22),
TVM_GETISEARCHSTRINGA = (TV_FIRST + 23),
TVM_GETISEARCHSTRINGW = (TV_FIRST + 64),
TVM_SETTOOLTIPS = (TV_FIRST + 24),
TVM_GETTOOLTIPS = (TV_FIRST + 25),
TVM_SETINSERTMARK = (TV_FIRST + 26),
TVM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
TVM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
TVM_SETITEMHEIGHT = (TV_FIRST + 27),
TVM_GETITEMHEIGHT = (TV_FIRST + 28),
TVM_SETBKCOLOR = (TV_FIRST + 29),
TVM_SETTEXTCOLOR = (TV_FIRST + 30),
TVM_GETBKCOLOR = (TV_FIRST + 31),
TVM_GETTEXTCOLOR = (TV_FIRST + 32),
TVM_SETSCROLLTIME = (TV_FIRST + 33),
TVM_GETSCROLLTIME = (TV_FIRST + 34),
TVM_SETINSERTMARKCOLOR = (TV_FIRST + 37),
TVM_GETINSERTMARKCOLOR = (TV_FIRST + 38),
TVM_GETITEMSTATE = (TV_FIRST + 39),
TVM_SETLINECOLOR = (TV_FIRST + 40),
TVM_GETLINECOLOR = (TV_FIRST + 41),
TVM_MAPACCIDTOHTREEITEM = (TV_FIRST + 42),
TVM_MAPHTREEITEMTOACCID = (TV_FIRST + 43),
CBEM_INSERTITEMA = (WM_USER + 1),
CBEM_SETIMAGELIST = (WM_USER + 2),
CBEM_GETIMAGELIST = (WM_USER + 3),
CBEM_GETITEMA = (WM_USER + 4),
CBEM_SETITEMA = (WM_USER + 5),
CBEM_DELETEITEM = CB_DELETESTRING,
CBEM_GETCOMBOCONTROL = (WM_USER + 6),
CBEM_GETEDITCONTROL = (WM_USER + 7),
CBEM_SETEXTENDEDSTYLE = (WM_USER + 14),
CBEM_GETEXTENDEDSTYLE = (WM_USER + 9),
CBEM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
CBEM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
CBEM_SETEXSTYLE = (WM_USER + 8),
CBEM_GETEXSTYLE = (WM_USER + 9),
CBEM_HASEDITCHANGED = (WM_USER + 10),
CBEM_INSERTITEMW = (WM_USER + 11),
CBEM_SETITEMW = (WM_USER + 12),
CBEM_GETITEMW = (WM_USER + 13),
TCM_GETIMAGELIST = (TCM_FIRST + 2),
TCM_SETIMAGELIST = (TCM_FIRST + 3),
TCM_GETITEMCOUNT = (TCM_FIRST + 4),
TCM_GETITEMA = (TCM_FIRST + 5),
TCM_GETITEMW = (TCM_FIRST + 60),
TCM_SETITEMA = (TCM_FIRST + 6),
TCM_SETITEMW = (TCM_FIRST + 61),
TCM_INSERTITEMA = (TCM_FIRST + 7),
TCM_INSERTITEMW = (TCM_FIRST + 62),
TCM_DELETEITEM = (TCM_FIRST + 8),
TCM_DELETEALLITEMS = (TCM_FIRST + 9),
TCM_GETITEMRECT = (TCM_FIRST + 10),
TCM_GETCURSEL = (TCM_FIRST + 11),
TCM_SETCURSEL = (TCM_FIRST + 12),
TCM_HITTEST = (TCM_FIRST + 13),
TCM_SETITEMEXTRA = (TCM_FIRST + 14),
TCM_ADJUSTRECT = (TCM_FIRST + 40),
TCM_SETITEMSIZE = (TCM_FIRST + 41),
TCM_REMOVEIMAGE = (TCM_FIRST + 42),
TCM_SETPADDING = (TCM_FIRST + 43),
TCM_GETROWCOUNT = (TCM_FIRST + 44),
TCM_GETTOOLTIPS = (TCM_FIRST + 45),
TCM_SETTOOLTIPS = (TCM_FIRST + 46),
TCM_GETCURFOCUS = (TCM_FIRST + 47),
TCM_SETCURFOCUS = (TCM_FIRST + 48),
TCM_SETMINTABWIDTH = (TCM_FIRST + 49),
TCM_DESELECTALL = (TCM_FIRST + 50),
TCM_HIGHLIGHTITEM = (TCM_FIRST + 51),
TCM_SETEXTENDEDSTYLE = (TCM_FIRST + 52),
TCM_GETEXTENDEDSTYLE = (TCM_FIRST + 53),
TCM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
TCM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
ACM_OPENA = (WM_USER+100),
ACM_OPENW = (WM_USER+103),
ACM_PLAY = (WM_USER+101),
ACM_STOP = (WM_USER+102),
MCM_FIRST = 0x1000,
MCM_GETCURSEL = (MCM_FIRST + 1),
MCM_SETCURSEL = (MCM_FIRST + 2),
MCM_GETMAXSELCOUNT = (MCM_FIRST + 3),
MCM_SETMAXSELCOUNT = (MCM_FIRST + 4),
MCM_GETSELRANGE = (MCM_FIRST + 5),
MCM_SETSELRANGE = (MCM_FIRST + 6),
MCM_GETMONTHRANGE = (MCM_FIRST + 7),
MCM_SETDAYSTATE = (MCM_FIRST + 8),
MCM_GETMINREQRECT = (MCM_FIRST + 9),
MCM_SETCOLOR = (MCM_FIRST + 10),
MCM_GETCOLOR = (MCM_FIRST + 11),
MCM_SETTODAY = (MCM_FIRST + 12),
MCM_GETTODAY = (MCM_FIRST + 13),
MCM_HITTEST = (MCM_FIRST + 14),
MCM_SETFIRSTDAYOFWEEK = (MCM_FIRST + 15),
MCM_GETFIRSTDAYOFWEEK = (MCM_FIRST + 16),
MCM_GETRANGE = (MCM_FIRST + 17),
MCM_SETRANGE = (MCM_FIRST + 18),
MCM_GETMONTHDELTA = (MCM_FIRST + 19),
MCM_SETMONTHDELTA = (MCM_FIRST + 20),
MCM_GETMAXTODAYWIDTH = (MCM_FIRST + 21),
MCM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
MCM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
DTM_FIRST = 0x1000,
DTM_GETSYSTEMTIME = (DTM_FIRST + 1),
DTM_SETSYSTEMTIME = (DTM_FIRST + 2),
DTM_GETRANGE = (DTM_FIRST + 3),
DTM_SETRANGE = (DTM_FIRST + 4),
DTM_SETFORMATA = (DTM_FIRST + 5),
DTM_SETFORMATW = (DTM_FIRST + 50),
DTM_SETMCCOLOR = (DTM_FIRST + 6),
DTM_GETMCCOLOR = (DTM_FIRST + 7),
DTM_GETMONTHCAL = (DTM_FIRST + 8),
DTM_SETMCFONT = (DTM_FIRST + 9),
DTM_GETMCFONT = (DTM_FIRST + 10),
PGM_SETCHILD = (PGM_FIRST + 1),
PGM_RECALCSIZE = (PGM_FIRST + 2),
PGM_FORWARDMOUSE = (PGM_FIRST + 3),
PGM_SETBKCOLOR = (PGM_FIRST + 4),
PGM_GETBKCOLOR = (PGM_FIRST + 5),
PGM_SETBORDER = (PGM_FIRST + 6),
PGM_GETBORDER = (PGM_FIRST + 7),
PGM_SETPOS = (PGM_FIRST + 8),
PGM_GETPOS = (PGM_FIRST + 9),
PGM_SETBUTTONSIZE = (PGM_FIRST + 10),
PGM_GETBUTTONSIZE = (PGM_FIRST + 11),
PGM_GETBUTTONSTATE = (PGM_FIRST + 12),
PGM_GETDROPTARGET = CCM_GETDROPTARGET,
BCM_GETIDEALSIZE = (BCM_FIRST + 0x0001),
BCM_SETIMAGELIST = (BCM_FIRST + 0x0002),
BCM_GETIMAGELIST = (BCM_FIRST + 0x0003),
BCM_SETTEXTMARGIN = (BCM_FIRST + 0x0004),
BCM_GETTEXTMARGIN = (BCM_FIRST + 0x0005),
EM_SETCUEBANNER = (ECM_FIRST + 1),
EM_GETCUEBANNER = (ECM_FIRST + 2),
EM_SHOWBALLOONTIP = (ECM_FIRST + 3),
EM_HIDEBALLOONTIP = (ECM_FIRST + 4),
CB_SETMINVISIBLE = (CBM_FIRST + 1),
CB_GETMINVISIBLE = (CBM_FIRST + 2),
LM_HITTEST = (WM_USER + 0x300),
LM_GETIDEALHEIGHT = (WM_USER + 0x301),
LM_SETITEM = (WM_USER + 0x302),
LM_GETITEM = (WM_USER + 0x303)
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* a class that provides a basic SKIPJACK engine.
*/
public class SkipjackEngine
: IBlockCipher
{
const int BLOCK_SIZE = 8;
static readonly short [] ftable =
{
0xa3, 0xd7, 0x09, 0x83, 0xf8, 0x48, 0xf6, 0xf4, 0xb3, 0x21, 0x15, 0x78, 0x99, 0xb1, 0xaf, 0xf9,
0xe7, 0x2d, 0x4d, 0x8a, 0xce, 0x4c, 0xca, 0x2e, 0x52, 0x95, 0xd9, 0x1e, 0x4e, 0x38, 0x44, 0x28,
0x0a, 0xdf, 0x02, 0xa0, 0x17, 0xf1, 0x60, 0x68, 0x12, 0xb7, 0x7a, 0xc3, 0xe9, 0xfa, 0x3d, 0x53,
0x96, 0x84, 0x6b, 0xba, 0xf2, 0x63, 0x9a, 0x19, 0x7c, 0xae, 0xe5, 0xf5, 0xf7, 0x16, 0x6a, 0xa2,
0x39, 0xb6, 0x7b, 0x0f, 0xc1, 0x93, 0x81, 0x1b, 0xee, 0xb4, 0x1a, 0xea, 0xd0, 0x91, 0x2f, 0xb8,
0x55, 0xb9, 0xda, 0x85, 0x3f, 0x41, 0xbf, 0xe0, 0x5a, 0x58, 0x80, 0x5f, 0x66, 0x0b, 0xd8, 0x90,
0x35, 0xd5, 0xc0, 0xa7, 0x33, 0x06, 0x65, 0x69, 0x45, 0x00, 0x94, 0x56, 0x6d, 0x98, 0x9b, 0x76,
0x97, 0xfc, 0xb2, 0xc2, 0xb0, 0xfe, 0xdb, 0x20, 0xe1, 0xeb, 0xd6, 0xe4, 0xdd, 0x47, 0x4a, 0x1d,
0x42, 0xed, 0x9e, 0x6e, 0x49, 0x3c, 0xcd, 0x43, 0x27, 0xd2, 0x07, 0xd4, 0xde, 0xc7, 0x67, 0x18,
0x89, 0xcb, 0x30, 0x1f, 0x8d, 0xc6, 0x8f, 0xaa, 0xc8, 0x74, 0xdc, 0xc9, 0x5d, 0x5c, 0x31, 0xa4,
0x70, 0x88, 0x61, 0x2c, 0x9f, 0x0d, 0x2b, 0x87, 0x50, 0x82, 0x54, 0x64, 0x26, 0x7d, 0x03, 0x40,
0x34, 0x4b, 0x1c, 0x73, 0xd1, 0xc4, 0xfd, 0x3b, 0xcc, 0xfb, 0x7f, 0xab, 0xe6, 0x3e, 0x5b, 0xa5,
0xad, 0x04, 0x23, 0x9c, 0x14, 0x51, 0x22, 0xf0, 0x29, 0x79, 0x71, 0x7e, 0xff, 0x8c, 0x0e, 0xe2,
0x0c, 0xef, 0xbc, 0x72, 0x75, 0x6f, 0x37, 0xa1, 0xec, 0xd3, 0x8e, 0x62, 0x8b, 0x86, 0x10, 0xe8,
0x08, 0x77, 0x11, 0xbe, 0x92, 0x4f, 0x24, 0xc5, 0x32, 0x36, 0x9d, 0xcf, 0xf3, 0xa6, 0xbb, 0xac,
0x5e, 0x6c, 0xa9, 0x13, 0x57, 0x25, 0xb5, 0xe3, 0xbd, 0xa8, 0x3a, 0x01, 0x05, 0x59, 0x2a, 0x46
};
private int[] key0, key1, key2, key3;
private bool encrypting;
/**
* initialise a SKIPJACK cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("invalid parameter passed to SKIPJACK init - " + parameters.GetType().ToString());
byte[] keyBytes = ((KeyParameter)parameters).GetKey();
this.encrypting = forEncryption;
this.key0 = new int[32];
this.key1 = new int[32];
this.key2 = new int[32];
this.key3 = new int[32];
//
// expand the key to 128 bytes in 4 parts (saving us a modulo, multiply
// and an addition).
//
for (int i = 0; i < 32; i ++)
{
key0[i] = keyBytes[(i * 4) % 10] & 0xff;
key1[i] = keyBytes[(i * 4 + 1) % 10] & 0xff;
key2[i] = keyBytes[(i * 4 + 2) % 10] & 0xff;
key3[i] = keyBytes[(i * 4 + 3) % 10] & 0xff;
}
}
public string AlgorithmName
{
get { return "SKIPJACK"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return BLOCK_SIZE;
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (key1 == null)
throw new InvalidOperationException("SKIPJACK engine not initialised");
if ((inOff + BLOCK_SIZE) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + BLOCK_SIZE) > output.Length)
throw new DataLengthException("output buffer too short");
if (encrypting)
{
EncryptBlock(input, inOff, output, outOff);
}
else
{
DecryptBlock(input, inOff, output, outOff);
}
return BLOCK_SIZE;
}
public void Reset()
{
}
/**
* The G permutation
*/
private int G(
int k,
int w)
{
int g1, g2, g3, g4, g5, g6;
g1 = (w >> 8) & 0xff;
g2 = w & 0xff;
g3 = ftable[g2 ^ key0[k]] ^ g1;
g4 = ftable[g3 ^ key1[k]] ^ g2;
g5 = ftable[g4 ^ key2[k]] ^ g3;
g6 = ftable[g5 ^ key3[k]] ^ g4;
return ((g5 << 8) + g6);
}
public int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
int w1 = (input[inOff + 0] << 8) + (input[inOff + 1] & 0xff);
int w2 = (input[inOff + 2] << 8) + (input[inOff + 3] & 0xff);
int w3 = (input[inOff + 4] << 8) + (input[inOff + 5] & 0xff);
int w4 = (input[inOff + 6] << 8) + (input[inOff + 7] & 0xff);
int k = 0;
for (int t = 0; t < 2; t++)
{
for(int i = 0; i < 8; i++)
{
int tmp = w4;
w4 = w3;
w3 = w2;
w2 = G(k, w1);
w1 = w2 ^ tmp ^ (k + 1);
k++;
}
for(int i = 0; i < 8; i++)
{
int tmp = w4;
w4 = w3;
w3 = w1 ^ w2 ^ (k + 1);
w2 = G(k, w1);
w1 = tmp;
k++;
}
}
outBytes[outOff + 0] = (byte)((w1 >> 8));
outBytes[outOff + 1] = (byte)(w1);
outBytes[outOff + 2] = (byte)((w2 >> 8));
outBytes[outOff + 3] = (byte)(w2);
outBytes[outOff + 4] = (byte)((w3 >> 8));
outBytes[outOff + 5] = (byte)(w3);
outBytes[outOff + 6] = (byte)((w4 >> 8));
outBytes[outOff + 7] = (byte)(w4);
return BLOCK_SIZE;
}
/**
* the inverse of the G permutation.
*/
private int H(
int k,
int w)
{
int h1, h2, h3, h4, h5, h6;
h1 = w & 0xff;
h2 = (w >> 8) & 0xff;
h3 = ftable[h2 ^ key3[k]] ^ h1;
h4 = ftable[h3 ^ key2[k]] ^ h2;
h5 = ftable[h4 ^ key1[k]] ^ h3;
h6 = ftable[h5 ^ key0[k]] ^ h4;
return ((h6 << 8) + h5);
}
public int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
int w2 = (input[inOff + 0] << 8) + (input[inOff + 1] & 0xff);
int w1 = (input[inOff + 2] << 8) + (input[inOff + 3] & 0xff);
int w4 = (input[inOff + 4] << 8) + (input[inOff + 5] & 0xff);
int w3 = (input[inOff + 6] << 8) + (input[inOff + 7] & 0xff);
int k = 31;
for (int t = 0; t < 2; t++)
{
for(int i = 0; i < 8; i++)
{
int tmp = w4;
w4 = w3;
w3 = w2;
w2 = H(k, w1);
w1 = w2 ^ tmp ^ (k + 1);
k--;
}
for(int i = 0; i < 8; i++)
{
int tmp = w4;
w4 = w3;
w3 = w1 ^ w2 ^ (k + 1);
w2 = H(k, w1);
w1 = tmp;
k--;
}
}
outBytes[outOff + 0] = (byte)((w2 >> 8));
outBytes[outOff + 1] = (byte)(w2);
outBytes[outOff + 2] = (byte)((w1 >> 8));
outBytes[outOff + 3] = (byte)(w1);
outBytes[outOff + 4] = (byte)((w4 >> 8));
outBytes[outOff + 5] = (byte)(w4);
outBytes[outOff + 6] = (byte)((w3 >> 8));
outBytes[outOff + 7] = (byte)(w3);
return BLOCK_SIZE;
}
}
}
| |
// 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 Xunit;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public class TaskFactory_FromAsyncTests
{
// Exercise the FromAsync() methods in Task and Task<TResult>.
[Fact]
public static void RunAPMFactoryTests()
{
FakeAsyncClass fac = new FakeAsyncClass();
Task t = null;
Task<string> f = null;
string check;
object stateObject = new object();
// Exercise void overload that takes IAsyncResult instead of StartMethod
t = Task.Factory.FromAsync(fac.StartWrite("", 0, 0, null, null), delegate (IAsyncResult iar) { });
t.Wait();
check = fac.ToString();
Assert.Equal(0, check.Length);
//CreationOption overload
t = Task.Factory.FromAsync(fac.StartWrite("", 0, 0, null, null), delegate (IAsyncResult iar) { }, TaskCreationOptions.None);
t.Wait();
check = fac.ToString();
Assert.Equal(0, check.Length);
// Exercise 0-arg void option
t = Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, stateObject);
t.Wait();
Assert.Equal(0, check.Length);
Assert.Same(stateObject, ((IAsyncResult)t).AsyncState);
// Exercise 1-arg void option
Task.Factory.FromAsync(
fac.StartWrite,
fac.EndWrite,
"1234", stateObject).Wait();
check = fac.ToString();
Assert.Equal("1234", check);
Assert.Same(stateObject, ((IAsyncResult)t).AsyncState);
// Exercise 2-arg void option
Task.Factory.FromAsync(
fac.StartWrite,
fac.EndWrite,
"aaaabcdef",
4, stateObject).Wait();
check = fac.ToString();
Assert.Equal("1234aaaa", check);
Assert.Same(stateObject, ((IAsyncResult)t).AsyncState);
// Exercise 3-arg void option
Task.Factory.FromAsync(
fac.StartWrite,
fac.EndWrite,
"abcdzzzz",
4,
4,
stateObject).Wait();
check = fac.ToString();
Assert.Equal("1234aaaazzzz", check);
Assert.Same(stateObject, ((IAsyncResult)t).AsyncState);
// Read side, exercises getting return values from EndMethod
char[] carray = new char[100];
// Exercise 3-arg value option
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
4, // maxchars
carray,
0,
stateObject);
string s = f.Result;
Assert.Equal("1234", s);
Assert.Equal('1', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 2-arg value option
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
4,
carray,
stateObject);
s = f.Result;
Assert.Equal("aaaa", s);
Assert.Equal('a', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 1-arg value option
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
1,
stateObject);
s = f.Result;
Assert.Equal("z", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 0-arg value option
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
stateObject);
s = f.Result;
Assert.Equal("zzz", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
//
// Do all of the read tests again, except with Task.Factory.FromAsync<string>(), instead of Task<string>.Factory.FromAsync().
//
fac.EndWrite(fac.StartWrite("12345678aaaaAAAAzzzz", null, null));
// Exercise 3-arg value option
f = Task.Factory.FromAsync<int, char[], int, string>(
//f = Task.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
4, // maxchars
carray,
0,
stateObject);
s = f.Result;
Assert.Equal("1234", s);
Assert.Equal('1', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// one more with the creationOptions overload
f = Task.Factory.FromAsync<int, char[], int, string>(
//f = Task.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
4, // maxchars
carray,
0,
stateObject,
TaskCreationOptions.None);
s = f.Result;
Assert.Equal("5678", s);
Assert.Equal('5', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 2-arg value option
f = Task.Factory.FromAsync<int, char[], string>(
fac.StartRead,
fac.EndRead,
4,
carray,
stateObject);
s = f.Result;
Assert.Equal("aaaa", s);
Assert.Equal('a', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
//one more with the creation option overload
f = Task.Factory.FromAsync<int, char[], string>(
fac.StartRead,
fac.EndRead,
4,
carray,
stateObject,
TaskCreationOptions.None);
s = f.Result;
Assert.Equal("AAAA", s);
Assert.Equal('A', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 1-arg value option
f = Task.Factory.FromAsync<int, string>(
fac.StartRead,
fac.EndRead,
1,
stateObject);
s = f.Result;
Assert.Equal("z", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// one more with creation option overload
f = Task.Factory.FromAsync<int, string>(
fac.StartRead,
fac.EndRead,
1,
stateObject,
TaskCreationOptions.None);
s = f.Result;
Assert.Equal("z", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 0-arg value option
f = Task.Factory.FromAsync<string>(
fac.StartRead,
fac.EndRead,
stateObject);
s = f.Result;
Assert.Equal("zz", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
//one more with Creation options overload
f = Task.Factory.FromAsync<string>(
fac.StartRead,
fac.EndRead,
stateObject,
TaskCreationOptions.None);
s = f.Result;
Assert.Equal(string.Empty, s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Inject a few more characters into the buffer
fac.EndWrite(fac.StartWrite("0123456789", null, null));
// Exercise value overload that accepts an IAsyncResult instead of a beginMethod.
f = Task<string>.Factory.FromAsync(
fac.StartRead(4, null, null),
fac.EndRead);
s = f.Result;
Assert.Equal("0123", s);
f = Task.Factory.FromAsync<string>(
fac.StartRead(4, null, null),
fac.EndRead);
s = f.Result;
Assert.Equal("4567", s);
// Test Exception handling from beginMethod
Assert.ThrowsAsync<NullReferenceException>(() =>
t = Task.Factory.FromAsync(
fac.StartWrite,
fac.EndWrite,
(string)null, // will cause null.Length to be dereferenced
null));
// Test Exception handling from asynchronous logic
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
10,
carray,
200, // offset past end of array
null);
Assert.Throws<AggregateException>(() =>
check = f.Result);
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, null, TaskCreationOptions.LongRunning));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, null, TaskCreationOptions.PreferFairness));
// Empty the buffer, then inject a few more characters into the buffer
fac.ResetStateTo("0123456789");
Task asyncTask = null;
//
// Now check that the endMethod throwing an OCE correctly results in a canceled task.
//
// Test IAsyncResult overload that returns Task
asyncTask = Task.Factory.FromAsync(
fac.StartWrite("abc", null, null),
delegate (IAsyncResult iar) { throw new OperationCanceledException("FromAsync"); });
AggregateException ae = Assert.Throws<AggregateException>(() =>
{
asyncTask.Wait();
});
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
Assert.Equal(TaskStatus.Canceled, asyncTask.Status);
// Test beginMethod overload that returns Task
asyncTask = Task.Factory.FromAsync(
fac.StartWrite,
delegate (IAsyncResult iar) { throw new OperationCanceledException("FromAsync"); },
"abc",
null);
ae = Assert.Throws<AggregateException>(() =>
{
asyncTask.Wait();
});
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
Assert.Equal(TaskStatus.Canceled, asyncTask.Status);
// Test IAsyncResult overload that returns Task<string>
Task<string> asyncFuture = null;
asyncFuture = Task<string>.Factory.FromAsync(
fac.StartRead(3, null, null),
delegate (IAsyncResult iar) { throw new OperationCanceledException("FromAsync"); });
ae = Assert.Throws<AggregateException>(() =>
{
asyncTask.Wait();
});
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
Assert.Equal(TaskStatus.Canceled, asyncTask.Status);
// Test beginMethod overload that returns Task<string>
asyncFuture = null;
asyncFuture = Task<string>.Factory.FromAsync(
fac.StartRead,
delegate (IAsyncResult iar) { throw new OperationCanceledException("FromAsync"); },
3, null);
ae = Assert.Throws<AggregateException>(() =>
{
asyncFuture.Wait();
});
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
Assert.Equal(TaskStatus.Canceled, asyncFuture.Status);
//
// Make sure that tasks aren't left hanging if StartXYZ() throws an exception
//
Task foo = Task.Factory.StartNew(delegate
{
// Every one of these should throw an exception from StartWrite/StartRead. Test to
// see that foo is allowed to complete (i.e., no dangling attached tasks from FromAsync()
// calls.
Task foo1 = Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, (string)null, null, TaskCreationOptions.AttachedToParent);
Task foo2 = Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, (string)null, 4, null, TaskCreationOptions.AttachedToParent);
Task foo3 = Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, (string)null, 4, 4, null, TaskCreationOptions.AttachedToParent);
Task<string> foo4 = Task<string>.Factory.FromAsync(fac.StartRead, fac.EndRead, -1, null, TaskCreationOptions.AttachedToParent);
Task<string> foo5 = Task<string>.Factory.FromAsync(fac.StartRead, fac.EndRead, -1, (char[])null, null, TaskCreationOptions.AttachedToParent);
Task<string> foo6 = Task<string>.Factory.FromAsync(fac.StartRead, fac.EndRead, -1, (char[])null, 200, null, TaskCreationOptions.AttachedToParent);
});
Debug.WriteLine("RunAPMFactoryTests: Waiting on task w/ faulted FromAsync() calls. If we hang, there is a problem");
Assert.Throws<AggregateException>(() =>
{
foo.Wait();
});
}
// This class is used in testing APM Factory tests.
private class FakeAsyncClass
{
private List<char> _list = new List<char>();
public override string ToString()
{
StringBuilder sb = new StringBuilder();
lock (_list)
{
for (int i = 0; i < _list.Count; i++)
sb.Append(_list[i]);
}
return sb.ToString();
}
// Silly use of Write, but I wanted to test no-argument StartXXX handling.
public IAsyncResult StartWrite(AsyncCallback cb, object o)
{
return StartWrite("", 0, 0, cb, o);
}
public IAsyncResult StartWrite(string s, AsyncCallback cb, object o)
{
return StartWrite(s, 0, s.Length, cb, o);
}
public IAsyncResult StartWrite(string s, int length, AsyncCallback cb, object o)
{
return StartWrite(s, 0, length, cb, o);
}
public IAsyncResult StartWrite(string s, int offset, int length, AsyncCallback cb, object o)
{
myAsyncResult mar = new myAsyncResult(cb, o);
// Allow for exception throwing to test our handling of that.
if (s == null)
throw new ArgumentNullException(nameof(s));
Task t = Task.Factory.StartNew(delegate
{
//Task.Delay(100).Wait();
try
{
lock (_list)
{
for (int i = 0; i < length; i++)
_list.Add(s[i + offset]);
}
mar.Signal();
}
catch (Exception e) { mar.Signal(e); }
});
return mar;
}
public void EndWrite(IAsyncResult iar)
{
myAsyncResult mar = iar as myAsyncResult;
mar.Wait();
if (mar.IsFaulted)
throw (mar.Exception);
}
public IAsyncResult StartRead(AsyncCallback cb, object o)
{
return StartRead(128 /*=maxbytes*/, null, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, AsyncCallback cb, object o)
{
return StartRead(maxBytes, null, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, char[] buf, AsyncCallback cb, object o)
{
return StartRead(maxBytes, buf, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, char[] buf, int offset, AsyncCallback cb, object o)
{
myAsyncResult mar = new myAsyncResult(cb, o);
// Allow for exception throwing to test our handling of that.
if (maxBytes == -1)
throw new ArgumentException("Value was not valid", nameof(maxBytes));
Task t = Task.Factory.StartNew(delegate
{
//Thread.Sleep(100);
StringBuilder sb = new StringBuilder();
int bytesRead = 0;
try
{
lock (_list)
{
while ((_list.Count > 0) && (bytesRead < maxBytes))
{
sb.Append(_list[0]);
if (buf != null) { buf[offset] = _list[0]; offset++; }
_list.RemoveAt(0);
bytesRead++;
}
}
mar.SignalState(sb.ToString());
}
catch (Exception e) { mar.Signal(e); }
});
return mar;
}
public string EndRead(IAsyncResult iar)
{
myAsyncResult mar = iar as myAsyncResult;
if (mar.IsFaulted)
throw (mar.Exception);
return (string)mar.AsyncState;
}
public void ResetStateTo(string s)
{
_list.Clear();
for (int i = 0; i < s.Length; i++)
_list.Add(s[i]);
}
}
// This is an internal class used for a concrete IAsyncResult in the APM Factory tests.
private class myAsyncResult : IAsyncResult
{
private volatile int _isCompleted;
private ManualResetEvent _asyncWaitHandle;
private AsyncCallback _callback;
private object _asyncState;
private Exception _exception;
public myAsyncResult(AsyncCallback cb, object o)
{
_isCompleted = 0;
_asyncWaitHandle = new ManualResetEvent(false);
_callback = cb;
_asyncState = o;
_exception = null;
}
public bool IsCompleted
{
get { return (_isCompleted == 1); }
}
public bool CompletedSynchronously
{
get { return false; }
}
public WaitHandle AsyncWaitHandle
{
get { return _asyncWaitHandle; }
}
public object AsyncState
{
get { return _asyncState; }
}
public void Signal()
{
_isCompleted = 1;
_asyncWaitHandle.Set();
if (_callback != null)
_callback(this);
}
public void Signal(Exception e)
{
_exception = e;
Signal();
}
public void SignalState(object o)
{
_asyncState = o;
Signal();
}
public void Wait()
{
_asyncWaitHandle.WaitOne();
if (_exception != null)
throw (_exception);
}
public bool IsFaulted
{
get { return ((_isCompleted == 1) && (_exception != null)); }
}
public Exception Exception
{
get { return _exception; }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using SteamKit2;
using SteamTrade.Exceptions;
namespace SteamTrade
{
public partial class Trade
{
#region Static Public data
public static Schema CurrentSchema = null;
#endregion
// current bot's sid
SteamID mySteamId;
// If the bot is ready.
bool meIsReady = false;
// If the other user is ready.
bool otherIsReady = false;
// Whether or not the trade actually started.
bool tradeStarted = false;
Dictionary<int, ulong> myOfferedItems;
List<ulong> steamMyOfferedItems;
// Internal properties needed for Steam API.
string apiKey;
int numEvents;
internal Trade (SteamID me, SteamID other, string sessionId, string token, string apiKey, Inventory myInventory, Inventory otherInventory)
{
mySteamId = me;
OtherSID = other;
this.sessionId = sessionId;
this.steamLogin = token;
this.apiKey = apiKey;
OtherOfferedItems = new List<ulong> ();
myOfferedItems = new Dictionary<int, ulong> ();
steamMyOfferedItems = new List<ulong> ();
OtherInventory = otherInventory;
MyInventory = myInventory;
Init ();
}
#region Public Properties
/// <summary>Gets the other user's steam ID.</summary>
public SteamID OtherSID { get; private set; }
/// <summary>
/// Gets the bot's Steam ID.
/// </summary>
public SteamID MySteamId
{
get { return mySteamId; }
}
/// <summary>
/// Gets the inventory of the other user.
/// </summary>
public Inventory OtherInventory { get; private set; }
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
public Inventory MyInventory { get; private set; }
/// <summary>
/// Gets the items the user has offered, by itemid.
/// </summary>
/// <value>
/// The other offered items.
/// </value>
public List<ulong> OtherOfferedItems { get; private set; }
/// <summary>
/// Gets a value indicating if the other user is ready to trade.
/// </summary>
public bool OtherIsReady
{
get { return otherIsReady; }
}
/// <summary>
/// Gets a value indicating if the bot is ready to trade.
/// </summary>
public bool MeIsReady
{
get { return meIsReady; }
}
/// <summary>
/// Gets a value indicating if a trade has started.
/// </summary>
public bool TradeStarted
{
get { return tradeStarted; }
}
/// <summary>
/// Gets a value indicating if the remote trading partner cancelled the trade.
/// </summary>
public bool OtherUserCancelled { get; private set; }
#endregion
#region Public Events
public delegate void CloseHandler ();
public delegate void ErrorHandler (string error);
public delegate void TimeoutHandler ();
public delegate void SuccessfulInit ();
public delegate void UserAddItemHandler (Schema.Item schemaItem,Inventory.Item inventoryItem);
public delegate void UserRemoveItemHandler (Schema.Item schemaItem,Inventory.Item inventoryItem);
public delegate void MessageHandler (string msg);
public delegate void UserSetReadyStateHandler (bool ready);
public delegate void UserAcceptHandler ();
/// <summary>
/// When the trade closes, this is called. It doesn't matter
/// whether or not it was a timeout or an error, this is called
/// to close the trade.
/// </summary>
public event CloseHandler OnClose;
/// <summary>
/// This is for handling errors that may occur, like inventories
/// not loading.
/// </summary>
public event ErrorHandler OnError;
/// <summary>
/// This occurs after Inventories have been loaded.
/// </summary>
public event SuccessfulInit OnAfterInit;
/// <summary>
/// This occurs when the other user adds an item to the trade.
/// </summary>
public event UserAddItemHandler OnUserAddItem;
/// <summary>
/// This occurs when the other user removes an item from the
/// trade.
/// </summary>
public event UserAddItemHandler OnUserRemoveItem;
/// <summary>
/// This occurs when the user sends a message to the bot over
/// trade.
/// </summary>
public event MessageHandler OnMessage;
/// <summary>
/// This occurs when the user sets their ready state to either
/// true or false.
/// </summary>
public event UserSetReadyStateHandler OnUserSetReady;
/// <summary>
/// This occurs when the user accepts the trade.
/// </summary>
public event UserAcceptHandler OnUserAccept;
#endregion
/// <summary>
/// Cancel the trade. This calls the OnClose handler, as well.
/// </summary>
public bool CancelTrade ()
{
bool ok = CancelTradeWebCmd ();
if (!ok)
throw new TradeException ("The Web command to cancel the trade failed");
if (OnClose != null)
OnClose ();
return true;
}
/// <summary>
/// Adds a specified item by its itemid.
/// </summary>
/// <returns><c>false</c> if the item was not found in the inventory.</returns>
public bool AddItem (ulong itemid)
{
if (MyInventory.GetItem (itemid) == null)
return false;
var slot = NextTradeSlot ();
bool ok = AddItemWebCmd (itemid, slot);
if (!ok)
throw new TradeException ("The Web command to add the Item failed");
myOfferedItems [slot] = itemid;
return true;
}
/// <summary>
/// Adds a single item by its Defindex.
/// </summary>
/// <returns>
/// <c>true</c> if an item was found with the corresponding
/// defindex, <c>false</c> otherwise.
/// </returns>
public bool AddItemByDefindex (int defindex)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
foreach (Inventory.Item item in items)
{
if (!myOfferedItems.ContainsValue (item.Id))
{
return AddItem (item.Id);
}
}
return false;
}
/// <summary>
/// Adds an entire set of items by Defindex to each successive
/// slot in the trade.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToAdd">The upper limit on amount of items to add. <c>0</c> to add all items.</param>
/// <returns>Number of items added.</returns>
public uint AddAllItemsByDefindex (int defindex, uint numToAdd = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
uint added = 0;
foreach (Inventory.Item item in items)
{
if (item != null && !myOfferedItems.ContainsValue (item.Id))
{
bool success = AddItem (item.Id);
if (success)
added++;
if (numToAdd > 0 && added >= numToAdd)
return added;
}
}
return added;
}
/// <summary>
/// Removes an item by its itemid.
/// </summary>
/// <returns><c>false</c> the item was not found in the trade.</returns>
public bool RemoveItem (ulong itemid)
{
int? slot = GetItemSlot (itemid);
if (!slot.HasValue)
return false;
bool ok = RemoveItemWebCmd (itemid, slot.Value);
if (!ok)
throw new TradeException ("The web command to remove the item failed.");
myOfferedItems.Remove (slot.Value);
return true;
}
/// <summary>
/// Removes an item with the given Defindex from the trade.
/// </summary>
/// <returns>
/// Returns <c>true</c> if it found a corresponding item; <c>false</c> otherwise.
/// </returns>
public bool RemoveItemByDefindex (int defindex)
{
foreach (ulong id in myOfferedItems.Values)
{
Inventory.Item item = MyInventory.GetItem (id);
if (item.Defindex == defindex)
{
return RemoveItem (item.Id);
}
}
return false;
}
/// <summary>
/// Removes an entire set of items by Defindex.
/// </summary>
/// <param name="defindex">The defindex. (ex. 5022 = crates)</param>
/// <param name="numToRemove">The upper limit on amount of items to remove. <c>0</c> to remove all items.</param>
/// <returns>Number of items removed.</returns>
public uint RemoveAllItemsByDefindex (int defindex, uint numToRemove = 0)
{
List<Inventory.Item> items = MyInventory.GetItemsByDefindex (defindex);
uint removed = 0;
foreach (Inventory.Item item in items)
{
if (item != null && !myOfferedItems.ContainsValue (item.Id))
{
bool success = RemoveItem (item.Id);
if (success)
removed++;
if (numToRemove > 0 && removed >= numToRemove)
return removed;
}
}
return removed;
}
/// <summary>
/// Sends a message to the user over the trade chat.
/// </summary>
public bool SendMessage (string msg)
{
bool ok = SendMessageWebCmd (msg);
if (!ok)
throw new TradeException ("The web command to send the trade message failed.");
return true;
}
/// <summary>
/// Sets the bot to a ready status.
/// </summary>
public bool SetReady (bool ready)
{
// testing
ValidateLocalTradeItems ();
bool ok = SetReadyWebCmd (ready);
if (!ok)
throw new TradeException ("The web command to set trade ready state failed.");
return true;
}
/// <summary>
/// Accepts the trade from the user. Returns a deserialized
/// JSON object.
/// </summary>
public bool AcceptTrade ()
{
ValidateLocalTradeItems ();
bool ok = AcceptTradeWebCmd ();
if (!ok)
throw new TradeException ("The web command to accept the trade failed.");
return true;
}
/// <summary>
/// This updates the trade. This is called at an interval of a
/// default of 800ms, not including the execution time of the
/// method itself.
/// </summary>
/// <returns><c>true</c> if the other trade partner performed an action; otherwise <c>false</c>.</returns>
public bool Poll ()
{
bool otherDidSomething = false;
if (!TradeStarted)
{
tradeStarted = true;
// since there is no feedback to let us know that the trade
// is fully initialized we assume that it is when we start polling.
if (OnAfterInit != null)
OnAfterInit ();
}
StatusObj status = GetStatus ();
if (status == null)
throw new TradeException ("The web command to get the trade status failed.");
// I've noticed this when the trade is cancelled.
if (status.trade_status == 3)
{
if (OnError != null)
OnError ("Trade was cancelled by other user.");
OtherUserCancelled = true;
return otherDidSomething;
}
if (status.events != null && numEvents != status.events.Length)
{
int numLoops = status.events.Length - numEvents;
numEvents = status.events.Length;
for (int i = numLoops; i > 0; i--)
{
int EventID;
if (numLoops == 1)
{
EventID = numEvents - 1;
}
else
{
EventID = numEvents - i;
}
bool isBot = status.events [EventID].steamid == MySteamId.ConvertToUInt64 ().ToString ();
/*
*
* Trade Action ID's
*
* 0 = Add item (itemid = "assetid")
* 1 = remove item (itemid = "assetid")
* 2 = Toggle ready
* 3 = Toggle not ready
* 4
* 5
* 6
* 7 = Chat (message = "text")
*
*/
ulong itemID;
switch (status.events [EventID].action)
{
case 0:
itemID = (ulong)status.events [EventID].assetid;
if (isBot)
{
steamMyOfferedItems.Add (itemID);
ValidateSteamItemChanged (itemID, true);
}
else
{
OtherOfferedItems.Add (itemID);
Inventory.Item item = OtherInventory.GetItem (itemID);
Schema.Item schemaItem = CurrentSchema.GetItem (item.Defindex);
OnUserAddItem (schemaItem, item);
}
break;
case 1:
itemID = (ulong)status.events [EventID].assetid;
if (isBot)
{
steamMyOfferedItems.Remove (itemID);
ValidateSteamItemChanged (itemID, false);
}
else
{
OtherOfferedItems.Remove (itemID);
Inventory.Item item = OtherInventory.GetItem (itemID);
Schema.Item schemaItem = CurrentSchema.GetItem (item.Defindex);
OnUserRemoveItem (schemaItem, item);
}
break;
case 2:
if (!isBot)
{
otherIsReady = true;
OnUserSetReady (true);
}
break;
case 3:
if (!isBot)
{
otherIsReady = false;
OnUserSetReady (false);
}
break;
case 4:
if (!isBot)
{
OnUserAccept ();
}
break;
case 7:
if (!isBot)
{
OnMessage (status.events [EventID].text);
}
break;
default:
// Todo: add an OnWarning or similar event
if (OnError != null)
OnError ("Unkown Event ID: " + status.events [EventID].action);
break;
}
if (!isBot)
otherDidSomething = true;
}
}
// Update Local Variables
if (status.them != null)
{
otherIsReady = status.them.ready == 1 ? true : false;
meIsReady = status.me.ready == 1 ? true : false;
}
// Update version
if (status.newversion)
{
Version = status.version;
}
if (status.logpos != 0)
{
LogPos = status.logpos;
}
return otherDidSomething;
}
int NextTradeSlot ()
{
int slot = 0;
while (myOfferedItems.ContainsKey (slot))
{
slot++;
}
return slot;
}
int? GetItemSlot (ulong itemid)
{
foreach (int slot in myOfferedItems.Keys)
{
if (myOfferedItems [slot] == itemid)
{
return slot;
}
}
return null;
}
void ValidateSteamItemChanged (ulong itemid, bool wasAdded)
{
// checks to make sure that the Trade polling saw
// the correct change for the given item.
// check if the correct item was added
if (wasAdded && !myOfferedItems.ContainsValue (itemid))
throw new TradeException ("Steam Trade had an invalid item added: " + itemid);
// check if the correct item was removed
if (!wasAdded && myOfferedItems.ContainsValue (itemid))
throw new TradeException ("Steam Trade had an invalid item removed: " + itemid);
}
void ValidateLocalTradeItems ()
{
if (myOfferedItems.Count != steamMyOfferedItems.Count)
{
throw new TradeException ("Error validating local copy of items in the trade: Count mismatch");
}
foreach (ulong id in myOfferedItems.Values)
{
if (!steamMyOfferedItems.Contains (id))
throw new TradeException ("Error validating local copy of items in the trade: Item was not in the Steam Copy.");
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
using OpenLiveWriter.PostEditor.BlogProviderButtons;
namespace OpenLiveWriter.PostEditor.Configuration.Wizard
{
/// <summary>
/// Summary description for WelcomeToBlogControl.
/// </summary>
internal class WeblogConfigurationWizardPanelBasicInfo : WeblogConfigurationWizardPanel, IAccountBasicInfoProvider
{
private System.Windows.Forms.Label labelPassword;
private System.Windows.Forms.TextBox textBoxPassword;
private System.Windows.Forms.TextBox textBoxUsername;
private System.Windows.Forms.Label labelUsername;
private System.Windows.Forms.TextBox textBoxHomepageUrl;
private System.Windows.Forms.Label labelHomepageUrl;
private System.Windows.Forms.Label labelHomepageUrl2;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private System.Windows.Forms.CheckBox checkBoxSavePassword;
public WeblogConfigurationWizardPanelBasicInfo()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.textBoxHomepageUrl.RightToLeft = RightToLeft.No;
if (BidiHelper.IsRightToLeft)
textBoxHomepageUrl.TextAlign = HorizontalAlignment.Right;
this.labelHeader.Text = Res.Get(StringId.CWBasicHeader);
this.labelHomepageUrl.Text = Res.Get(StringId.CWBasicHomepage);
this.labelHomepageUrl2.Text = Res.Get(StringId.CWBasicHomepage2);
this.labelUsername.Text = Res.Get(StringId.UsernameLabel);
this.labelPassword.Text = Res.Get(StringId.PasswordLabel);
this.textBoxPassword.PasswordChar = Res.PasswordChar;
this.checkBoxSavePassword.Text = Res.Get(StringId.RememberPassword);
textBoxPassword.PasswordChar = Res.PasswordChar;
textBoxHomepageUrl.AccessibleName = ControlHelper.ToAccessibleName(Res.Get(StringId.CWBasicHomepage));
}
public override void NaturalizeLayout()
{
if (!DesignMode)
{
MaximizeWidth(labelHomepageUrl);
MaximizeWidth(labelHomepageUrl2);
MaximizeWidth(checkBoxSavePassword);
LayoutHelper.NaturalizeHeightAndDistribute(3, labelHomepageUrl, textBoxHomepageUrl, labelHomepageUrl2);
LayoutHelper.NaturalizeHeightAndDistribute(3, labelUsername, textBoxUsername);
LayoutHelper.NaturalizeHeightAndDistribute(3, labelPassword, textBoxPassword, checkBoxSavePassword);
LayoutHelper.DistributeVertically(10, false,
new ControlGroup(labelHomepageUrl, textBoxHomepageUrl, labelHomepageUrl2),
new ControlGroup(labelUsername, textBoxUsername),
new ControlGroup(labelPassword, textBoxPassword, checkBoxSavePassword)
);
}
}
public override ConfigPanelId? PanelId
{
get { return ConfigPanelId.OtherBasicInfo; }
}
public override bool ShowProxySettingsLink
{
get { return true; }
}
public IBlogProviderAccountWizardDescription ProviderAccountWizard
{
set { }
}
public string AccountId
{
set { }
}
public string HomepageUrl
{
get { return UrlHelper.FixUpUrl(textBoxHomepageUrl.Text); }
set { textBoxHomepageUrl.Text = value; }
}
public bool SavePassword
{
get { return checkBoxSavePassword.Checked; }
set { checkBoxSavePassword.Checked = value; }
}
public bool ForceManualConfiguration
{
get { return false; }
set { }
}
public IBlogCredentials Credentials
{
get
{
TemporaryBlogCredentials credentials = new TemporaryBlogCredentials();
credentials.Username = textBoxUsername.Text.Trim();
credentials.Password = textBoxPassword.Text.Trim();
return credentials;
}
set
{
textBoxUsername.Text = value.Username;
textBoxPassword.Text = value.Password;
}
}
public bool IsDirty(TemporaryBlogSettings settings)
{
return
!UrlHelper.UrlsAreEqual(HomepageUrl, settings.HomepageUrl) ||
!BlogCredentialsHelper.CredentialsAreEqual(Credentials, settings.Credentials);
}
public BlogInfo BlogAccount
{
get
{
return null;
}
}
public override bool ValidatePanel()
{
string homepageUrl = HomepageUrl;
if (homepageUrl == String.Empty)
{
ShowValidationError(textBoxHomepageUrl, MessageId.HomepageUrlRequired);
return false;
}
if (!UrlHelper.IsUrl(homepageUrl))
{
ShowValidationError(textBoxHomepageUrl, MessageId.HomepageUrlInvalid);
return false;
}
if (textBoxUsername.Text.Trim() == String.Empty)
{
ShowValidationError(textBoxUsername, MessageId.UsernameAndPasswordRequired);
return false;
}
if (textBoxPassword.Text.Trim() == String.Empty)
{
ShowValidationError(textBoxPassword, MessageId.UsernameAndPasswordRequired);
return false;
}
if (IsWordPress(homepageUrl))
{
ShowValidationError(textBoxHomepageUrl, MessageId.WordpressHomepageWrong, ApplicationEnvironment.ProductNameQualified);
return false;
}
return true;
}
private static bool IsWordPress(string url)
{
try
{
return Regex.IsMatch(
new Uri(url).Host,
@"^(www\.)?wordpress\.com$",
RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
}
catch (Exception e)
{
Trace.Fail(e.ToString());
return false;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.checkBoxSavePassword = new System.Windows.Forms.CheckBox();
this.labelPassword = new System.Windows.Forms.Label();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.textBoxUsername = new System.Windows.Forms.TextBox();
this.labelUsername = new System.Windows.Forms.Label();
this.textBoxHomepageUrl = new System.Windows.Forms.TextBox();
this.labelHomepageUrl = new System.Windows.Forms.Label();
this.labelHomepageUrl2 = new System.Windows.Forms.Label();
this.panelMain.SuspendLayout();
this.SuspendLayout();
panelMain.Controls.Add(labelHomepageUrl);
panelMain.Controls.Add(textBoxHomepageUrl);
panelMain.Controls.Add(labelHomepageUrl2);
panelMain.Controls.Add(labelUsername);
panelMain.Controls.Add(textBoxUsername);
panelMain.Controls.Add(labelPassword);
panelMain.Controls.Add(textBoxPassword);
panelMain.Controls.Add(checkBoxSavePassword);
//
// checkBoxSavePassword
//
this.checkBoxSavePassword.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBoxSavePassword.Location = new System.Drawing.Point(20, 98);
this.checkBoxSavePassword.Name = "checkBoxSavePassword";
this.checkBoxSavePassword.Size = new System.Drawing.Size(165, 26);
this.checkBoxSavePassword.TabIndex = 5;
this.checkBoxSavePassword.Text = "&Remember my password";
this.checkBoxSavePassword.TextAlign = System.Drawing.ContentAlignment.TopLeft;
//
// labelPassword
//
this.labelPassword.AutoSize = true;
this.labelPassword.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelPassword.Location = new System.Drawing.Point(20, 57);
this.labelPassword.Name = "labelPassword";
this.labelPassword.Size = new System.Drawing.Size(73, 17);
this.labelPassword.TabIndex = 3;
this.labelPassword.Text = "&Password:";
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(20, 74);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.PasswordChar = '*';
this.textBoxPassword.Size = new System.Drawing.Size(208, 22);
this.textBoxPassword.TabIndex = 4;
this.textBoxPassword.Enter += new System.EventHandler(this.textBoxPassword_Enter);
//
// textBoxUsername
//
this.textBoxUsername.Location = new System.Drawing.Point(20, 74);
this.textBoxUsername.Name = "textBoxUsername";
this.textBoxUsername.Size = new System.Drawing.Size(208, 22);
this.textBoxUsername.TabIndex = 2;
this.textBoxUsername.Enter += new System.EventHandler(this.textBoxUsername_Enter);
//
// labelUsername
//
this.labelUsername.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelUsername.Location = new System.Drawing.Point(20, 57);
this.labelUsername.Name = "labelUsername";
this.labelUsername.Size = new System.Drawing.Size(167, 13);
this.labelUsername.TabIndex = 1;
this.labelUsername.Text = "&Username:";
//
// textBoxHomepageUrl
//
this.textBoxHomepageUrl.Location = new System.Drawing.Point(20, 74);
this.textBoxHomepageUrl.Name = "textBoxHomepageUrl";
this.textBoxHomepageUrl.Size = new System.Drawing.Size(275, 22);
this.textBoxHomepageUrl.TabIndex = 2;
this.textBoxHomepageUrl.Enter += new System.EventHandler(this.textBoxHomepageUrl_Enter);
this.textBoxHomepageUrl.Leave += new System.EventHandler(this.textBoxHomepageUrl_Leave);
//
// labelHomepageUrl
//
this.labelHomepageUrl.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelHomepageUrl.Location = new System.Drawing.Point(20, 0);
this.labelHomepageUrl.Name = "labelHomepageUrl";
this.labelHomepageUrl.Size = new System.Drawing.Size(167, 13);
this.labelHomepageUrl.TabIndex = 1;
this.labelHomepageUrl.Text = "Web &address of your blog:";
//
// labelHomepageUrl2
//
this.labelHomepageUrl2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelHomepageUrl2.ForeColor = SystemColors.GrayText;
this.labelHomepageUrl2.Location = new System.Drawing.Point(20, 57);
this.labelHomepageUrl2.Name = "labelHomepageUrl2";
this.labelHomepageUrl2.Size = new System.Drawing.Size(167, 13);
this.labelHomepageUrl2.TabIndex = 1;
this.labelHomepageUrl2.Text = "This is the URL that visitors use to read your blog";
//
// WeblogConfigurationWizardPanelBasicInfo
//
this.Name = "WeblogConfigurationWizardPanelBasicInfo";
this.Size = new System.Drawing.Size(432, 244);
this.panelMain.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void textBoxHomepageUrl_Enter(object sender, EventArgs e)
{
textBoxHomepageUrl.SelectAll();
}
private void textBoxHomepageUrl_Leave(object sender, EventArgs e)
{
// adds http:// if necessary
HomepageUrl = HomepageUrl;
}
private void textBoxUsername_Enter(object sender, EventArgs e)
{
textBoxUsername.SelectAll();
}
private void textBoxPassword_Enter(object sender, EventArgs e)
{
textBoxPassword.SelectAll();
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmMakeRepairItem : System.Windows.Forms.Form
{
int gStockItemID;
int gPromotionID;
int gQuantity;
private void loadLanguage()
{
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1255;
//Make Finished Product|Checked
if (modRecordSet.rsLang.RecordCount){My.MyProject.Forms.frmMakeFinishItem.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;My.MyProject.Forms.frmMakeFinishItem.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//lblPComp = No Code [Please enter the Qty you wish to make]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblPComp.Caption = rsLang("LanguageLayoutLnk_Description"): lblPComp.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1935;
//Stock Item Name|Checked
if (modRecordSet.rsLang.RecordCount){_LBL_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_LBL_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//_lbl_2 = No Code [Item Qty]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1151;
//Price|Checked
if (modRecordSet.rsLang.RecordCount){_LBL_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_LBL_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmMakeRepairItem.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
public void makeItem()
{
int lID = 0;
ADODB.Recordset rs = default(ADODB.Recordset);
lID = My.MyProject.Forms.frmStockList.getItem();
if (lID != 0) {
// ERROR: Not supported in C#: OnErrorStatement
loadItem(lID);
//adoPrimaryRS("PromotionID"), lID
}
}
private void loadData()
{
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rj = default(ADODB.Recordset);
rs = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Name, CatalogueChannelLnk.CatalogueChannelLnk_Quantity, CatalogueChannelLnk.CatalogueChannelLnk_Price FROM (Catalogue INNER JOIN StockItem ON (StockItem.StockItem_Quantity = Catalogue.Catalogue_Quantity) AND (Catalogue.Catalogue_StockItemID = StockItem.StockItemID)) INNER JOIN CatalogueChannelLnk ON (Catalogue.Catalogue_StockItemID = CatalogueChannelLnk.CatalogueChannelLnk_StockItemID) AND (Catalogue.Catalogue_Quantity = CatalogueChannelLnk.CatalogueChannelLnk_Quantity) WHERE (((StockItem.StockItemID)=" + gStockItemID + ") AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1));");
if (rs.RecordCount) {
lblStockItem.Text = rs.Fields("StockItem_Name").Value;
//lblPromotion.Caption = rs("Promotion_Name")
txtPrice.Text = Convert.ToString(rs.Fields("CatalogueChannelLnk_Price").Value * 100);
txtPrice_Leave(txtPrice, new System.EventArgs());
//cmbQuantity.Tag = rs("CatalogueChannelLnk_Quantity")
loadLanguage();
ShowDialog();
} else {
this.Close();
return;
}
}
//Public Sub loadItem(promotionID As Long, stockitemID As Long, Optional quantity As Long)
public void loadItem(ref int stockitemID, ref int quantity = 0)
{
gStockItemID = stockitemID;
//gPromotionID = promotionID
gQuantity = quantity;
//lblPComp.Caption = frmStockTransfer.lblPComp.Caption
loadData();
//show 1
}
private void frmMakeRepairItem_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
bool mbAddNewFlag = false;
bool mbEditFlag = false;
if (mbEditFlag | mbAddNewFlag)
goto EventExitSub;
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
EventExitSub:
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
bool mbDataChanged = false;
int mvBookMark = 0;
ADODB.Recordset adoPrimaryRS = default(ADODB.Recordset);
bool mbAddNewFlag = false;
bool mbEditFlag = false;
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
if (mvBookMark > 0) {
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
mbDataChanged = false;
}
this.Close();
}
//UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
private bool update_Renamed()
{
bool functionReturnValue = false;
int gID = 0;
string strFldName = null;
// ERROR: Not supported in C#: OnErrorStatement
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rj = default(ADODB.Recordset);
ADODB.Recordset adoPrimaryRS = default(ADODB.Recordset);
string sql = null;
decimal lQuantity = default(decimal);
// Long
rs = modRecordSet.getRS(ref "SELECT * from RecipeStockitemLnk Where RecipeStockitemLnk_RecipeID = " + gStockItemID + ";");
if (rs.RecordCount > 0) {
//If MsgBox("You have " & rs.RecordCount & " enabled items in database. Do you want to make them Zero?", vbOKCancel) = vbOK Then
strFldName = "HandHeldID Number,Handheld_Barcode Text(50), Quantity Currency";
modRecordSet.cnnDB.Execute("CREATE TABLE " + "HandheldMakeFinish" + " (" + strFldName + ")");
System.Windows.Forms.Application.DoEvents();
sql = "INSERT INTO HandheldMakeFinish (HandHeldID,Handheld_Barcode,Quantity) VALUES (" + gStockItemID + ", 0, " + Convert.ToDecimal(txtQty.Text) + ")";
modRecordSet.cnnDB.Execute(sql);
System.Windows.Forms.Application.DoEvents();
while (rs.EOF == false) {
sql = "INSERT INTO HandheldMakeFinish (HandHeldID,Handheld_Barcode,Quantity) VALUES (" + rs.Fields("RecipeStockitemLnk_StockitemID").Value + ", 0, " + (0 - (rs.Fields("RecipeStockitemLnk_Quantity").Value * Convert.ToDecimal(txtQty.Text))) + ")";
modRecordSet.cnnDB.Execute(sql);
rs.moveNext();
}
//Else
// Exit Sub
//End If
} else {
Interaction.MsgBox("This Product does not have any Recipe.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, _4PosBackOffice.NET.My.MyProject.Application.Info.Title);
return functionReturnValue;
}
modRecordSet.cnnDB.Execute("INSERT INTO StockGroup (StockGroup_Name) VALUES ('HandheldMakeFinish')");
modApplication.stTableName = "HandheldMakeFinish";
rj = modRecordSet.getRS(ref "SELECT StockGroup.StockGroupID, StockGroup.StockGroup_Name From StockGroup WHERE StockGroup.StockGroup_Name = 'HandheldMakeFinish';");
gID = rj.Fields("StockGroupID").Value;
//snap shot
modRecordSet.cnnDB.Execute("UPDATE Company SET Company.Company_StockTakeDate = now();");
modRecordSet.cnnDB.Execute("DELETE FROM StockTake WHERE (StockTake_WarehouseID = 2)");
modRecordSet.cnnDB.Execute("INSERT INTO StockTake ( StockTake_StockItemID, StockTake_WarehouseID, StockTake_Quantity, StockTake_Adjustment ) SELECT StockItem.StockItemID, 2 AS warehouse, 0 AS quantity, 0 AS adjustment FROM StockItem;");
modRecordSet.cnnDB.Execute("UPDATE StockTake INNER JOIN WarehouseStockItemLnk ON (StockTake.StockTake_StockItemID = WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID) AND (StockTake.StockTake_WarehouseID = WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID) SET StockTake.StockTake_Quantity = [WarehouseStockItemLnk]![WarehouseStockItemLnk_Quantity] WHERE (((WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID)=2));");
modRecordSet.cnnDB.Execute("DELETE FROM StockTakeDeposit");
modRecordSet.cnnDB.Execute("INSERT INTO StockTakeDeposit ( StockTakeDeposit_WarehouseID, StockTakeDeposit_DepositID, StockTakeDeposit_DepositTypeID, StockTakeDeposit_Quantity, StockTakeDeposit_Adjustment ) SELECT WarehouseDepositItemLnk.WarehouseDepositItemLnk_WarehouseID, WarehouseDepositItemLnk.WarehouseDepositItemLnk_DepositID, WarehouseDepositItemLnk.WarehouseDepositItemLnk_DepositTypeID, WarehouseDepositItemLnk.WarehouseDepositItemLnk_Quantity, WarehouseDepositItemLnk.WarehouseDepositItemLnk_Quantity FROM WarehouseDepositItemLnk INNER JOIN DISPLAY_Deposits ON (DISPLAY_Deposits.type = WarehouseDepositItemLnk.WarehouseDepositItemLnk_DepositTypeID) AND (WarehouseDepositItemLnk.WarehouseDepositItemLnk_DepositID = DISPLAY_Deposits.DepositID) AND (WarehouseDepositItemLnk.WarehouseDepositItemLnk_WarehouseID = DISPLAY_Deposits.WarehouseID);");
//snap shot
//Set adoPrimaryRS = getRS("SELECT StockItem.StockItem_Name, " & stTableName & ".Quantity, StockItem.StockItem_Quantity," & stTableName & ".HandHeldID, StockTake.StockTake_Quantity, StockTake.StockTake_StockItemID FROM ((" & stTableName & " INNER JOIN StockItem ON " & stTableName & ".HandHeldID = StockItem.StockItemID) INNER JOIN StockGroup ON StockItem.StockItem_StockGroupID = StockGroup.StockGroupID) INNER JOIN (StockTake INNER JOIN Warehouse ON StockTake.StockTake_WarehouseID = Warehouse.WarehouseID) ON StockItem.StockItemID = StockTake.StockTake_StockItemID Where (((StockGroup.StockGroupID) < " & gID & ") And ((Warehouse.WarehouseID) = 2) And ((StockItem.StockItem_Disabled) = False) And ((StockItem.StockItem_Discontinued) = False)) ORDER BY StockItem.StockItem_Name")
adoPrimaryRS = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Name, " + modApplication.stTableName + ".Quantity, StockItem.StockItem_Quantity," + modApplication.stTableName + ".HandHeldID, StockTake.StockTake_Quantity, StockTake.StockTake_StockItemID FROM ((" + modApplication.stTableName + " INNER JOIN StockItem ON " + modApplication.stTableName + ".HandHeldID = StockItem.StockItemID) INNER JOIN StockGroup ON StockItem.StockItem_StockGroupID = StockGroup.StockGroupID) INNER JOIN (StockTake INNER JOIN Warehouse ON StockTake.StockTake_WarehouseID = Warehouse.WarehouseID) ON StockItem.StockItemID = StockTake.StockTake_StockItemID Where (((StockGroup.StockGroupID) < " + gID + ") And ((Warehouse.WarehouseID) = 2)) ORDER BY StockItem.StockItem_Name");
if (adoPrimaryRS.RecordCount > 0) {
while (adoPrimaryRS.EOF == false) {
lQuantity = adoPrimaryRS.Fields("Quantity").Value;
//lQuantity = adoPrimaryRS("Quantity") - adoPrimaryRS("StockTake_Quantity").OriginalValue
modRecordSet.cnnDB.Execute("UPDATE StockTake SET StockTake.StockTake_Quantity = " + lQuantity + " WHERE (((StockTake.StockTake_StockItemID)=" + adoPrimaryRS.Fields("StockTake_StockItemID").Value + ") AND ((StockTake.StockTake_WarehouseID)=2));");
modRecordSet.cnnDB.Execute("UPDATE WarehouseStockItemLnk INNER JOIN StockTake ON (StockTake.StockTake_WarehouseID = WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID) AND (WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID = StockTake.StockTake_StockItemID) SET WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity = [WarehouseStockItemLnk]![WarehouseStockItemLnk_Quantity]+(" + lQuantity + ") WHERE (((StockTake.StockTake_StockItemID)=" + adoPrimaryRS.Fields("StockTake_StockItemID").Value + ") AND ((StockTake.StockTake_WarehouseID)=2));");
//cnnDB.Execute "UPDATE WarehouseStockItemLnk INNER JOIN StockTake ON (StockTake.StockTake_WarehouseID = WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID) AND (WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID = StockTake.StockTake_StockItemID) SET WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity = 0 WHERE (((StockTake.StockTake_StockItemID)=" & adoPrimaryRS("StockTake_StockItemID") & ") AND ((StockTake.StockTake_WarehouseID)=2));"
modRecordSet.cnnDB.Execute("UPDATE DayEndStockItemLnk INNER JOIN Company ON DayEndStockItemLnk.DayEndStockItemLnk_DayEndID = Company.Company_DayEndID SET DayEndStockItemLnk.DayEndStockItemLnk_QuantityShrink = [DayEndStockItemLnk]![DayEndStockItemLnk_QuantityShrink]-(" + lQuantity + ") WHERE (((DayEndStockItemLnk.DayEndStockItemLnk_StockItemID)=" + adoPrimaryRS.Fields("StockTake_StockItemID").Value + "));");
adoPrimaryRS.moveNext();
}
}
modRecordSet.cnnDB.Execute("DROP TABLE HandheldMakeFinish");
modRecordSet.cnnDB.Execute("DELETE * FROM StockGroup WHERE StockGroup_Name ='HandheldMakeFinish'");
Interaction.MsgBox("Make Finished Product process has been completed.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, _4PosBackOffice.NET.My.MyProject.Application.Info.Title);
functionReturnValue = true;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = true;
return functionReturnValue;
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (Convert.ToDecimal(txtQty.Text) > 0) {
} else {
txtQty.Focus();
return;
}
if (Convert.ToDecimal(txtQtyTaken.Text) > 0) {
} else {
txtQtyTaken.Focus();
return;
}
if (Convert.ToDecimal(txtQty.Text) > Convert.ToDecimal(txtQtyTaken.Text)) {
Interaction.MsgBox("Cannot make more then taken Qty.");
txtQtyTaken.Focus();
return;
}
if (updateProc()) {
this.Close();
}
}
private bool updateProc()
{
bool functionReturnValue = false;
decimal AsHoldOriginal = default(decimal);
int gID = 0;
string strFldName = null;
// ERROR: Not supported in C#: OnErrorStatement
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rj = default(ADODB.Recordset);
ADODB.Recordset RSadoPrimary = default(ADODB.Recordset);
ADODB.Recordset rsBarcode = default(ADODB.Recordset);
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
string sql = null;
decimal lQuantity = default(decimal);
int getNewID = 0;
//Set rs = getRS("SELECT VegTestItem.*, StockItem.StockItemID, StockItem.StockItem_SBarcode FROM VegTestItem INNER JOIN StockItem ON VegTestItem.VegTestItem_StockItemID = StockItem.StockItemID WHERE (((VegTestItem.VegTestItem_VegTestID)=" & testID & "));")
//If rs.RecordCount > 0 Then
strFldName = "HandHeldID Number,Handheld_Barcode Text(50), Quantity Currency";
modRecordSet.cnnDB.Execute("CREATE TABLE " + "HandheldVegTest" + " (" + strFldName + ")");
System.Windows.Forms.Application.DoEvents();
sql = "INSERT INTO HandheldVegTest (HandHeldID,Handheld_Barcode,Quantity) VALUES (" + gStockItemID + ", 0, " + (0 - (Convert.ToDecimal(txtQtyTaken.Text) - Convert.ToDecimal(txtQty.Text))) + ")";
modRecordSet.cnnDB.Execute(sql);
System.Windows.Forms.Application.DoEvents();
// Do While rs.EOF = False
// If rs("VegTestItem_PerWeightYield") > 0 Then
// getNewID = 0
// If rs("StockItem_SBarcode") = True Then
// getNewID = rs("VegTestItem_StockItemID")
// 'create new
// 'CreateVegItems rs("VegTestItem_StockItemID"), rs("VegTestItem_ActualSellPriceIncl"), rs("VegTestItem_PackSize"), getNewID ' csvSplit(0), csvSplit(1), csvSplit(2), CCur(csvSplit(3)), CCur(csvSplit(4)), csvSplit(6), csvSplit(7)
// Else
// getNewID = rs("VegTestItem_StockItemID")
// End If
// 'Stock Adjustment
// sql = "INSERT INTO HandheldVegTest (HandHeldID,Handheld_Barcode,Quantity) VALUES (" & getNewID & ", 0, " & (rs("VegTestItem_PerWeightYield")) & ")"
// cnnDB.Execute sql
// End If
// rs.moveNext
// Loop
//Else
// MsgBox "This Product does not have any Recipe.", vbApplicationModal + vbInformation + vbOKOnly, App.title
// Exit Function
//End If
//---------------------------------------------
modRecordSet.cnnDB.Execute("INSERT INTO StockGroup (StockGroup_Name) VALUES ('HandheldVegTest')");
modApplication.stTableName = "HandheldVegTest";
rj = modRecordSet.getRS(ref "SELECT StockGroup.StockGroupID, StockGroup.StockGroup_Name From StockGroup WHERE StockGroup.StockGroup_Name = 'HandheldVegTest';");
gID = rj.Fields("StockGroupID").Value;
//snap shot
modRecordSet.cnnDB.Execute("UPDATE Company SET Company.Company_StockTakeDate = now();");
//Multi Warehouse change
modRecordSet.cnnDB.Execute("DELETE FROM StockTake WHERE (StockTake_WarehouseID > 0)");
modRecordSet.cnnDB.Execute("INSERT INTO StockTake ( StockTake_StockItemID, StockTake_WarehouseID, StockTake_Quantity, StockTake_Adjustment ) SELECT WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID, WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID, 0 AS quantity, 0 AS adjustment FROM WarehouseStockItemLnk;");
modRecordSet.cnnDB.Execute("UPDATE StockTake INNER JOIN WarehouseStockItemLnk ON (StockTake.StockTake_StockItemID = WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID) AND (StockTake.StockTake_WarehouseID = WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID) SET StockTake.StockTake_Quantity = [WarehouseStockItemLnk]![WarehouseStockItemLnk_Quantity] WHERE (((WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID)>0));");
//Multi Warehouse change
// cnnDB.Execute "UPDATE StockTake SET StockTake.StockTake_Adjustment = [StockTake]![StockTake_Quantity];"
modRecordSet.cnnDB.Execute("DELETE FROM StockTakeDeposit");
modRecordSet.cnnDB.Execute("INSERT INTO StockTakeDeposit ( StockTakeDeposit_WarehouseID, StockTakeDeposit_DepositID, StockTakeDeposit_DepositTypeID, StockTakeDeposit_Quantity, StockTakeDeposit_Adjustment ) SELECT WarehouseDepositItemLnk.WarehouseDepositItemLnk_WarehouseID, WarehouseDepositItemLnk.WarehouseDepositItemLnk_DepositID, WarehouseDepositItemLnk.WarehouseDepositItemLnk_DepositTypeID, WarehouseDepositItemLnk.WarehouseDepositItemLnk_Quantity, WarehouseDepositItemLnk.WarehouseDepositItemLnk_Quantity FROM WarehouseDepositItemLnk INNER JOIN DISPLAY_Deposits ON (DISPLAY_Deposits.type = WarehouseDepositItemLnk.WarehouseDepositItemLnk_DepositTypeID) AND (WarehouseDepositItemLnk.WarehouseDepositItemLnk_DepositID = DISPLAY_Deposits.DepositID) AND (WarehouseDepositItemLnk.WarehouseDepositItemLnk_WarehouseID = DISPLAY_Deposits.WarehouseID);");
//snap shot
RSadoPrimary = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Name, " + modApplication.stTableName + ".Quantity, StockItem.StockItem_Quantity," + modApplication.stTableName + ".HandHeldID, StockTake.StockTake_Quantity, StockTake.StockTake_StockItemID FROM ((" + modApplication.stTableName + " INNER JOIN StockItem ON " + modApplication.stTableName + ".HandHeldID = StockItem.StockItemID) INNER JOIN StockGroup ON StockItem.StockItem_StockGroupID = StockGroup.StockGroupID) INNER JOIN (StockTake INNER JOIN Warehouse ON StockTake.StockTake_WarehouseID = Warehouse.WarehouseID) ON StockItem.StockItemID = StockTake.StockTake_StockItemID Where (((StockGroup.StockGroupID) < " + gID + ") And ((Warehouse.WarehouseID) = 2)) ORDER BY StockItem.StockItem_Name");
if (RSadoPrimary.RecordCount > 0) {
while (RSadoPrimary.EOF == false) {
AsHoldOriginal = RSadoPrimary.Fields("StockTake_Adjustment").Value;
//Setting the StockTake_Adjustment to it's original value
RSadoPrimary.Fields("StockTake_Adjustment").Value = 0;
lQuantity = AsHoldOriginal + RSadoPrimary.Fields("StockTake_Quantity").OriginalValue;
lQuantity = RSadoPrimary.Fields("Quantity").Value;
lQuantity = RSadoPrimary.Fields("Quantity").Value + RSadoPrimary.Fields("StockTake_Quantity").OriginalValue;
modRecordSet.cnnDB.Execute("INSERT INTO StockTakeDetail ( StockTake_StockItemID, StockTake_WarehouseID, StockTake_Quantity, StockTake_Adjustment, StockTake_DayEndID, StockTake_Note, StockTake_DateTime ) SELECT " + RSadoPrimary.Fields("StockTake_StockItemID").Value + ", 2, " + lQuantity + ", " + RSadoPrimary.Fields("Quantity").Value + ", Company_DayEndID, '" + "4VEG Repair" + " ', #" + DateAndTime.Now + "# FROM Company;");
modRecordSet.cnnDB.Execute("UPDATE StockTake SET StockTake.StockTake_Quantity = " + lQuantity + " WHERE (((StockTake.StockTake_StockItemID)=" + RSadoPrimary.Fields("StockTake_StockItemID").Value + ") AND ((StockTake.StockTake_WarehouseID)=2));");
//cnnDB.Execute "UPDATE WarehouseStockItemLnk INNER JOIN StockTake ON (StockTake.StockTake_WarehouseID = WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID) AND (WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID = StockTake.StockTake_StockItemID) SET WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity = [WarehouseStockItemLnk]![WarehouseStockItemLnk_Quantity]-(" & lQuantity & ") WHERE (((StockTake.StockTake_StockItemID)=" & RSadoPrimary("StockTake_StockItemID") & ") AND ((StockTake.StockTake_WarehouseID)=2));"
modRecordSet.cnnDB.Execute("UPDATE WarehouseStockItemLnk INNER JOIN StockTake ON (StockTake.StockTake_WarehouseID = WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID) AND (WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID = StockTake.StockTake_StockItemID) SET WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity = " + lQuantity + " WHERE (((StockTake.StockTake_StockItemID)=" + RSadoPrimary.Fields("StockTake_StockItemID").Value + ") AND ((StockTake.StockTake_WarehouseID)=2));");
//cnnDB.Execute "UPDATE WarehouseStockItemLnk INNER JOIN StockTake ON (StockTake.StockTake_WarehouseID = WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID) AND (WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID = StockTake.StockTake_StockItemID) SET WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity = 0 WHERE (((StockTake.StockTake_StockItemID)=" & RSadoPrimary("StockTake_StockItemID") & ") AND ((StockTake.StockTake_WarehouseID)=2));"
modRecordSet.cnnDB.Execute("UPDATE DayEndStockItemLnk INNER JOIN Company ON DayEndStockItemLnk.DayEndStockItemLnk_DayEndID = Company.Company_DayEndID SET DayEndStockItemLnk.DayEndStockItemLnk_QuantityShrink = [DayEndStockItemLnk]![DayEndStockItemLnk_QuantityShrink]-(" + RSadoPrimary.Fields("Quantity").Value + ") WHERE (((DayEndStockItemLnk.DayEndStockItemLnk_StockItemID)=" + RSadoPrimary.Fields("StockTake_StockItemID").Value + "));");
RSadoPrimary.moveNext();
}
}
//Update POS
//Set rsPri = getRS("SELECT GRVItem.GRVItem_StockItemID, (GRVItem.GRVItem_Quantity*GRVItem_PackSize) AS GRVItem_Quantity, StockItem.StockItem_SBarcode,StockItem.StockItem_SShelf FROM GRVItem INNER JOIN StockItem ON GRVItem.GRVItem_StockItemID = StockItem.StockItemID WHERE GRVItem_GRVID = " & Val(frmGRV.adoPrimaryRS("GRVID")) & " AND (StockItem_SBarcode = True Or StockItem_SShelf = True)")
//Set rsBarcode = getRS("SELECT HandheldVegTest.HandHeldID AS GRVItem_StockItemID, HandheldVegTest.Quantity AS GRVItem_Quantity, StockItem.StockItem_SBarcode, StockItem.StockItem_SShelf FROM HandheldVegTest INNER JOIN StockItem ON HandheldVegTest.HandHeldID = StockItem.StockItemID WHERE (((HandheldVegTest.Quantity)>0));")
rsBarcode = modRecordSet.getRS(ref "SELECT HandheldVegTest.HandHeldID AS GRVItem_StockItemID, " + Convert.ToDecimal(txtQty.Text) + " AS GRVItem_Quantity, StockItem.StockItem_SBarcode, StockItem.StockItem_SShelf FROM HandheldVegTest INNER JOIN StockItem ON HandheldVegTest.HandHeldID = StockItem.StockItemID WHERE (((HandheldVegTest.Quantity)<>0) AND ((StockItem.StockItem_SBarcode)=True)) OR (((StockItem.StockItem_SShelf)=True));");
//Write file
if (rsBarcode.RecordCount) {
if (fso.FileExists(modRecordSet.serverPath + "ShelfBarcode.dat"))
fso.DeleteFile(modRecordSet.serverPath + "ShelfBarcode.dat", true);
rsBarcode.save(modRecordSet.serverPath + "ShelfBarcode.dat", ADODB.PersistFormatEnum.adPersistADTG);
modApplication.grvPrin = true;
//If MsgBox("Do you want to do Shelf/Barcode Printing on flagged StockItems?", vbQuestion + vbYesNo + vbApplicationModal + vbDefaultButton1, App.title) = vbYes Then
modApplication.blMEndUpdatePOS = true;
modApplication.blChangeOnlyUpdatePOS = true;
My.MyProject.Forms.frmUpdatePOScriteria.ShowDialog();
modApplication.blChangeOnlyUpdatePOS = false;
modApplication.blMEndUpdatePOS = false;
My.MyProject.Forms.frmBarcode.ShowDialog();
}
modRecordSet.cnnDB.Execute("DROP TABLE HandheldVegTest");
modRecordSet.cnnDB.Execute("DELETE * FROM StockGroup WHERE StockGroup_Name ='HandheldVegTest'");
//cnnDB.Execute "UPDATE VegTest SET VegTest_VegTestStatusID = 3 WHERE (VegTestID = " & testID & ")"
//cnnDB.Execute "UPDATE VegTest INNER JOIN GRVItem ON (VegTest.VegTest_GRVID = GRVItem.GRVItem_GRVID) AND (VegTest.VegTest_MainItemID = GRVItem.GRVItem_StockItemID) SET GRVItem.GRVItem_QuantityUsedKG = " & CCur(TotalQTY.Text) & " WHERE (((VegTest.VegTestID)=" & testID & "));"
Interaction.MsgBox("Repair process has been completed.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, _4PosBackOffice.NET.My.MyProject.Application.Info.Title);
functionReturnValue = true;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
// ERROR: Not supported in C#: ResumeStatement
return functionReturnValue;
//updateProc = True
}
private void txtPrice_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocusNumeric(ref txtPrice);
}
private void txtPrice_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
modUtilities.MyKeyPressNegative(ref txtPrice, ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtPrice_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyLostFocus(ref txtPrice, ref 2);
}
private void txtPrice_MyGotFocus(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocusNumeric(ref txtPrice);
}
private void txtPrice_MyLostFocus(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyLostFocus(ref txtPrice, ref 2);
}
private void txtQty_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocusNumeric(ref txtQty);
}
private void txtQty_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtQty_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyLostFocus(ref txtQty, ref 0);
}
private void txtQtyTaken_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocusNumeric(ref txtQtyTaken);
}
private void txtQtyTaken_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtQtyTaken_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyLostFocus(ref txtQtyTaken, ref 0);
}
private void frmMakeRepairItem_Load(object sender, System.EventArgs e)
{
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json.Linq;
using Frapid.WebsiteBuilder.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.WebsiteBuilder.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Menu Item Views.
/// </summary>
[RoutePrefix("api/v1.0/website/menu-item-view")]
public class MenuItemViewController : FrapidApiController
{
/// <summary>
/// The MenuItemView repository.
/// </summary>
private readonly IMenuItemViewRepository MenuItemViewRepository;
public MenuItemViewController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.MenuItemViewRepository = new Frapid.WebsiteBuilder.DataAccess.MenuItemView
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public MenuItemViewController(IMenuItemViewRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.MenuItemViewRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Counts the number of menu item views.
/// </summary>
/// <returns>Returns the count of the menu item views.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/website/menu-item-view/count")]
[Authorize]
public long Count()
{
try
{
return this.MenuItemViewRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of menu item view for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("all")]
[Route("~/api/website/menu-item-view/export")]
[Route("~/api/website/menu-item-view/all")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItemView> Get()
{
try
{
return this.MenuItemViewRepository.Get();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 menu item views on each page, sorted by the property .
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/website/menu-item-view")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItemView> GetPaginatedResult()
{
try
{
return this.MenuItemViewRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 menu item views on each page, sorted by the property .
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/website/menu-item-view/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItemView> GetPaginatedResult(long pageNumber)
{
try
{
return this.MenuItemViewRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of menu item views.
/// </summary>
/// <returns>Returns an enumerable key/value collection of menu item views.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/website/menu-item-view/display-fields")]
[Authorize]
public IEnumerable<DisplayField> GetDisplayFields()
{
try
{
return this.MenuItemViewRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of menu item views using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered menu item views.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/website/menu-item-view/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.MenuItemViewRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 menu item views on each page, sorted by the property .
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/website/menu-item-view/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItemView> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.MenuItemViewRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of menu item views using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered menu item views.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/website/menu-item-view/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.MenuItemViewRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 menu item views on each page, sorted by the property .
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/website/menu-item-view/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItemView> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.MenuItemViewRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
#pragma warning disable 0067 // Unused events
#pragma warning disable 0649 // Uninitialized fields
namespace System.Reflection.Tests
{
public static class TypeTests_PrefixingOnlyAllowedOnGetMember
{
[Fact]
public static void TestGetEvent()
{
MemberInfo member;
Type t = typeof(TestClass).Project();
member = t.GetEvent("My*", BindingFlags.Public | BindingFlags.Instance);
Assert.Null(member);
}
[Fact]
public static void TestGetField()
{
MemberInfo member;
Type t = typeof(TestClass).Project();
member = t.GetField("My*", BindingFlags.Public | BindingFlags.Instance);
Assert.Null(member);
}
[Fact]
public static void TestGetMethod()
{
MemberInfo member;
Type t = typeof(TestClass).Project();
member = t.GetMethod("My*", BindingFlags.Public | BindingFlags.Instance);
Assert.Null(member);
}
[Fact]
public static void TestGetNestedType()
{
MemberInfo member;
Type t = typeof(TestClass).Project();
member = t.GetNestedType("My*", BindingFlags.Public | BindingFlags.Instance);
Assert.Null(member);
}
[Fact]
public static void TestGetProperty()
{
MemberInfo member;
Type t = typeof(TestClass).Project();
member = t.GetProperty("My*", BindingFlags.Public | BindingFlags.Instance);
Assert.Null(member);
}
[Fact]
public static void TestGetMemberAll()
{
Type t = typeof(TestClass).Project();
MemberInfo[] members = t.GetMember("My*", BindingFlags.Public | BindingFlags.Instance);
Assert.Equal(5, members.Length);
}
[Fact]
public static void TestGetMemberEvent()
{
Type t = typeof(TestClass).Project();
MemberInfo[] members = t.GetMember("My*", MemberTypes.Event, BindingFlags.Public | BindingFlags.Instance);
Assert.Equal(1, members.Length);
Assert.Equal("MyEvent", members[0].Name);
}
[Fact]
public static void TestGetMemberField()
{
Type t = typeof(TestClass).Project();
MemberInfo[] members = t.GetMember("My*", MemberTypes.Field, BindingFlags.Public | BindingFlags.Instance);
Assert.Equal(1, members.Length);
Assert.Equal("MyField", members[0].Name);
}
[Fact]
public static void TestGetMemberMethod()
{
Type t = typeof(TestClass).Project();
MemberInfo[] members = t.GetMember("My*", MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance);
Assert.Equal(1, members.Length);
Assert.Equal("MyMethod", members[0].Name);
}
[Fact]
public static void TestGetMemberNestedType()
{
Type t = typeof(TestClass).Project();
MemberInfo[] members = t.GetMember("My*", MemberTypes.NestedType, BindingFlags.Public | BindingFlags.Instance);
Assert.Equal(1, members.Length);
Assert.Equal("MyNestedType", members[0].Name);
}
[Fact]
public static void TestGetMemberProperty()
{
Type t = typeof(TestClass).Project();
MemberInfo[] members = t.GetMember("My*", MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance);
Assert.Equal(1, members.Length);
Assert.Equal("MyProperty", members[0].Name);
}
private class TestClass
{
public event Action MyEvent { add { } remove { } }
public int MyField;
public void MyMethod() { }
public class MyNestedType { }
public int MyProperty { get; }
}
}
public static class TypeTests_HiddenEvents
{
[Fact]
public static void GetEventHidesEventsBySimpleNameCompare()
{
Type t = typeof(Derived).Project();
EventInfo[] es = t.GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);
Assert.Equal(4, es.Length);
int count = 0;
foreach (EventInfo e in es)
{
if (e.DeclaringType.Equals(typeof(Base).Project()))
count++;
}
Assert.Equal(0, count);
}
private class Base
{
public event Action MyEvent { add { } remove { } }
public static event Action MyStaticEvent { add { } remove { } }
public event Action MyEventInstanceStatic { add { } remove { } }
public static event Action MyEventStaticInstance { add { } remove { } }
}
private class Derived : Base
{
public new event Action<int> MyEvent { add { } remove { } }
public static new event Action<double> MyStaticEvent { add { } remove { } }
public static new event Action<float> MyEventInstanceStatic { add { } remove { } }
public new event Action<long> MyEventStaticInstance { add { } remove { } }
}
}
public static class TypeTests_HiddenFields
{
[Fact]
public static void GetFieldDoesNotHideHiddenFields()
{
Type t = typeof(Derived).Project();
FieldInfo[] fs = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);
Assert.Equal(4, fs.Length);
int count = 0;
foreach (FieldInfo f in fs)
{
if (f.DeclaringType.Equals(typeof(Base).Project()))
count++;
}
Assert.Equal(2, count);
}
private class Base
{
public int MyField;
public static int MyStaticField;
}
private class Derived : Base
{
public new int MyField;
public static new int MyStaticField;
}
}
public static class TypeTests_HiddenMethods
{
[Fact]
public static void GetMethodDoesNotHideHiddenMethods()
{
Type t = typeof(Derived).Project();
MethodInfo[] ms = t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);
int count = 0;
foreach (MethodInfo m in ms)
{
if (m.DeclaringType.Equals(typeof(Base).Project()))
count++;
}
Assert.Equal(2, count);
}
private class Base
{
public int MyMethod() { throw null; }
public static int MyStaticMethod() { throw null; }
}
private class Derived : Base
{
public new int MyMethod() { throw null; }
public static new int MyStaticMethod() { throw null; }
}
}
public static class TypeTests_HiddenProperties
{
[Fact]
public static void GetPropertyHidesPropertiesByNameAndSigAndCallingConventionCompare()
{
Type t = typeof(Derived).Project();
PropertyInfo[] ps = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);
List<string> names = new List<string>();
foreach (PropertyInfo p in ps)
{
if (p.DeclaringType.Equals(typeof(Base).Project()))
{
names.Add(p.Name);
}
}
names.Sort();
string[] expected = { "Item", nameof(Base.MyInstanceThenStaticProp), nameof(Base.MyStaticThenInstanceProp), nameof(Base.MyStringThenDoubleProp) };
Assert.Equal<string>(expected, names.ToArray());
}
private abstract class Base
{
public int MyProp { get; } // will get hidden
public static int MyStaticProp { get; } // will get hidden
public int MyInstanceThenStaticProp { get; } // won't get hidden (calling convention mismatch)
public static int MyStaticThenInstanceProp { get; } // won't get hidden (calling convention mismatch)
public string MyStringThenDoubleProp { get; } // won't get hidden (signature mismatch on return type)
public abstract int this[int x] { get; } // won't get hidden (signature mismatch on parameter type)
}
private abstract class Derived : Base
{
public new int MyProp { get; }
public static new int MyStaticProp { get; }
public static new int MyInstanceThenStaticProp { get; }
public new int MyStaticThenInstanceProp { get; }
public new double MyStringThenDoubleProp { get; }
public abstract int this[double x] { get; }
}
}
public static class TypeTests_HiddenTestingOrder
{
[Fact]
public static void HideDetectionHappensBeforeBindingFlagChecks()
{
// Hiding members suppress results even if the hiding member itself is filtered out by the binding flags.
Type derived = typeof(Derived).Project();
EventInfo[] events = derived.GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
Assert.Equal(0, events.Length);
PropertyInfo[] properties = derived.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
Assert.Equal(0, properties.Length);
}
[Fact]
public static void HideDetectionHappensAfterPrivateInBaseClassChecks()
{
// Hiding members won't suppress results if the hiding member is filtered out due to being a private member in a base class.
Type derived2 = typeof(Derived2).Project();
EventInfo[] events = derived2.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
Assert.Equal(1, events.Length);
Assert.Equal(typeof(Base).Project(), events[0].DeclaringType);
Assert.Equal(nameof(Base.MyEvent), events[0].Name);
PropertyInfo[] properties = derived2.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
Assert.Equal(1, properties.Length);
Assert.Equal(typeof(Base).Project(), properties[0].DeclaringType);
Assert.Equal(nameof(Base.MyProp), properties[0].Name);
}
[Fact]
public static void HideDetectionHappensBeforeStaticInNonFlattenedHierarchyChecks()
{
// Hiding members suppress results even if the hiding member is filtered out due to being a static member in a base class (and BindingFlags.FlattenHierarchy not being specified.)
// (that check is actually just another bindingflags check.)
Type staticDerived2 = typeof(StaticDerived2).Project();
EventInfo[] events = staticDerived2.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
Assert.Equal(0, events.Length);
}
private abstract class Base
{
public event Action MyEvent { add { } remove { } }
public int MyProp { get; }
}
private abstract class Derived : Base
{
private new event Action MyEvent { add { } remove { } }
private new int MyProp { get; }
}
private abstract class Derived2 : Derived
{
}
private class StaticBase
{
public event Action MyEvent { add { } remove { } }
}
private class StaticDerived : StaticBase
{
public static new event Action MyEvent { add { } remove { } }
}
private class StaticDerived2 : StaticDerived
{
}
}
public static class TypeTests_AmbiguityResolution_NoParameterBinding
{
[Fact]
public static void EventsThrowAlways()
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase;
Type t = typeof(Derived).Project();
Assert.Throws<AmbiguousMatchException>(() => t.GetEvent("myevent", bf));
}
[Fact]
public static void NestedTypesThrowAlways()
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase;
Type t = typeof(Derived).Project();
Assert.Throws<AmbiguousMatchException>(() => t.GetNestedType("myinner", bf));
}
[Fact]
public static void PropertiesThrowAlways()
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase;
Type t = typeof(Derived).Project();
Assert.Throws<AmbiguousMatchException>(() => t.GetProperty("myprop", bf));
}
[Fact]
public static void FieldsThrowIfDeclaringTypeIsSame()
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase;
Type t = typeof(Derived).Project();
// Fields return the most derived match.
FieldInfo f = t.GetField("myfield", bf);
Assert.Equal("MyField", f.Name);
// Unless two of them are both the most derived match...
Assert.Throws<AmbiguousMatchException>(() => t.GetField("myfield2", bf));
}
[Fact]
public static void MethodsThrowIfDeclaringTypeIsSameAndSigIsDifferent()
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase;
Type t = typeof(Derived).Project();
// Methods return the most derived match, provided all their signatures are the same.
MethodInfo m1 = t.GetMethod("mymethod1", bf);
Assert.Equal("MyMethod1", m1.Name);
MethodInfo m2 = t.GetMethod("mymethod2", bf);
Assert.Equal("MyMethod2", m2.Name);
// Unless two of them are both the most derived match...
Assert.Throws<AmbiguousMatchException>(() => t.GetMethod("mymethod3", bf));
// or they have different sigs.
Assert.Throws<AmbiguousMatchException>(() => t.GetMethod("mymethod4", bf));
}
private class Base
{
public event Action myevent;
public int myprop { get; }
public int myfield;
public void mymethod1(int x) { }
public static void mymethod2(int x, int y) { }
public void mymethod4(int x) { }
}
private class Derived : Base
{
public event Action MyEvent;
public class myinner { }
public class MyInner { }
public int MyProp { get; }
public int MyField;
public int MyField2;
public int myfield2;
public void MyMethod1(int x) { }
public void MyMethod2(int x, int y) { }
public static void mymethod3(int x, int y, double z) { }
public void MyMethod3(int x, int y, double z) { }
public void mymethod4(string x) { }
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.