context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* 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 iam-2010-05-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IdentityManagement.Model
{
/// <summary>
/// Container for the parameters to the UpdateAccountPasswordPolicy operation.
/// Updates the password policy settings for the AWS account.
///
/// <note>
/// <para>
/// This action does not support partial updates. No parameters are required, but if you
/// do not specify a parameter, that parameter's value reverts to its default value. See
/// the <b>Request Parameters</b> section for each parameter's default value.
/// </para>
/// </note>
/// <para>
/// For more information about using a password policy, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html">Managing
/// an IAM Password Policy</a> in the <i>IAM User Guide</i>.
/// </para>
/// </summary>
public partial class UpdateAccountPasswordPolicyRequest : AmazonIdentityManagementServiceRequest
{
private bool? _allowUsersToChangePassword;
private bool? _hardExpiry;
private int? _maxPasswordAge;
private int? _minimumPasswordLength;
private int? _passwordReusePrevention;
private bool? _requireLowercaseCharacters;
private bool? _requireNumbers;
private bool? _requireSymbols;
private bool? _requireUppercaseCharacters;
/// <summary>
/// Gets and sets the property AllowUsersToChangePassword.
/// <para>
/// Allows all IAM users in your account to use the AWS Management Console to change
/// their own passwords. For more information, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/HowToPwdIAMUser.html">Letting
/// IAM Users Change Their Own Passwords</a> in the <i>IAM User Guide</i>.
/// </para>
///
/// <para>
/// Default value: false
/// </para>
/// </summary>
public bool AllowUsersToChangePassword
{
get { return this._allowUsersToChangePassword.GetValueOrDefault(); }
set { this._allowUsersToChangePassword = value; }
}
// Check to see if AllowUsersToChangePassword property is set
internal bool IsSetAllowUsersToChangePassword()
{
return this._allowUsersToChangePassword.HasValue;
}
/// <summary>
/// Gets and sets the property HardExpiry.
/// <para>
/// Prevents IAM users from setting a new password after their password has expired.
/// </para>
///
/// <para>
/// Default value: false
/// </para>
/// </summary>
public bool HardExpiry
{
get { return this._hardExpiry.GetValueOrDefault(); }
set { this._hardExpiry = value; }
}
// Check to see if HardExpiry property is set
internal bool IsSetHardExpiry()
{
return this._hardExpiry.HasValue;
}
/// <summary>
/// Gets and sets the property MaxPasswordAge.
/// <para>
/// The number of days that an IAM user password is valid. The default value of 0 means
/// IAM user passwords never expire.
/// </para>
///
/// <para>
/// Default value: 0
/// </para>
/// </summary>
public int MaxPasswordAge
{
get { return this._maxPasswordAge.GetValueOrDefault(); }
set { this._maxPasswordAge = value; }
}
// Check to see if MaxPasswordAge property is set
internal bool IsSetMaxPasswordAge()
{
return this._maxPasswordAge.HasValue;
}
/// <summary>
/// Gets and sets the property MinimumPasswordLength.
/// <para>
/// The minimum number of characters allowed in an IAM user password.
/// </para>
///
/// <para>
/// Default value: 6
/// </para>
/// </summary>
public int MinimumPasswordLength
{
get { return this._minimumPasswordLength.GetValueOrDefault(); }
set { this._minimumPasswordLength = value; }
}
// Check to see if MinimumPasswordLength property is set
internal bool IsSetMinimumPasswordLength()
{
return this._minimumPasswordLength.HasValue;
}
/// <summary>
/// Gets and sets the property PasswordReusePrevention.
/// <para>
/// Specifies the number of previous passwords that IAM users are prevented from reusing.
/// The default value of 0 means IAM users are not prevented from reusing previous passwords.
/// </para>
///
/// <para>
/// Default value: 0
/// </para>
/// </summary>
public int PasswordReusePrevention
{
get { return this._passwordReusePrevention.GetValueOrDefault(); }
set { this._passwordReusePrevention = value; }
}
// Check to see if PasswordReusePrevention property is set
internal bool IsSetPasswordReusePrevention()
{
return this._passwordReusePrevention.HasValue;
}
/// <summary>
/// Gets and sets the property RequireLowercaseCharacters.
/// <para>
/// Specifies whether IAM user passwords must contain at least one lowercase character
/// from the ISO basic Latin alphabet (a to z).
/// </para>
///
/// <para>
/// Default value: false
/// </para>
/// </summary>
public bool RequireLowercaseCharacters
{
get { return this._requireLowercaseCharacters.GetValueOrDefault(); }
set { this._requireLowercaseCharacters = value; }
}
// Check to see if RequireLowercaseCharacters property is set
internal bool IsSetRequireLowercaseCharacters()
{
return this._requireLowercaseCharacters.HasValue;
}
/// <summary>
/// Gets and sets the property RequireNumbers.
/// <para>
/// Specifies whether IAM user passwords must contain at least one numeric character (0
/// to 9).
/// </para>
///
/// <para>
/// Default value: false
/// </para>
/// </summary>
public bool RequireNumbers
{
get { return this._requireNumbers.GetValueOrDefault(); }
set { this._requireNumbers = value; }
}
// Check to see if RequireNumbers property is set
internal bool IsSetRequireNumbers()
{
return this._requireNumbers.HasValue;
}
/// <summary>
/// Gets and sets the property RequireSymbols.
/// <para>
/// Specifies whether IAM user passwords must contain at least one of the following non-alphanumeric
/// characters:
/// </para>
///
/// <para>
/// ! @ # $ % ^ &amp; * ( ) _ + - = [ ] { } | '
/// </para>
///
/// <para>
/// Default value: false
/// </para>
/// </summary>
public bool RequireSymbols
{
get { return this._requireSymbols.GetValueOrDefault(); }
set { this._requireSymbols = value; }
}
// Check to see if RequireSymbols property is set
internal bool IsSetRequireSymbols()
{
return this._requireSymbols.HasValue;
}
/// <summary>
/// Gets and sets the property RequireUppercaseCharacters.
/// <para>
/// Specifies whether IAM user passwords must contain at least one uppercase character
/// from the ISO basic Latin alphabet (A to Z).
/// </para>
///
/// <para>
/// Default value: false
/// </para>
/// </summary>
public bool RequireUppercaseCharacters
{
get { return this._requireUppercaseCharacters.GetValueOrDefault(); }
set { this._requireUppercaseCharacters = value; }
}
// Check to see if RequireUppercaseCharacters property is set
internal bool IsSetRequireUppercaseCharacters()
{
return this._requireUppercaseCharacters.HasValue;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using Xunit;
namespace System.Security.Cryptography.Hashing.Tests
{
public class SimpleHashAlgorithmTest
{
private static readonly byte[] s_tenBytes = new byte[10];
[Fact]
public void EmptyArrayHash()
{
ArrayHash(new byte[0]);
}
[Fact]
public void NonEmptyArrayHash()
{
ArrayHash(s_tenBytes);
}
[Fact]
public void LargeArrayHash()
{
ArrayHash(new byte[32768]);
}
[Fact]
public void ZeroCountHash()
{
ArrayHash(s_tenBytes, 0, 0);
}
[Fact]
public void NonZeroCountHash()
{
ArrayHash(s_tenBytes, 0, 5);
}
[Fact]
public void LargeLimitedArrayHash()
{
ArrayHash(new byte[32768], 16384, 16384);
}
[Fact]
public void EmptyStreamHash()
{
StreamHash(0);
}
[Fact]
public void StreamHash()
{
// This value is a completely arbitrary non-power-of-two.
StreamHash(82);
}
[Fact]
public void LargeStreamHash()
{
StreamHash(1048576);
}
[Fact]
public void ValidateStreamContents()
{
byte[] result;
const int ByteCount = 1026;
using (var stream = new PositionValueStream(ByteCount))
using (HashAlgorithm hash = new Sum32Hash())
{
result = hash.ComputeHash(stream);
}
AssertCorrectAnswer(ExpectedSum(0, ByteCount), result);
}
[Fact]
public void ValidateOffset_0()
{
// HashCount should not be a multiple of 256, otherwise it can't
// catch offset problems through Sum32 due to the data being cyclic.
ValidateOffset(2048, 0, 1500);
}
[Fact]
public void ValidateOffset_121()
{
ValidateOffset(2048, 121, 1500);
}
[Fact]
public void ValidateOffset_255()
{
ValidateOffset(2048, 255, 1500);
}
[Fact]
public void HashFullArrayInvalidArguments()
{
using (HashAlgorithm hash = new Length32Hash())
{
Assert.Throws<ArgumentNullException>(() => hash.ComputeHash((byte[])null));
hash.Dispose();
Assert.Throws<ObjectDisposedException>(() => hash.ComputeHash(s_tenBytes));
}
}
[Fact]
public void HashPartialArrayInvalidArguments()
{
using (HashAlgorithm hash = new Length32Hash())
{
Assert.Throws<ArgumentNullException>(() => hash.ComputeHash((byte[])null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => hash.ComputeHash(s_tenBytes, -1, 0));
Assert.Throws<ArgumentException>(() => hash.ComputeHash(s_tenBytes, 0, -1));
Assert.Throws<ArgumentException>(() => hash.ComputeHash(s_tenBytes, 0, 11));
Assert.Throws<ArgumentException>(() => hash.ComputeHash(s_tenBytes, 9, 2));
hash.Dispose();
Assert.Throws<ObjectDisposedException>(() => hash.ComputeHash(s_tenBytes, 0, 10));
}
}
[Fact]
public void StreamHashInvalidArguments()
{
using (var stream = new PositionValueStream(0))
using (HashAlgorithm hash = new Length32Hash())
{
Assert.Throws<NullReferenceException>(() => hash.ComputeHash((Stream)null));
hash.Dispose();
Assert.Throws<ObjectDisposedException>(() => hash.ComputeHash(stream));
}
}
private void ArrayHash(byte[] array)
{
// Do not call ArrayHash(byte[], int, int).
// Here we're verifying ComputeHash(byte[]).
byte[] result;
using (HashAlgorithm hash = new Length32Hash())
{
result = hash.ComputeHash(array);
}
AssertCorrectAnswer((uint)array.Length, result);
}
private void ArrayHash(byte[] array, int offset, int count)
{
byte[] result;
using (HashAlgorithm hash = new Length32Hash())
{
result = hash.ComputeHash(array, offset, count);
}
AssertCorrectAnswer((uint)count, result);
}
private void StreamHash(int byteCount)
{
byte[] result;
using (var stream = new PositionValueStream(byteCount))
using (HashAlgorithm hash = new Length32Hash())
{
result = hash.ComputeHash(stream);
}
AssertCorrectAnswer((uint)byteCount, result);
}
private void ValidateOffset(int arraySize, int hashOffset, int hashCount)
{
byte[] input;
using (var stream = new PositionValueStream(arraySize))
using (var reader = new BinaryReader(stream))
{
input = reader.ReadBytes(arraySize);
}
byte[] result;
using (HashAlgorithm hash = new Sum32Hash())
{
result = hash.ComputeHash(input, hashOffset, hashCount);
}
uint expectedSum = ExpectedSum(hashOffset, hashCount);
AssertCorrectAnswer(expectedSum, result);
}
private void AssertCorrectAnswer(uint expectedValue, byte[] result)
{
Assert.NotNull(result);
Assert.Equal(sizeof(uint), result.Length);
uint interpreted = BitConverter.ToUInt32(result, 0);
Assert.Equal(expectedValue, interpreted);
}
private static uint ExpectedSum(int offset, int byteCount)
{
// SUM(1..n) => n * (n + 1) / 2.
// Since our data cycles 0, 1, ..., 254, 255, 0, 1, ... we need to break it down
// into chunks.
unchecked
{
uint max = (uint)byteCount + (uint)offset;
uint skippedCycles = (uint)offset / 256;
uint fullCycles = max / 256;
uint partialCycleMax = unchecked((byte)max);
uint partialCycleSkipped = unchecked((byte)offset);
// For the partial cycles, reduce the value by 1 because the sum is 0..(n-1), not 1..n
if (partialCycleMax > 0)
{
partialCycleMax--;
}
if (partialCycleSkipped > 0)
{
partialCycleSkipped--;
}
const uint FullCycleValue = 255 * 256 / 2;
uint accum = (fullCycles - skippedCycles) * FullCycleValue;
accum += partialCycleMax * (partialCycleMax + 1) / 2;
accum -= partialCycleSkipped * (partialCycleSkipped + 1) / 2;
return accum;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.CSharp;
//using Microsoft.JScript;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.CompilerTools
{
public class CSConverter : IScriptConverter
{
private readonly CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
#region IScriptConverter Members
public string DefaultState
{
get { return ""; }
}
public void Initialise(Compiler compiler)
{
}
public void Convert(string Script, out string CompiledScript,
out object PositionMap)
{
CompiledScript = CreateCompilerScript(Script);
PositionMap = null;
}
public string Name
{
get { return "cs"; }
}
public CompilerResults Compile(CompilerParameters parameters, bool isFile, string Script)
{
bool complete = false;
bool retried = false;
CompilerResults results;
do
{
lock (CScodeProvider)
{
if (isFile)
results = CScodeProvider.CompileAssemblyFromFile(
parameters, Script);
else
results = CScodeProvider.CompileAssemblyFromSource(
parameters, Script);
}
// Deal with an occasional segv in the compiler.
// Rarely, if ever, occurs twice in succession.
// Line # == 0 and no file name are indications that
// this is a native stack trace rather than a normal
// error log.
if (results.Errors.Count > 0)
{
if (!retried && string.IsNullOrEmpty(results.Errors[0].FileName) &&
results.Errors[0].Line == 0)
{
// System.Console.WriteLine("retrying failed compilation");
retried = true;
}
else
{
complete = true;
}
}
else
{
complete = true;
}
} while (!complete);
return results;
}
public void FinishCompile(IScriptModulePlugin plugin, ScriptData data, IScript Script)
{
}
public void FindErrorLine(CompilerError CompErr, object PositionMap, string script, out int LineN, out int CharN)
{
LineN = CompErr.Line;
CharN = CompErr.Column;
}
#endregion
public void Dispose()
{
}
private string CreateCompilerScript(string compileScript)
{
compileScript = compileScript.Replace("string",
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString");
compileScript = compileScript.Replace("integer",
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLInteger");
compileScript = compileScript.Replace("float",
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLFloat");
compileScript = compileScript.Replace("list",
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.list");
compileScript = compileScript.Replace("rotation",
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion");
compileScript = compileScript.Replace("vector",
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3");
string compiledScript = "";
compiledScript = String.Empty +
"using Aurora.ScriptEngine.AuroraDotNetEngine.Runtime;\n" +
"using Aurora.ScriptEngine.AuroraDotNetEngine;\n" +
"using System;\n" +
"using System.Collections.Generic;\n" +
"using System.Collections;\n" +
"namespace Script\n" +
"{\n";
compiledScript +=
"public class ScriptClass : Aurora.ScriptEngine.AuroraDotNetEngine.Runtime.ScriptBaseClass, IDisposable\n";
compiledScript += "{\n";
compiledScript +=
compileScript;
compiledScript += "\n}"; // Close Class
compiledScript += "\n}"; // Close Namespace
return compiledScript;
}
}
public class AScriptConverter : IScriptConverter
{
private readonly CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
public bool m_addLSLAPI;
public bool m_allowUnsafe;
private Compiler m_compiler;
public List<string> m_includedAssemblies = new List<string>();
public List<string> m_includedDefines = new List<string>();
#region IScriptConverter Members
public string DefaultState
{
get { return ""; }
}
public void Initialise(Compiler compiler)
{
m_compiler = compiler;
}
public void Convert(string Script, out string CompiledScript,
out object PositionMap)
{
#region Reset
m_includedDefines.Clear();
m_includedAssemblies.Clear();
m_allowUnsafe = false;
m_addLSLAPI = false;
#endregion
CompiledScript = CreateCompilerScript(Script);
PositionMap = null;
}
public string Name
{
get { return "ascript"; }
}
public CompilerResults Compile(CompilerParameters parameters, bool isFile, string Script)
{
string rootPath =
Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
if (rootPath != null)
{
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.Framework.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenMetaverse.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenMetaverseTypes.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenMetaverse.StructuredData.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"Aurora.BotManager.dll"));
#if (!ISWIN)
foreach (string line in m_includedAssemblies)
{
if (!parameters.ReferencedAssemblies.Contains(line))
{
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, line));
}
}
#else
foreach (string line in m_includedAssemblies.Where(line => !parameters.ReferencedAssemblies.Contains(line)))
{
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
line));
}
#endif
}
bool complete = false;
bool retried = false;
CompilerResults results;
do
{
lock (CScodeProvider)
{
if (isFile)
results = CScodeProvider.CompileAssemblyFromFile(
parameters, Script);
else
results = CScodeProvider.CompileAssemblyFromSource(
parameters, Script);
}
// Deal with an occasional segv in the compiler.
// Rarely, if ever, occurs twice in succession.
// Line # == 0 and no file name are indications that
// this is a native stack trace rather than a normal
// error log.
if (results.Errors.Count > 0)
{
if (!retried && string.IsNullOrEmpty(results.Errors[0].FileName) &&
results.Errors[0].Line == 0)
{
// System.Console.WriteLine("retrying failed compilation");
retried = true;
}
else
{
complete = true;
}
}
else
{
complete = true;
}
} while (!complete);
return results;
}
public void FinishCompile(IScriptModulePlugin plugin, ScriptData data, IScript Script)
{
Script.SetSceneRefs(data.World, data.Part, false);
}
public void FindErrorLine(CompilerError CompErr, object PositionMap, string script, out int LineN, out int CharN)
{
LineN = CompErr.Line;
CharN = CompErr.Column;
}
#endregion
public void Dispose()
{
}
private string CreateCompilerScript(string compileScript)
{
bool newLine = true;
bool reading = true;
string lastLine = "";
for (int i = 0; i < compileScript.Length; i++)
{
if (compileScript[i] == '\n')
{
if (lastLine != "")
ReadLine(lastLine);
reading = false;
lastLine = "";
newLine = true;
}
if (!newLine)
{
reading = false;
continue;
}
if (compileScript.Length <= i + 2)
continue;
if (!reading &&
!(compileScript[i + 1] == '#' || (compileScript[i + 1] == '/' && compileScript[i + 2] == '/')))
{
newLine = false;
continue;
}
reading = true;
if (compileScript[i] != '\n')
lastLine += compileScript[i];
compileScript = compileScript.Remove(i, 1);
i--; //Removed a letter, remove a char here as well
}
if (m_addLSLAPI)
{
string[] lines = compileScript.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
LSLReadLine(ref lines[i]);
}
compileScript = string.Join("\n", lines);
}
string compiledScript = "";
compiledScript = String.Empty +
"using Aurora.ScriptEngine.AuroraDotNetEngine.Runtime;\n" +
"using Aurora.ScriptEngine.AuroraDotNetEngine;\n" +
"using Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces;\n" +
"using Aurora.Framework;\n" +
"using OpenSim.Services.Interfaces;\n" +
"using OpenSim.Region.Framework.Interfaces;\n" +
"using OpenSim.Region.Framework.Scenes;\n" +
"using OpenMetaverse;\n" +
"using System;\n" +
"using System.Collections.Generic;\n" +
"using System.Collections;\n";
foreach (string line in m_includedDefines)
{
compiledScript += "using " + line + ";\n";
}
compiledScript += "namespace Script\n" +
"{\n";
compiledScript +=
"public class ScriptClass : Aurora.ScriptEngine.AuroraDotNetEngine.Runtime.ScriptBaseClass, IDisposable\n";
compiledScript += "{\n";
compiledScript +=
compileScript;
compiledScript += "\n}"; // Close Class
compiledScript += "\n}"; // Close Namespace
return compiledScript;
}
private void ReadLine(string line)
{
if (line.StartsWith("#include"))
{
line = line.Replace("#include", "");
if (line.EndsWith(";"))
line = line.Remove(line.Length - 1);
line = line.TrimStart(' ');
m_includedDefines.Add(line); //TODO: Add a check here
}
else if (line.StartsWith("#assembly"))
{
line = line.Replace("#assembly", "");
if (line.EndsWith(";"))
line = line.Remove(line.Length - 1);
line = line.TrimStart(' ');
m_includedAssemblies.Add(line); //TODO: Add a check here
}
else if (line.StartsWith("#threaded"))
{
}
else if (line.StartsWith("#useLSLAPI"))
{
m_addLSLAPI = true;
}
else if (line.StartsWith("#allowUnsafe"))
{
m_allowUnsafe = true;
}
}
private void LSLReadLine(ref string line)
{
foreach (KeyValuePair<string, IScriptApi> functionName in m_compiler.ScriptEngine.GetAllFunctionNamesAPIs())
{
string newline = line.Replace(functionName.Key,
"((" + functionName.Value.InterfaceName + ")m_apis[\"" +
functionName.Value.Name + "\"])." + functionName.Key);
if (newline != line)
{
line = newline;
return;
}
}
}
}
}
| |
using System;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
namespace Marten.Testing.Acceptance
{
public class foreign_keys: IntegrationContext
{
[Fact]
public void can_insert_document_with_null_value_of_foreign_key()
{
ConfigureForeignKeyWithCascadingDeletes(false);
var issue = new Issue();
ShouldProperlySave(issue);
}
[Fact]
public void can_insert_document_with_existing_value_of_foreign_key()
{
ConfigureForeignKeyWithCascadingDeletes(false);
var user = new User();
using (var session = theStore.OpenSession())
{
session.Store(user);
session.SaveChanges();
}
var issue = new Issue { AssigneeId = user.Id };
ShouldProperlySave(issue);
}
[Fact]
public void cannot_insert_document_with_non_existing_value_of_foreign_key()
{
ConfigureForeignKeyWithCascadingDeletes(false);
var issue = new Issue { AssigneeId = Guid.NewGuid() };
Should.Throw<Marten.Exceptions.MartenCommandException>(() =>
{
using (var session = theStore.OpenSession())
{
session.Insert(issue);
session.SaveChanges();
}
});
}
[Fact]
public void can_update_document_with_existing_value_of_foreign_key_to_other_existing_value()
{
ConfigureForeignKeyWithCascadingDeletes(false);
var user = new User();
var otherUser = new User();
var issue = new Issue { AssigneeId = user.Id };
using (var session = theStore.OpenSession())
{
session.Store(user, otherUser);
session.Store(issue);
session.SaveChanges();
}
issue.AssigneeId = otherUser.Id;
ShouldProperlySave(issue);
}
[Fact]
public void can_update_document_with_existing_value_of_foreign_key_to_null()
{
ConfigureForeignKeyWithCascadingDeletes(false);
var user = new User();
var otherUser = new User();
var issue = new Issue { AssigneeId = user.Id };
using (var session = theStore.OpenSession())
{
session.Store(user, otherUser);
session.Store(issue);
session.SaveChanges();
}
issue.AssigneeId = null;
ShouldProperlySave(issue);
}
[Fact]
public void cannot_update_document_with_existing_value_of_foreign_key_to_not_existing()
{
ConfigureForeignKeyWithCascadingDeletes(false);
var user = new User();
var otherUser = new User();
var issue = new Issue { AssigneeId = user.Id };
using (var session = theStore.OpenSession())
{
session.Store(user, otherUser);
session.Store(issue);
session.SaveChanges();
}
issue.AssigneeId = Guid.NewGuid();
Should.Throw<Marten.Exceptions.MartenCommandException>(() =>
{
using (var session = theStore.OpenSession())
{
session.Update(issue);
session.SaveChanges();
}
});
}
[Fact]
public void can_delete_document_with_foreign_key()
{
ConfigureForeignKeyWithCascadingDeletes(true);
var user = new User();
var issue = new Issue { AssigneeId = user.Id };
using (var session = theStore.OpenSession())
{
session.Store(user);
session.Store(issue);
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
session.Delete(issue);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
SpecificationExtensions.ShouldBeNull(query.Load<Issue>(issue.Id));
SpecificationExtensions.ShouldNotBeNull(query.Load<User>(user.Id));
}
}
[Fact]
public void can_delete_document_that_is_referenced_by_foreignkey_with_cascadedeletes_from_other_document()
{
ConfigureForeignKeyWithCascadingDeletes(true);
var user = new User();
var issue = new Issue { AssigneeId = user.Id };
using (var session = theStore.OpenSession())
{
session.Store(user);
session.Store(issue);
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
session.Delete(user);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
SpecificationExtensions.ShouldBeNull(query.Load<Issue>(issue.Id));
SpecificationExtensions.ShouldBeNull(query.Load<User>(user.Id));
}
}
[Fact]
public void cannot_delete_document_that_is_referenced_by_foreignkey_without_cascadedeletes_from_other_document()
{
ConfigureForeignKeyWithCascadingDeletes(false);
var user = new User();
var issue = new Issue { AssigneeId = user.Id };
using (var session = theStore.OpenSession())
{
session.Store(user);
session.Store(issue);
session.SaveChanges();
}
Should.Throw<Marten.Exceptions.MartenCommandException>(() =>
{
using (var session = theStore.OpenSession())
{
session.Delete(user);
session.SaveChanges();
}
});
using (var query = theStore.QuerySession())
{
SpecificationExtensions.ShouldNotBeNull(query.Load<Issue>(issue.Id));
SpecificationExtensions.ShouldNotBeNull(query.Load<User>(user.Id));
}
}
private void ConfigureForeignKeyWithCascadingDeletes(bool hasCascadeDeletes)
{
StoreOptions(options =>
{
options.Schema.For<Issue>().ForeignKey<User>(x => x.AssigneeId, fkd => fkd.CascadeDeletes = hasCascadeDeletes);
});
theStore.Tenancy.Default.EnsureStorageExists(typeof(User));
}
private void ShouldProperlySave(Issue issue)
{
using (var session = theStore.OpenSession())
{
session.Store(issue);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
var documentFromDb = query.Load<Issue>(issue.Id);
SpecificationExtensions.ShouldNotBeNull(documentFromDb);
}
}
public foreign_keys(DefaultStoreFixture fixture) : base(fixture)
{
}
}
}
| |
using System;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class ClickTest : DriverTestFixture
{
[SetUp]
public void SetupMethod()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("clicks.html");
}
[TearDown]
public void TearDownMethod()
{
driver.SwitchTo().DefaultContent();
}
[Test]
public void CanClickOnALinkAndFollowIt()
{
driver.FindElement(By.Id("normal")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Opera, "Not tested")]
public void CanClickOnALinkThatOverflowsAndFollowIt()
{
driver.FindElement(By.Id("overflowLink")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
}
[Test]
public void CanClickOnAnAnchorAndNotReloadThePage()
{
((IJavaScriptExecutor)driver).ExecuteScript("document.latch = true");
driver.FindElement(By.Id("anchor")).Click();
bool samePage = (bool)((IJavaScriptExecutor)driver).ExecuteScript("return document.latch");
Assert.AreEqual(true, samePage, "Latch was reset");
}
[Test]
public void CanClickOnALinkThatUpdatesAnotherFrame()
{
driver.SwitchTo().Frame("source");
driver.FindElement(By.Id("otherframe")).Click();
driver.SwitchTo().DefaultContent().SwitchTo().Frame("target");
Assert.That(driver.PageSource, Does.Contain("Hello WebDriver"));
}
[Test]
public void ElementsFoundByJsCanLoadUpdatesInAnotherFrame()
{
driver.SwitchTo().Frame("source");
IWebElement toClick = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return document.getElementById('otherframe');");
toClick.Click();
driver.SwitchTo().DefaultContent().SwitchTo().Frame("target");
Assert.That(driver.PageSource, Does.Contain("Hello WebDriver"));
}
[Test]
public void JsLocatedElementsCanUpdateFramesIfFoundSomehowElse()
{
driver.SwitchTo().Frame("source");
// Prime the cache of elements
driver.FindElement(By.Id("otherframe"));
// This _should_ return the same element
IWebElement toClick = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return document.getElementById('otherframe');");
toClick.Click();
driver.SwitchTo().DefaultContent().SwitchTo().Frame("target");
Assert.That(driver.PageSource, Does.Contain("Hello WebDriver"));
}
[Test]
public void CanClickOnAnElementWithTopSetToANegativeNumber()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("styledPage.html");
IWebElement searchBox = driver.FindElement(By.Name("searchBox"));
searchBox.SendKeys("Cheese");
driver.FindElement(By.Name("btn")).Click();
string log = driver.FindElement(By.Id("log")).Text;
Assert.AreEqual("click", log);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldSetRelatedTargetForMouseOver()
{
driver.Url = javascriptPage;
driver.FindElement(By.Id("movable")).Click();
string log = driver.FindElement(By.Id("result")).Text;
// Note: It is not guaranteed that the relatedTarget property of the mouseover
// event will be the parent, when using native events. Only check that the mouse
// has moved to this element, not that the parent element was the related target.
if (this.IsNativeEventsEnabled)
{
Assert.That(log, Does.StartWith("parent matches?"));
}
else
{
Assert.AreEqual("parent matches? true", log);
}
}
[Test]
public void ShouldClickOnFirstBoundingClientRectWithNonZeroSize()
{
driver.FindElement(By.Id("twoClientRects")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
[IgnoreBrowser(Browser.Opera, "Doesn't support multiple windows")]
public void ShouldOnlyFollowHrefOnce()
{
driver.Url = clicksPage;
int windowHandlesBefore = driver.WindowHandles.Count;
driver.FindElement(By.Id("new-window")).Click();
WaitFor(() => { return driver.WindowHandles.Count >= windowHandlesBefore + 1; }, "Window handles was not " + (windowHandlesBefore + 1).ToString());
Assert.AreEqual(windowHandlesBefore + 1, driver.WindowHandles.Count);
}
[Test]
[Ignore("Ignored for all browsers")]
public void ShouldSetRelatedTargetForMouseOut()
{
Assert.Fail("Must. Write. Meamingful. Test (but we don't fire mouse outs synthetically");
}
[Test]
public void ClickingLabelShouldSetCheckbox()
{
driver.Url = formsPage;
driver.FindElement(By.Id("label-for-checkbox-with-label")).Click();
Assert.That(driver.FindElement(By.Id("checkbox-with-label")).Selected, "Checkbox should be selected");
}
[Test]
public void CanClickOnALinkWithEnclosedImage()
{
driver.FindElement(By.Id("link-with-enclosed-image")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void CanClickOnAnImageEnclosedInALink()
{
driver.FindElement(By.Id("link-with-enclosed-image")).FindElement(By.TagName("img")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void CanClickOnALinkThatContainsTextWrappedInASpan()
{
driver.FindElement(By.Id("link-with-enclosed-span")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void CanClickOnALinkThatContainsEmbeddedBlockElements()
{
driver.FindElement(By.Id("embeddedBlock")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void CanClickOnAnElementEnclosedInALink()
{
driver.FindElement(By.Id("link-with-enclosed-span")).FindElement(By.TagName("span")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
// See http://code.google.com/p/selenium/issues/attachmentText?id=2700
[Test]
public void ShouldBeAbleToClickOnAnElementInTheViewport()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_out_of_bounds.html");
driver.Url = url;
IWebElement button = driver.FindElement(By.Id("button"));
button.Click();
}
[Test]
public void ClicksASurroundingStrongTag()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("ClickTest_testClicksASurroundingStrongTag.html");
driver.FindElement(By.TagName("a")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
}
[Test]
[IgnoreBrowser(Browser.IE, "Map click fails")]
[IgnoreBrowser(Browser.Opera, "Map click fails")]
public void CanClickAnImageMapArea()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html");
driver.FindElement(By.Id("rectG")).Click();
WaitFor(() => { return driver.Title == "Target Page 1"; }, "Browser title was not 'Target Page 1'");
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html");
driver.FindElement(By.Id("circleO")).Click();
WaitFor(() => { return driver.Title == "Target Page 2"; }, "Browser title was not 'Target Page 2'");
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html");
driver.FindElement(By.Id("polyLE")).Click();
WaitFor(() => { return driver.Title == "Target Page 3"; }, "Browser title was not 'Target Page 3'");
}
[Test]
public void ShouldBeAbleToClickOnAnElementGreaterThanTwoViewports()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_too_big.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("click"));
element.Click();
WaitFor(() => { return driver.Title == "clicks"; }, "Browser title was not 'clicks'");
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Fails on Chrome")]
[IgnoreBrowser(Browser.Opera, "Not Tested")]
public void ShouldBeAbleToClickOnAnElementInFrameGreaterThanTwoViewports()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_too_big_in_frame.html");
driver.Url = url;
IWebElement frame = driver.FindElement(By.Id("iframe1"));
driver.SwitchTo().Frame(frame);
IWebElement element = driver.FindElement(By.Id("click"));
element.Click();
WaitFor(() => { return driver.Title == "clicks"; }, "Browser title was not 'clicks'");
}
[Test]
public void ShouldBeAbleToClickOnRightToLeftLanguageLink()
{
String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_rtl.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("ar_link"));
element.Click();
WaitFor(() => driver.Title == "clicks", "Expected title to be 'clicks'");
Assert.AreEqual("clicks", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnLinkInAbsolutelyPositionedFooter()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("fixedFooterNoScroll.html");
driver.Url = url;
driver.FindElement(By.Id("link")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnLinkInAbsolutelyPositionedFooterInQuirksMode()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("fixedFooterNoScrollQuirksMode.html");
driver.Url = url;
driver.FindElement(By.Id("link")).Click();
WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'");
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.LinkText("No href"));
element.Click();
WaitFor(() => driver.Title == "Changed", "Expected title to be 'Changed'");
Assert.AreEqual("Changed", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnALinkThatWrapsToTheNextLine()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/link_that_wraps.html");
driver.FindElement(By.Id("link")).Click();
WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'");
Assert.AreEqual("Submitted Successfully!", driver.Title);
}
[Test]
public void ShouldBeAbleToClickOnASpanThatWrapsToTheNextLine()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/span_that_wraps.html");
driver.FindElement(By.Id("span")).Click();
WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'");
Assert.AreEqual("Submitted Successfully!", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.IE)]
[IgnoreBrowser(Browser.Chrome)]
public void ShouldBeAbleToClickOnAPartiallyOverlappedLinkThatWrapsToTheNextLine()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/wrapped_overlapping_elements.html");
driver.FindElement(By.Id("link")).Click();
WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'");
Assert.AreEqual("Submitted Successfully!", driver.Title);
}
[Test]
public void ClickingOnADisabledElementIsANoOp()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/disabled_element.html");
IWebElement element = driver.FindElement(By.Name("disabled"));
element.Click();
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void ShouldBeAbleToClickLinkContainingLineBreak()
{
driver.Url = simpleTestPage;
driver.FindElement(By.Id("multilinelink")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'");
Assert.AreEqual("We Arrive Here", driver.Title);
}
}
}
| |
using System;
using System.Collections;
using GenLib;
namespace PrimerProObjects
{
/// <summary>
/// Syllable Class
/// </summary>summary>
public class Syllable
{
private Settings m_Settings;
private string m_SyllableAsString;
private ArrayList m_Graphemes;
private string m_CVPattern;
//private string m_Syllable;
public const string Underscore = "_";
public Syllable (string strSyll, Settings s)
{
m_Settings = s;
m_SyllableAsString = strSyll;
m_Graphemes = new ArrayList();
BuildSyllable(strSyll);
m_CVPattern = BuildCVPattern();
}
public ArrayList Graphemes
{
get { return m_Graphemes; }
set { m_Graphemes = value; }
}
public string DisplaySyllable
{
get {return m_SyllableAsString;}
}
public string CVPattern
{
get { return m_CVPattern; }
}
public int GraphemeCount()
{
if (this.Graphemes != null)
return this.Graphemes.Count;
else return 0;
}
public Grapheme GetGrapheme(int n)
{
if (n < 0)
return null;
if (n < this.Graphemes.Count)
return (Grapheme) this.Graphemes[n];
else return null;
}
public Grapheme GetGraphemeWithoutTone(int n)
{
Grapheme grf = null;
Tone tone = null;
GraphemeInventory gi = m_Settings.GraphemeInventory;
int ndx = 0;
if (n < this.GraphemeCount())
{
grf = this.GetGrapheme(n);
ndx = gi.FindToneIndex(grf.Symbol);
if (ndx >= 0)
{
tone = gi.GetTone(ndx);
grf = tone.ToneBearingUnit;
}
}
return grf;
}
public string GetSyllableInLowerCase()
{
string strSyll = "";
Grapheme grf = null;
GraphemeInventory gi = m_Settings.GraphemeInventory;
for (int i = 0; i < this.GraphemeCount(); i++)
{
grf = this.GetGrapheme(i);
strSyll += grf.Symbol;
}
return strSyll;
}
public string GetSyllableWithoutTone()
{
string strSyll = "";
int ndx = 0;
Grapheme grf = null;
Tone tone = null;
GraphemeInventory gi = m_Settings.GraphemeInventory;
for (int i = 0; i < this.GraphemeCount(); i++)
{
grf = this.GetGrapheme(i);
ndx = gi.FindToneIndex(grf.Symbol);
if (ndx >= 0)
{
tone = gi.GetTone(ndx);
Grapheme tbu = tone.ToneBearingUnit;
if (tbu != null)
strSyll += tbu.Symbol;
}
else strSyll += grf.Symbol;
}
return strSyll;
}
public bool IsOpenSyllable()
{
bool fReturn = false;
int n = this.GraphemeCount() - 1;
Grapheme grf = null;
grf = this.GetGraphemeWithoutTone(n);
if (grf.IsVowel)
fReturn = true;
return fReturn;
}
public bool IsClosedSyllable()
{
bool fReturn = false;
int n = this.GraphemeCount() - 1;
Grapheme grf = null;
grf = this.GetGraphemeWithoutTone(n);
if (grf.IsConsonant)
fReturn = true;
return fReturn;
}
public bool IsOnset(string strGrapheme)
{
bool fReturn = false;
Grapheme grf = this.GetGrapheme(0);
if (grf.Symbol == strGrapheme)
fReturn = true;
return fReturn;
}
public bool IsCoda(string strGrapheme)
{
bool fReturn = false;
int n = this.GraphemeCount() - 1;
Grapheme grf = this.GetGrapheme(n);
if (grf.Symbol == strGrapheme)
fReturn = true;
return fReturn;
}
public bool IsSyllableInitial(string strGrapheme)
{
bool fReturn = false;
Grapheme grf = this.GetGrapheme(0);
if (grf != null)
{
if (grf.Symbol == strGrapheme)
fReturn = true;
}
else fReturn = false;
return fReturn;
}
public bool IsSyllableMedial(string strGrapheme)
{
bool fReturn = false;
string str = "";
for (int i = 1; i < this.GraphemeCount() - 1; i++)
str += this.GetGrapheme(i).Symbol;
if (str.IndexOf(strGrapheme) >= 0)
fReturn = true;
return fReturn;
}
public bool IsSyllableFinal(string strGrapheme)
{
bool fReturn = false;
int n = this.GraphemeCount() - 1;
Grapheme grf = this.GetGrapheme(n);
if (grf != null)
{
if (grf.Symbol == strGrapheme)
fReturn = true;
}
else fReturn = false;
return fReturn;
}
public bool IsInSyllable(string strGrf)
{
bool fReturn = false;
for (int i = 0; i < this.GraphemeCount(); i++)
{
if (this.GetGraphemeWithoutTone(i).Symbol == strGrf)
fReturn = true;
}
return fReturn;
}
public bool IsBuildable(ArrayList alGTO)
{
bool flag = false;
string strGrf = "";
string strSymbol = "";
int nLenght = 0;
for (int i = 0; i < this.GraphemeCount(); i++)
{
strSymbol = this.GetGrapheme(i).Symbol;
bool fMatch = false;
if (i == 0) //if syllable initial
{
for (int j = 0; j < alGTO.Count; j++)
{
strGrf = (string) alGTO[j];
nLenght = strGrf.Length;
if (strGrf == strSymbol)
{
fMatch =true;
break;
}
else if ((strGrf.EndsWith(Underscore) && (strGrf.Substring(0, nLenght - 1)) == strSymbol))
{
fMatch = true;
break;
}
}
}
else if (i == this.GraphemeCount() - 1) //if syllable final
{
for (int j = 0; j < alGTO.Count; j++)
{
strGrf = (string) alGTO[j];
nLenght = strGrf.Length;
if (strGrf == strSymbol)
{
fMatch = true;
break;
}
else if ((strGrf.StartsWith(Underscore)) && (strGrf.Substring(1) == strSymbol))
{
fMatch = true;
break;
}
}
}
else
{
for (int j = 0; j < alGTO.Count; j++)
{
strGrf = (string)alGTO[j];
if (strGrf == strSymbol)
{
fMatch = true;
break;
}
}
}
flag = fMatch;
if (!fMatch)
break;
}
return flag;
}
private void BuildSyllable(string strSyllable)
{
GraphemeInventory gi = m_Settings.GraphemeInventory;
int nMaxSize = this.m_Settings.OptionSettings.MaxSizeGrapheme;
Grapheme grf = null;
string strSymbol = "";
for (int i = 0; i < strSyllable.Length; i++)
{
strSymbol = strSyllable.Substring(i, 1);
grf = new Grapheme(strSymbol);
for (int j = nMaxSize; j > 0; j--)
{
if ((i + j) <= strSyllable.Length)
{
strSymbol = strSyllable.Substring(i, j);
if (gi.IsInInventory(strSymbol))
{
grf = gi.GetGrapheme(strSymbol);
i = i + j - 1;
break;
}
}
}
this.Graphemes.Add(grf);
}
}
private string BuildCVPattern()
{
Grapheme grf = null;
string strCVPatt = "";
for (int i = 0; i < this.GraphemeCount(); i++)
{
grf = this.GetGrapheme(i);
strCVPatt += this.GetCVMarker(grf);
}
return strCVPatt;
}
private string GetCVMarker(Grapheme grf)
{
string strMarker = "";
if (grf != null)
{
GraphemeInventory gi = m_Settings.GraphemeInventory;
int ndx = 0;
Consonant cns = null;
Vowel vwl = null;
Tone tone = null;
Syllograph syllograph = null;
if (grf.Symbol.Trim() == "") //if space character
{
strMarker = Constants.Space.ToString();
return strMarker;
}
strMarker = GraphemeInventory.kUnknown;
if (grf.IsTone)
{
strMarker = m_Settings.OptionSettings.CVTone;
ndx = gi.FindToneIndex(grf.Symbol);
tone = gi.GetTone(ndx);
if (tone.ToneBearingUnit != null)
{
if (tone.ToneBearingUnit.IsVowel)
grf = tone.ToneBearingUnit;
else if (tone.ToneBearingUnit.IsConsonant)
grf = tone.ToneBearingUnit;
else strMarker = m_Settings.OptionSettings.CVTone;
}
}
if (grf.IsConsonant)
{
strMarker = m_Settings.OptionSettings.CVCns;
ndx = gi.FindConsonantIndex(grf.Symbol);
cns = gi.GetConsonant(ndx);
if (cns.IsSyllabic)
strMarker = m_Settings.OptionSettings.CVSyllbc;
if (cns.IsAspirated)
strMarker = m_Settings.OptionSettings.CVAspir;
if (cns.IsVelarized)
strMarker = m_Settings.OptionSettings.CVVelrzd;
if (cns.IsPalatalized)
strMarker = m_Settings.OptionSettings.CVPaltzd;
if (cns.IsLabialized)
strMarker = m_Settings.OptionSettings.CVLablzd;
if (cns.IsPrenasalized)
strMarker = m_Settings.OptionSettings.CVPrensl;
}
if (grf.IsVowel)
{
strMarker = m_Settings.OptionSettings.CVVwl;
ndx = gi.FindVowelIndex(grf.Symbol);
vwl = gi.GetVowel(ndx);
if (vwl.IsLong)
strMarker = m_Settings.OptionSettings.CVVwlLng;
if (vwl.IsNasal)
strMarker = m_Settings.OptionSettings.CVVwlNsl;
if (vwl.IsComplex)
strMarker = m_Settings.OptionSettings.CVVwlDip;
}
if (grf.IsSyllograph)
{
strMarker = m_Settings.OptionSettings.CVSyllograph;
ndx = gi.FindSyllographIndex(grf.Symbol);
syllograph = gi.GetSyllograph(ndx);
}
}
return strMarker;
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// Category
/// </summary>
public class Category : LegendItem
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Category"/> class.
/// </summary>
public Category()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Category"/> class and tailors the range to the specifeid values.
/// </summary>
/// <param name="startValue">The start value</param>
/// <param name="endValue">The end value</param>
public Category(double? startValue, double? endValue)
{
Range = new Range(startValue, endValue);
}
/// <summary>
/// Initializes a new instance of the <see cref="Category"/> class that has the same value for both minimum and maximum.
/// </summary>
/// <param name="value">The value to use</param>
public Category(double value)
{
Range = new Range(value);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the maximum value for this category using the scheme field. This is a convenient caching tool only, and doesn't control the filter expression at all.
/// Use ApplyMinMax after setting this to update the filter expression.
/// </summary>
[Description("Gets or sets the maximum value for this category using the scheme field.")]
public double? Maximum
{
get
{
return Range?.Maximum;
}
set
{
if (Range == null)
{
Range = new Range(null, value);
return;
}
Range.Maximum = value;
}
}
/// <summary>
/// Gets or sets the color to be used for this break. For
/// BiValued breaks, this only sets one of the colors. If
/// this is higher than the high value, both are set to this.
/// If this equals the high value, IsBiValue will be false.
/// </summary>
[Description("Gets or sets a minimum value for this category using the scheme field.")]
public double? Minimum
{
get
{
return Range?.Minimum;
}
set
{
if (Range == null)
{
Range = new Range(value, null);
return;
}
Range.Minimum = value;
}
}
/// <summary>
/// Gets or sets the numeric range for this color break.
/// </summary>
[Serialize("Range")]
public Range Range { get; set; }
/// <summary>
/// Gets or sets a status message for this string.
/// </summary>
public string Status { get; set; }
/// <summary>
/// Gets or sets a value indicating whether items of this category get selected by the parent layers Select methods.
/// If the legend is used for selection this gets set if either the whole layer is selected or this category.
/// If the legend is not used for selection this has to be set by code to be able to select only features of this category.
/// By default selection is allowed.
/// </summary>
public bool SelectionEnabled { get; set; } = true;
/// <summary>
/// Gets or sets the tag. This is not used by DotSpatial, but is provided for convenient linking for this object
/// in plugins or other applications.
/// </summary>
public object Tag { get; set; }
#endregion
#region Methods
/// <summary>
/// Since rasters are numeric and not relying on an SQL expression, this allows
/// this only sets the legend text using the method and digits to help with
/// formatting.
/// </summary>
/// <param name="settings">An EditorSettings from either a feature scheme or color scheme.</param>
public virtual void ApplyMinMax(EditorSettings settings)
{
LegendText = Range.ToString(settings.IntervalSnapMethod, settings.IntervalRoundingDigits);
}
/// <summary>
/// Applies the snapping rule directly to the categories, instead of the breaks.
/// </summary>
/// <param name="method">Snapping method that should be applied.</param>
/// <param name="numDigits">Number of significant digits.</param>
/// <param name="values">Values to get the min and max from when using IntervalSnapMethod.DataValue as method.</param>
public void ApplySnapping(IntervalSnapMethod method, int numDigits, List<double> values)
{
switch (method)
{
case IntervalSnapMethod.None: break;
case IntervalSnapMethod.SignificantFigures:
if (Maximum != null)
{
Maximum = Utils.SigFig(Maximum.Value, numDigits);
}
if (Minimum != null)
{
Minimum = Utils.SigFig(Minimum.Value, numDigits);
}
break;
case IntervalSnapMethod.Rounding:
if (Maximum != null)
{
Maximum = Math.Round((double)Maximum, numDigits);
}
if (Minimum != null)
{
Minimum = Math.Round((double)Minimum, numDigits);
}
break;
case IntervalSnapMethod.DataValue:
if (Maximum != null)
{
Maximum = Utils.GetNearestValue((double)Maximum, values);
}
if (Minimum != null)
{
Minimum = Utils.GetNearestValue((double)Minimum, values);
}
break;
}
}
/// <summary>
/// Tests to see if the specified value falls in the range specified by this ColorCategory
/// </summary>
/// <param name="value">The value of type int to test</param>
/// <returns>Boolean, true if the value was found in the range</returns>
public bool Contains(double value)
{
return Range == null || Range.Contains(value);
}
/// <summary>
/// Returns this Number as a string. This uses the DotSpatial.Globalization.CulturePreferences and
/// Controls the number type using the NumberFormat enumeration plus the DecimalCount to create
/// a number format.
/// </summary>
/// <returns>The string created using the specified number format and precision.</returns>
public override string ToString()
{
return Range.ToString();
}
/// <summary>
/// Returns this Number as a string.
/// </summary>
/// <param name="method">Specifies how the numbers are modified so that the numeric text can be cleaned up.</param>
/// <param name="digits">An integer clarifying digits for rounding or significant figure situations.</param>
/// <returns>A string with the formatted number.</returns>
public virtual string ToString(IntervalSnapMethod method, int digits)
{
return Range.ToString(method, digits);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace Lucene.Net.Codecs.Lucene40
{
using BytesRef = Lucene.Net.Util.BytesRef;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Directory = Lucene.Net.Store.Directory;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOUtils = Lucene.Net.Util.IOUtils;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//using LegacyDocValuesType = Lucene.Net.Codecs.Lucene40.LegacyDocValuesType;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using SegmentWriteState = Lucene.Net.Index.SegmentWriteState;
#pragma warning disable 612, 618
internal class Lucene40DocValuesWriter : DocValuesConsumer
{
private readonly Directory Dir;
private readonly SegmentWriteState State;
private readonly string LegacyKey;
private const string SegmentSuffix = "dv";
// note: intentionally ignores seg suffix
internal Lucene40DocValuesWriter(SegmentWriteState state, string filename, string legacyKey)
{
this.State = state;
this.LegacyKey = legacyKey;
this.Dir = new CompoundFileDirectory(state.Directory, filename, state.Context, true);
}
public override void AddNumericField(FieldInfo field, IEnumerable<long?> values)
{
// examine the values to determine best type to use
long minValue = long.MaxValue;
long maxValue = long.MinValue;
foreach (long? n in values)
{
long v = n.GetValueOrDefault();
minValue = Math.Min(minValue, v);
maxValue = Math.Max(maxValue, v);
}
string fileName = IndexFileNames.SegmentFileName(State.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), SegmentSuffix, "dat");
IndexOutput data = Dir.CreateOutput(fileName, State.Context);
bool success = false;
try
{
if (minValue >= sbyte.MinValue && maxValue <= sbyte.MaxValue && PackedInt32s.BitsRequired(maxValue - minValue) > 4)
{
// fits in a byte[], would be more than 4bpv, just write byte[]
AddBytesField(field, data, values);
}
else if (minValue >= short.MinValue && maxValue <= short.MaxValue && PackedInt32s.BitsRequired(maxValue - minValue) > 8)
{
// fits in a short[], would be more than 8bpv, just write short[]
AddShortsField(field, data, values);
}
else if (minValue >= int.MinValue && maxValue <= int.MaxValue && PackedInt32s.BitsRequired(maxValue - minValue) > 16)
{
// fits in a int[], would be more than 16bpv, just write int[]
AddIntsField(field, data, values);
}
else
{
AddVarIntsField(field, data, values, minValue, maxValue);
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(data);
}
else
{
IOUtils.DisposeWhileHandlingException(data);
}
}
}
private void AddBytesField(FieldInfo field, IndexOutput output, IEnumerable<long?> values)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.FIXED_INTS_8.ToString());
CodecUtil.WriteHeader(output, Lucene40DocValuesFormat.INTS_CODEC_NAME, Lucene40DocValuesFormat.INTS_VERSION_CURRENT);
output.WriteInt32(1); // size
foreach (long? n in values)
{
output.WriteByte((byte)n.GetValueOrDefault());
}
}
private void AddShortsField(FieldInfo field, IndexOutput output, IEnumerable<long?> values)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.FIXED_INTS_16.ToString());
CodecUtil.WriteHeader(output, Lucene40DocValuesFormat.INTS_CODEC_NAME, Lucene40DocValuesFormat.INTS_VERSION_CURRENT);
output.WriteInt32(2); // size
foreach (long? n in values)
{
output.WriteInt16((short)n.GetValueOrDefault());
}
}
private void AddIntsField(FieldInfo field, IndexOutput output, IEnumerable<long?> values)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.FIXED_INTS_32.ToString());
CodecUtil.WriteHeader(output, Lucene40DocValuesFormat.INTS_CODEC_NAME, Lucene40DocValuesFormat.INTS_VERSION_CURRENT);
output.WriteInt32(4); // size
foreach (long? n in values)
{
output.WriteInt32((int)n.GetValueOrDefault());
}
}
private void AddVarIntsField(FieldInfo field, IndexOutput output, IEnumerable<long?> values, long minValue, long maxValue)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.VAR_INTS.ToString());
CodecUtil.WriteHeader(output, Lucene40DocValuesFormat.VAR_INTS_CODEC_NAME, Lucene40DocValuesFormat.VAR_INTS_VERSION_CURRENT);
long delta = maxValue - minValue;
if (delta < 0)
{
// writes longs
output.WriteByte((byte)Lucene40DocValuesFormat.VAR_INTS_FIXED_64);
foreach (long? n in values)
{
output.WriteInt64(n.GetValueOrDefault());
}
}
else
{
// writes packed ints
output.WriteByte((byte)Lucene40DocValuesFormat.VAR_INTS_PACKED);
output.WriteInt64(minValue);
output.WriteInt64(0 - minValue); // default value (representation of 0)
PackedInt32s.Writer writer = PackedInt32s.GetWriter(output, State.SegmentInfo.DocCount, PackedInt32s.BitsRequired(delta), PackedInt32s.DEFAULT);
foreach (long? n in values)
{
writer.Add(n.GetValueOrDefault() - minValue);
}
writer.Finish();
}
}
public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values)
{
// examine the values to determine best type to use
HashSet<BytesRef> uniqueValues = new HashSet<BytesRef>();
int minLength = int.MaxValue;
int maxLength = int.MinValue;
var vals = values.ToArray();
for (int i = 0; i < vals.Length; i++)
{
var b = vals[i];
if (b == null)
{
b = vals[i] = new BytesRef(); // 4.0 doesnt distinguish
}
if (b.Length > Lucene40DocValuesFormat.MAX_BINARY_FIELD_LENGTH)
{
throw new System.ArgumentException("DocValuesField \"" + field.Name + "\" is too large, must be <= " + Lucene40DocValuesFormat.MAX_BINARY_FIELD_LENGTH);
}
minLength = Math.Min(minLength, b.Length);
maxLength = Math.Max(maxLength, b.Length);
if (uniqueValues != null)
{
if (uniqueValues.Add(BytesRef.DeepCopyOf(b)))
{
if (uniqueValues.Count > 256)
{
uniqueValues = null;
}
}
}
}
int maxDoc = State.SegmentInfo.DocCount;
bool @fixed = minLength == maxLength;
bool dedup = uniqueValues != null && uniqueValues.Count * 2 < maxDoc;
if (dedup)
{
// we will deduplicate and deref values
bool success = false;
IndexOutput data = null;
IndexOutput index = null;
string dataName = IndexFileNames.SegmentFileName(State.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), SegmentSuffix, "dat");
string indexName = IndexFileNames.SegmentFileName(State.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), SegmentSuffix, "idx");
try
{
data = Dir.CreateOutput(dataName, State.Context);
index = Dir.CreateOutput(indexName, State.Context);
if (@fixed)
{
AddFixedDerefBytesField(field, data, index, values, minLength);
}
else
{
AddVarDerefBytesField(field, data, index, values);
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(data, index);
}
else
{
IOUtils.DisposeWhileHandlingException(data, index);
}
}
}
else
{
// we dont deduplicate, just write values straight
if (@fixed)
{
// fixed byte[]
string fileName = IndexFileNames.SegmentFileName(State.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), SegmentSuffix, "dat");
IndexOutput data = Dir.CreateOutput(fileName, State.Context);
bool success = false;
try
{
AddFixedStraightBytesField(field, data, values, minLength);
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(data);
}
else
{
IOUtils.DisposeWhileHandlingException(data);
}
}
}
else
{
// variable byte[]
bool success = false;
IndexOutput data = null;
IndexOutput index = null;
string dataName = IndexFileNames.SegmentFileName(State.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), SegmentSuffix, "dat");
string indexName = IndexFileNames.SegmentFileName(State.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), SegmentSuffix, "idx");
try
{
data = Dir.CreateOutput(dataName, State.Context);
index = Dir.CreateOutput(indexName, State.Context);
AddVarStraightBytesField(field, data, index, values);
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(data, index);
}
else
{
IOUtils.DisposeWhileHandlingException(data, index);
}
}
}
}
}
private void AddFixedStraightBytesField(FieldInfo field, IndexOutput output, IEnumerable<BytesRef> values, int length)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.BYTES_FIXED_STRAIGHT.ToString());
CodecUtil.WriteHeader(output, Lucene40DocValuesFormat.BYTES_FIXED_STRAIGHT_CODEC_NAME, Lucene40DocValuesFormat.BYTES_FIXED_STRAIGHT_VERSION_CURRENT);
output.WriteInt32(length);
foreach (BytesRef v in values)
{
if (v != null)
{
output.WriteBytes(v.Bytes, v.Offset, v.Length);
}
}
}
// NOTE: 4.0 file format docs are crazy/wrong here...
private void AddVarStraightBytesField(FieldInfo field, IndexOutput data, IndexOutput index, IEnumerable<BytesRef> values)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.BYTES_VAR_STRAIGHT.ToString());
CodecUtil.WriteHeader(data, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_VERSION_CURRENT);
CodecUtil.WriteHeader(index, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_VERSION_CURRENT);
/* values */
long startPos = data.GetFilePointer();
foreach (BytesRef v in values)
{
if (v != null)
{
data.WriteBytes(v.Bytes, v.Offset, v.Length);
}
}
/* addresses */
long maxAddress = data.GetFilePointer() - startPos;
index.WriteVInt64(maxAddress);
int maxDoc = State.SegmentInfo.DocCount;
Debug.Assert(maxDoc != int.MaxValue); // unsupported by the 4.0 impl
PackedInt32s.Writer w = PackedInt32s.GetWriter(index, maxDoc + 1, PackedInt32s.BitsRequired(maxAddress), PackedInt32s.DEFAULT);
long currentPosition = 0;
foreach (BytesRef v in values)
{
w.Add(currentPosition);
if (v != null)
{
currentPosition += v.Length;
}
}
// write sentinel
Debug.Assert(currentPosition == maxAddress);
w.Add(currentPosition);
w.Finish();
}
private void AddFixedDerefBytesField(FieldInfo field, IndexOutput data, IndexOutput index, IEnumerable<BytesRef> values, int length)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.BYTES_FIXED_DEREF.ToString());
CodecUtil.WriteHeader(data, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_VERSION_CURRENT);
CodecUtil.WriteHeader(index, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_VERSION_CURRENT);
// deduplicate
SortedSet<BytesRef> dictionary = new SortedSet<BytesRef>();
foreach (BytesRef v in values)
{
dictionary.Add(v == null ? new BytesRef() : BytesRef.DeepCopyOf(v));
}
/* values */
data.WriteInt32(length);
foreach (BytesRef v in dictionary)
{
data.WriteBytes(v.Bytes, v.Offset, v.Length);
}
/* ordinals */
int valueCount = dictionary.Count;
Debug.Assert(valueCount > 0);
index.WriteInt32(valueCount);
int maxDoc = State.SegmentInfo.DocCount;
PackedInt32s.Writer w = PackedInt32s.GetWriter(index, maxDoc, PackedInt32s.BitsRequired(valueCount - 1), PackedInt32s.DEFAULT);
BytesRef brefDummy;
foreach (BytesRef v in values)
{
brefDummy = v;
if (v == null)
{
brefDummy = new BytesRef();
}
//int ord = dictionary.HeadSet(brefDummy).Size();
int ord = dictionary.Count(@ref => @ref.CompareTo(brefDummy) < 0);
w.Add(ord);
}
w.Finish();
}
private void AddVarDerefBytesField(FieldInfo field, IndexOutput data, IndexOutput index, IEnumerable<BytesRef> values)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.BYTES_VAR_DEREF.ToString());
CodecUtil.WriteHeader(data, Lucene40DocValuesFormat.BYTES_VAR_DEREF_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_VAR_DEREF_VERSION_CURRENT);
CodecUtil.WriteHeader(index, Lucene40DocValuesFormat.BYTES_VAR_DEREF_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_VAR_DEREF_VERSION_CURRENT);
// deduplicate
SortedSet<BytesRef> dictionary = new SortedSet<BytesRef>();
foreach (BytesRef v in values)
{
dictionary.Add(v == null ? new BytesRef() : BytesRef.DeepCopyOf(v));
}
/* values */
long startPosition = data.GetFilePointer();
long currentAddress = 0;
Dictionary<BytesRef, long> valueToAddress = new Dictionary<BytesRef, long>();
foreach (BytesRef v in dictionary)
{
currentAddress = data.GetFilePointer() - startPosition;
valueToAddress[v] = currentAddress;
WriteVShort(data, v.Length);
data.WriteBytes(v.Bytes, v.Offset, v.Length);
}
/* ordinals */
long totalBytes = data.GetFilePointer() - startPosition;
index.WriteInt64(totalBytes);
int maxDoc = State.SegmentInfo.DocCount;
PackedInt32s.Writer w = PackedInt32s.GetWriter(index, maxDoc, PackedInt32s.BitsRequired(currentAddress), PackedInt32s.DEFAULT);
foreach (BytesRef v in values)
{
w.Add(valueToAddress[v == null ? new BytesRef() : v]);
}
w.Finish();
}
// the little vint encoding used for var-deref
private static void WriteVShort(IndexOutput o, int i)
{
Debug.Assert(i >= 0 && i <= short.MaxValue);
if (i < 128)
{
o.WriteByte((byte)(sbyte)i);
}
else
{
o.WriteByte((byte)unchecked((sbyte)(0x80 | (i >> 8))));
o.WriteByte((byte)unchecked((sbyte)(i & 0xff)));
}
}
public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
// examine the values to determine best type to use
int minLength = int.MaxValue;
int maxLength = int.MinValue;
foreach (BytesRef b in values)
{
minLength = Math.Min(minLength, b.Length);
maxLength = Math.Max(maxLength, b.Length);
}
// but dont use fixed if there are missing values (we are simulating how lucene40 wrote dv...)
bool anyMissing = false;
foreach (long n in docToOrd)
{
if ((long)n == -1)
{
anyMissing = true;
break;
}
}
bool success = false;
IndexOutput data = null;
IndexOutput index = null;
string dataName = IndexFileNames.SegmentFileName(State.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), SegmentSuffix, "dat");
string indexName = IndexFileNames.SegmentFileName(State.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), SegmentSuffix, "idx");
try
{
data = Dir.CreateOutput(dataName, State.Context);
index = Dir.CreateOutput(indexName, State.Context);
if (minLength == maxLength && !anyMissing)
{
// fixed byte[]
AddFixedSortedBytesField(field, data, index, values, docToOrd, minLength);
}
else
{
// var byte[]
// three cases for simulating the old writer:
// 1. no missing
// 2. missing (and empty string in use): remap ord=-1 -> ord=0
// 3. missing (and empty string not in use): remap all ords +1, insert empty string into values
if (!anyMissing)
{
AddVarSortedBytesField(field, data, index, values, docToOrd);
}
else if (minLength == 0)
{
AddVarSortedBytesField(field, data, index, values, MissingOrdRemapper.MapMissingToOrd0(docToOrd));
}
else
{
AddVarSortedBytesField(field, data, index, MissingOrdRemapper.InsertEmptyValue(values), MissingOrdRemapper.MapAllOrds(docToOrd));
}
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(data, index);
}
else
{
IOUtils.DisposeWhileHandlingException(data, index);
}
}
}
private void AddFixedSortedBytesField(FieldInfo field, IndexOutput data, IndexOutput index, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd, int length)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.BYTES_FIXED_SORTED.ToString());
CodecUtil.WriteHeader(data, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_VERSION_CURRENT);
CodecUtil.WriteHeader(index, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_VERSION_CURRENT);
/* values */
data.WriteInt32(length);
int valueCount = 0;
foreach (BytesRef v in values)
{
data.WriteBytes(v.Bytes, v.Offset, v.Length);
valueCount++;
}
/* ordinals */
index.WriteInt32(valueCount);
int maxDoc = State.SegmentInfo.DocCount;
Debug.Assert(valueCount > 0);
PackedInt32s.Writer w = PackedInt32s.GetWriter(index, maxDoc, PackedInt32s.BitsRequired(valueCount - 1), PackedInt32s.DEFAULT);
foreach (long n in docToOrd)
{
w.Add((long)n);
}
w.Finish();
}
private void AddVarSortedBytesField(FieldInfo field, IndexOutput data, IndexOutput index, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
field.PutAttribute(LegacyKey, LegacyDocValuesType.BYTES_VAR_SORTED.ToString());
CodecUtil.WriteHeader(data, Lucene40DocValuesFormat.BYTES_VAR_SORTED_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_VAR_SORTED_VERSION_CURRENT);
CodecUtil.WriteHeader(index, Lucene40DocValuesFormat.BYTES_VAR_SORTED_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_VAR_SORTED_VERSION_CURRENT);
/* values */
long startPos = data.GetFilePointer();
int valueCount = 0;
foreach (BytesRef v in values)
{
data.WriteBytes(v.Bytes, v.Offset, v.Length);
valueCount++;
}
/* addresses */
long maxAddress = data.GetFilePointer() - startPos;
index.WriteInt64(maxAddress);
Debug.Assert(valueCount != int.MaxValue); // unsupported by the 4.0 impl
PackedInt32s.Writer w = PackedInt32s.GetWriter(index, valueCount + 1, PackedInt32s.BitsRequired(maxAddress), PackedInt32s.DEFAULT);
long currentPosition = 0;
foreach (BytesRef v in values)
{
w.Add(currentPosition);
currentPosition += v.Length;
}
// write sentinel
Debug.Assert(currentPosition == maxAddress);
w.Add(currentPosition);
w.Finish();
/* ordinals */
int maxDoc = State.SegmentInfo.DocCount;
Debug.Assert(valueCount > 0);
PackedInt32s.Writer ords = PackedInt32s.GetWriter(index, maxDoc, PackedInt32s.BitsRequired(valueCount - 1), PackedInt32s.DEFAULT);
foreach (long n in docToOrd)
{
ords.Add((long)n);
}
ords.Finish();
}
public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
throw new System.NotSupportedException("Lucene 4.0 does not support SortedSet docvalues");
}
protected override void Dispose(bool disposing)
{
Dir.Dispose();
}
}
#pragma warning restore 612, 618
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// HashRepartitionEnumerator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Linq.Parallel
{
/// <summary>
/// This enumerator handles the actual coordination among partitions required to
/// accomplish the repartitioning operation, as explained above.
/// </summary>
/// <typeparam name="TInputOutput">The kind of elements.</typeparam>
/// <typeparam name="THashKey">The key used to distribute elements.</typeparam>
/// <typeparam name="TIgnoreKey">The kind of keys found in the source (ignored).</typeparam>
internal class HashRepartitionEnumerator<TInputOutput, THashKey, TIgnoreKey> : QueryOperatorEnumerator<Pair<TInputOutput, THashKey>, int>
{
private const int ENUMERATION_NOT_STARTED = -1; // Sentinel to note we haven't begun enumerating yet.
private readonly int _partitionCount; // The number of partitions.
private readonly int _partitionIndex; // Our unique partition index.
private readonly Func<TInputOutput, THashKey>? _keySelector; // A key-selector function.
private readonly HashRepartitionStream<TInputOutput, THashKey, int> _repartitionStream; // A repartitioning stream.
private readonly ListChunk<Pair<TInputOutput, THashKey>>[][] _valueExchangeMatrix; // Matrix to do inter-task communication.
private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The immediate source of data.
private CountdownEvent _barrier; // Used to signal and wait for repartitions to complete.
private readonly CancellationToken _cancellationToken; // A token for canceling the process.
private Mutables? _mutables; // Mutable fields for this enumerator.
private class Mutables
{
internal int _currentBufferIndex; // Current buffer index.
internal ListChunk<Pair<TInputOutput, THashKey>>? _currentBuffer; // The buffer we're currently enumerating.
internal int _currentIndex; // Current index into the buffer.
internal Mutables()
{
_currentBufferIndex = ENUMERATION_NOT_STARTED;
}
}
//---------------------------------------------------------------------------------------
// Creates a new repartitioning enumerator.
//
// Arguments:
// source - the data stream from which to pull elements
// useOrdinalOrderPreservation - whether order preservation is required
// partitionCount - total number of partitions
// partitionIndex - this operator's unique partition index
// repartitionStream - the stream object to use for partition selection
// barrier - a latch used to signal task completion
// buffers - a set of buffers for inter-task communication
//
internal HashRepartitionEnumerator(
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, int partitionCount, int partitionIndex,
Func<TInputOutput, THashKey>? keySelector, HashRepartitionStream<TInputOutput, THashKey, int> repartitionStream,
CountdownEvent barrier, ListChunk<Pair<TInputOutput, THashKey>>[][] valueExchangeMatrix, CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(keySelector != null || typeof(THashKey) == typeof(NoKeyMemoizationRequired));
Debug.Assert(repartitionStream != null);
Debug.Assert(barrier != null);
Debug.Assert(valueExchangeMatrix != null);
Debug.Assert(valueExchangeMatrix.GetLength(0) == partitionCount, "expected square matrix of buffers (NxN)");
Debug.Assert(partitionCount > 0 && valueExchangeMatrix[0].Length == partitionCount, "expected square matrix of buffers (NxN)");
Debug.Assert(0 <= partitionIndex && partitionIndex < partitionCount);
_source = source;
_partitionCount = partitionCount;
_partitionIndex = partitionIndex;
_keySelector = keySelector;
_repartitionStream = repartitionStream;
_barrier = barrier;
_valueExchangeMatrix = valueExchangeMatrix;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Retrieves the next element from this partition. All repartitioning operators across
// all partitions cooperate in a barrier-style algorithm. The first time an element is
// requested, the repartitioning operator will enter the 1st phase: during this phase, it
// scans its entire input and compute the destination partition for each element. During
// the 2nd phase, each partition scans the elements found by all other partitions for
// it, and yield this to callers. The only synchronization required is the barrier itself
// -- all other parts of this algorithm are synchronization-free.
//
// Notes: One rather large penalty that this algorithm incurs is higher memory usage and a
// larger time-to-first-element latency, at least compared with our old implementation; this
// happens because all input elements must be fetched before we can produce a single output
// element. In many cases this isn't too terrible: e.g. a GroupBy requires this to occur
// anyway, so having the repartitioning operator do so isn't complicating matters much at all.
//
internal override bool MoveNext(ref Pair<TInputOutput, THashKey> currentElement, ref int currentKey)
{
if (_partitionCount == 1)
{
// If there's only one partition, no need to do any sort of exchanges.
TIgnoreKey keyUnused = default(TIgnoreKey)!;
TInputOutput current = default(TInputOutput)!;
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
if (_source.MoveNext(ref current!, ref keyUnused))
{
currentElement = new Pair<TInputOutput, THashKey>(
current, _keySelector == null ? default : _keySelector(current));
return true;
}
return false;
}
Mutables? mutables = _mutables;
if (mutables == null)
mutables = _mutables = new Mutables();
// If we haven't enumerated the source yet, do that now. This is the first phase
// of a two-phase barrier style operation.
if (mutables._currentBufferIndex == ENUMERATION_NOT_STARTED)
{
EnumerateAndRedistributeElements();
Debug.Assert(mutables._currentBufferIndex != ENUMERATION_NOT_STARTED);
}
// Once we've enumerated our contents, we can then go back and walk the buffers that belong
// to the current partition. This is phase two. Note that we slyly move on to the first step
// of phase two before actually waiting for other partitions. That's because we can enumerate
// the buffer we wrote to above, as already noted.
while (mutables._currentBufferIndex < _partitionCount)
{
// If the queue is non-null and still has elements, yield them.
if (mutables._currentBuffer != null)
{
if (++mutables._currentIndex < mutables._currentBuffer.Count)
{
// Return the current element.
currentElement = mutables._currentBuffer._chunk[mutables._currentIndex];
return true;
}
else
{
// If the chunk is empty, advance to the next one (if any).
mutables._currentIndex = ENUMERATION_NOT_STARTED;
mutables._currentBuffer = mutables._currentBuffer.Next;
Debug.Assert(mutables._currentBuffer == null || mutables._currentBuffer.Count > 0);
continue; // Go back around and invoke this same logic.
}
}
// We're done with the current partition. Slightly different logic depending on whether
// we're on our own buffer or one that somebody else found for us.
if (mutables._currentBufferIndex == _partitionIndex)
{
// We now need to wait at the barrier, in case some other threads aren't done.
// Once we wake up, we reset our index and will increment it immediately after.
_barrier.Wait(_cancellationToken);
mutables._currentBufferIndex = ENUMERATION_NOT_STARTED;
}
// Advance to the next buffer.
mutables._currentBufferIndex++;
mutables._currentIndex = ENUMERATION_NOT_STARTED;
if (mutables._currentBufferIndex == _partitionIndex)
{
// Skip our current buffer (since we already enumerated it).
mutables._currentBufferIndex++;
}
// Assuming we're within bounds, retrieve the next buffer object.
if (mutables._currentBufferIndex < _partitionCount)
{
mutables._currentBuffer = _valueExchangeMatrix[mutables._currentBufferIndex][_partitionIndex];
}
}
// We're done. No more buffers to enumerate.
return false;
}
//---------------------------------------------------------------------------------------
// Called when this enumerator is first enumerated; it must walk through the source
// and redistribute elements to their slot in the exchange matrix.
//
private void EnumerateAndRedistributeElements()
{
Mutables? mutables = _mutables;
Debug.Assert(mutables != null);
ListChunk<Pair<TInputOutput, THashKey>>[] privateBuffers = new ListChunk<Pair<TInputOutput, THashKey>>[_partitionCount];
TInputOutput element = default(TInputOutput)!;
TIgnoreKey ignoreKey = default(TIgnoreKey)!;
int loopCount = 0;
while (_source.MoveNext(ref element!, ref ignoreKey))
{
if ((loopCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Calculate the element's destination partition index, placing it into the
// appropriate buffer from which partitions will later enumerate.
int destinationIndex;
THashKey elementHashKey = default(THashKey)!;
if (_keySelector != null)
{
elementHashKey = _keySelector(element);
destinationIndex = _repartitionStream.GetHashCode(elementHashKey) % _partitionCount;
}
else
{
Debug.Assert(typeof(THashKey) == typeof(NoKeyMemoizationRequired));
destinationIndex = _repartitionStream.GetHashCode(element) % _partitionCount;
}
Debug.Assert(0 <= destinationIndex && destinationIndex < _partitionCount,
"destination partition outside of the legal range of partitions");
// Get the buffer for the destination partition, lazily allocating if needed. We maintain
// this list in our own private cache so that we avoid accessing shared memory locations
// too much. In the original implementation, we'd access the buffer in the matrix ([N,M],
// where N is the current partition and M is the destination), but some rudimentary
// performance profiling indicates copying at the end performs better.
ListChunk<Pair<TInputOutput, THashKey>> buffer = privateBuffers[destinationIndex];
if (buffer == null)
{
const int INITIAL_PRIVATE_BUFFER_SIZE = 128;
privateBuffers[destinationIndex] = buffer = new ListChunk<Pair<TInputOutput, THashKey>>(INITIAL_PRIVATE_BUFFER_SIZE);
}
buffer.Add(new Pair<TInputOutput, THashKey>(element, elementHashKey));
}
// Copy the local buffers to the shared space and then signal to other threads that
// we are done. We can then immediately move on to enumerating the elements we found
// for the current partition before waiting at the barrier. If we found a lot, we will
// hopefully never have to physically wait.
for (int i = 0; i < _partitionCount; i++)
{
_valueExchangeMatrix[_partitionIndex][i] = privateBuffers[i];
}
_barrier.Signal();
// Begin at our own buffer.
mutables._currentBufferIndex = _partitionIndex;
mutables._currentBuffer = privateBuffers[_partitionIndex];
mutables._currentIndex = ENUMERATION_NOT_STARTED;
}
protected override void Dispose(bool disposed)
{
if (_barrier != null)
{
// Since this enumerator is being disposed, we will decrement the barrier,
// in case other enumerators will wait on the barrier.
if (_mutables == null || (_mutables._currentBufferIndex == ENUMERATION_NOT_STARTED))
{
_barrier.Signal();
_barrier = null!;
}
_source.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.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
public partial struct Vector4
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
/// <summary>
/// The Z component of the vector.
/// </summary>
public Single Z;
/// <summary>
/// The W component of the vector.
/// </summary>
public Single W;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[JitIntrinsic]
public Vector4(Single value)
: this(value, value, value, value)
{
}
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="w">W component.</param>
/// <param name="x">X component.</param>
/// <param name="y">Y component.</param>
/// <param name="z">Z component.</param>
[JitIntrinsic]
public Vector4(Single x, Single y, Single z, Single w)
{
W = w;
X = x;
Y = y;
Z = z;
}
/// <summary>
/// Constructs a Vector4 from the given Vector2 and a Z and W component.
/// </summary>
/// <param name="value">The vector to use as the X and Y components.</param>
/// <param name="z">The Z component.</param>
/// <param name="w">The W component.</param>
public Vector4(Vector2 value, Single z, Single w)
{
X = value.X;
Y = value.Y;
Z = z;
W = w;
}
/// <summary>
/// Constructs a Vector4 from the given Vector3 and a W component.
/// </summary>
/// <param name="value">The vector to use as the X, Y, and Z components.</param>
/// <param name="w">The W component.</param>
public Vector4(Vector3 value, Single w)
{
X = value.X;
Y = value.Y;
Z = value.Z;
W = w;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array.</exception>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 4)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
array[index + 2] = Z;
array[index + 3] = W;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector4 is equal to this Vector4 instance.
/// </summary>
/// <param name="other">The Vector4 to compare this instance to.</param>
/// <returns>True if the other Vector4 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector4 other)
{
return this.X == other.X
&& this.Y == other.Y
&& this.Z == other.Z
&& this.W == other.W;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector4 vector1, Vector4 vector2)
{
return vector1.X * vector2.X +
vector1.Y * vector2.Y +
vector1.Z * vector2.Z +
vector1.W * vector2.W;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Min(Vector4 value1, Vector4 value2)
{
return new Vector4(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y,
(value1.Z < value2.Z) ? value1.Z : value2.Z,
(value1.W < value2.W) ? value1.W : value2.W);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The maximized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Max(Vector4 value1, Vector4 value2)
{
return new Vector4(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y,
(value1.Z > value2.Z) ? value1.Z : value2.Z,
(value1.W > value2.W) ? value1.W : value2.W);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Abs(Vector4 value)
{
return new Vector4(Math.Abs(value.X), Math.Abs(value.Y), Math.Abs(value.Z), Math.Abs(value.W));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 SquareRoot(Vector4 value)
{
return new Vector4((Single)Math.Sqrt(value.X), (Single)Math.Sqrt(value.Y), (Single)Math.Sqrt(value.Z), (Single)Math.Sqrt(value.W));
}
#endregion Public Static Methods
#region Public static operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 operator +(Vector4 left, Vector4 right)
{
return new Vector4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 operator -(Vector4 left, Vector4 right)
{
return new Vector4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 operator *(Vector4 left, Vector4 right)
{
return new Vector4(left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 operator *(Vector4 left, Single right)
{
return left * new Vector4(right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 operator *(Single left, Vector4 right)
{
return new Vector4(left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 operator /(Vector4 left, Vector4 right)
{
return new Vector4(left.X / right.X, left.Y / right.Y, left.Z / right.Z, left.W / right.W);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 operator /(Vector4 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector4(
value1.X * invDiv,
value1.Y * invDiv,
value1.Z * invDiv,
value1.W * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 operator -(Vector4 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector4 left, Vector4 right)
{
return left.Equals(right);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector4 left, Vector4 right)
{
return !(left == right);
}
#endregion Public static operators
}
}
| |
/*
* 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.Collections.Specialized;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects avatar presence information (for tracking current location and
/// message routing) to the SimianGrid backend
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_serverUrl = String.Empty;
private SimianActivityDetector m_activityDetector;
private bool m_Enabled = false;
#region ISharedRegionModule
public Type ReplaceableInterface { get { return null; } }
public void RegionLoaded(Scene scene) { }
public void PostInitialise() { }
public void Close() { }
public SimianPresenceServiceConnector() { m_activityDetector = new SimianActivityDetector(this); }
public string Name { get { return "SimianPresenceServiceConnector"; } }
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
scene.RegisterModuleInterface<IPresenceService>(this);
scene.RegisterModuleInterface<IGridUserService>(this);
m_activityDetector.AddRegion(scene);
LogoutRegionAgents(scene.RegionInfo.RegionID);
}
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IPresenceService>(this);
scene.UnregisterModuleInterface<IGridUserService>(this);
m_activityDetector.RemoveRegion(scene);
LogoutRegionAgents(scene.RegionInfo.RegionID);
}
}
#endregion ISharedRegionModule
public SimianPresenceServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("PresenceServices", "");
if (name == Name)
CommonInit(source);
}
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["PresenceService"];
if (gridConfig != null)
{
string serviceUrl = gridConfig.GetString("PresenceServerURI");
if (!String.IsNullOrEmpty(serviceUrl))
{
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_serverUrl = serviceUrl;
m_Enabled = true;
}
}
if (String.IsNullOrEmpty(m_serverUrl))
m_log.Info("[SIMIAN PRESENCE CONNECTOR]: No PresenceServerURI specified, disabling connector");
}
#region IPresenceService
public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
{
m_log.ErrorFormat("[SIMIAN PRESENCE CONNECTOR]: Login requested, UserID={0}, SessionID={1}, SecureSessionID={2}",
userID, sessionID, secureSessionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddSession" },
{ "UserID", userID.ToString() }
};
if (sessionID != UUID.Zero)
{
requestArgs["SessionID"] = sessionID.ToString();
requestArgs["SecureSessionID"] = secureSessionID.ToString();
}
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to login agent " + userID + ": " + response["Message"].AsString());
return success;
}
public bool LogoutAgent(UUID sessionID)
{
m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveSession" },
{ "SessionID", sessionID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agent with sessionID " + sessionID + ": " + response["Message"].AsString());
return success;
}
public bool LogoutRegionAgents(UUID regionID)
{
m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for all agents in region " + regionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveSessions" },
{ "SceneID", regionID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agents from region " + regionID + ": " + response["Message"].AsString());
return success;
}
public bool ReportAgent(UUID sessionID, UUID regionID)
{
// Not needed for SimianGrid
return true;
}
public PresenceInfo GetAgent(UUID sessionID)
{
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent with sessionID " + sessionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetSession" },
{ "SessionID", sessionID.ToString() }
};
OSDMap sessionResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
if (sessionResponse["Success"].AsBoolean())
{
UUID userID = sessionResponse["UserID"].AsUUID();
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
if (userResponse["Success"].AsBoolean())
return ResponseToPresenceInfo(sessionResponse, userResponse);
else
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString());
}
else
{
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session " + sessionID + ": " + sessionResponse["Message"].AsString());
}
return null;
}
public PresenceInfo[] GetAgents(string[] userIDs)
{
List<PresenceInfo> presences = new List<PresenceInfo>(userIDs.Length);
for (int i = 0; i < userIDs.Length; i++)
{
UUID userID;
if (UUID.TryParse(userIDs[i], out userID) && userID != UUID.Zero)
presences.AddRange(GetSessions(userID));
}
return presences.ToArray();
}
#endregion IPresenceService
#region IGridUserService
public GridUserInfo LoggedIn(string userID)
{
// Never implemented at the sim
return null;
}
public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Logging out user " + userID);
// Remove the session to mark this user offline
if (!LogoutAgent(sessionID))
return false;
// Save our last position as user data
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString());
return success;
}
public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
{
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "HomeLocation", SerializeLocation(regionID, position, lookAt) }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set home location for " + userID + ": " + response["Message"].AsString());
return success;
}
public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
return UpdateSession(sessionID, regionID, lastPosition, lastLookAt);
}
public GridUserInfo GetGridUserInfo(string user)
{
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user);
UUID userID = new UUID(user);
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
if (userResponse["Success"].AsBoolean())
return ResponseToGridUserInfo(userResponse);
else
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString());
return null;
}
#endregion
#region Helpers
private OSDMap GetUserData(UUID userID)
{
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["User"] is OSDMap)
return response;
else
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + response["Message"].AsString());
return null;
}
private List<PresenceInfo> GetSessions(UUID userID)
{
List<PresenceInfo> presences = new List<PresenceInfo>(1);
OSDMap userResponse = GetUserData(userID);
if (userResponse != null)
{
m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting sessions for " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetSession" },
{ "UserID", userID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
PresenceInfo presence = ResponseToPresenceInfo(response, userResponse);
if (presence != null)
presences.Add(presence);
}
else
{
m_log.Debug("[SIMIAN PRESENCE CONNECTOR]: No session returned for " + userID + ": " + response["Message"].AsString());
}
}
return presences;
}
private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
// Save our current location as session data
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "UpdateSession" },
{ "SessionID", sessionID.ToString() },
{ "SceneID", regionID.ToString() },
{ "ScenePosition", lastPosition.ToString() },
{ "SceneLookAt", lastLookAt.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString());
return success;
}
private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse, OSDMap userResponse)
{
if (sessionResponse == null)
return null;
PresenceInfo info = new PresenceInfo();
info.UserID = sessionResponse["UserID"].AsUUID().ToString();
info.RegionID = sessionResponse["SceneID"].AsUUID();
return info;
}
private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse)
{
if (userResponse != null && userResponse["User"] is OSDMap)
{
GridUserInfo info = new GridUserInfo();
info.Online = true;
info.UserID = userResponse["UserID"].AsUUID().ToString();
info.LastRegionID = userResponse["SceneID"].AsUUID();
info.LastPosition = userResponse["ScenePosition"].AsVector3();
info.LastLookAt = userResponse["SceneLookAt"].AsVector3();
OSDMap user = (OSDMap)userResponse["User"];
info.Login = user["LastLoginDate"].AsDate();
info.Logout = user["LastLogoutDate"].AsDate();
DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt);
return info;
}
return null;
}
private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt)
{
return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}";
}
private bool DeserializeLocation(string location, out UUID regionID, out Vector3 position, out Vector3 lookAt)
{
OSDMap map = null;
try { map = OSDParser.DeserializeJson(location) as OSDMap; }
catch { }
if (map != null)
{
regionID = map["SceneID"].AsUUID();
if (Vector3.TryParse(map["Position"].AsString(), out position) &&
Vector3.TryParse(map["LookAt"].AsString(), out lookAt))
{
return true;
}
}
regionID = UUID.Zero;
position = Vector3.Zero;
lookAt = Vector3.Zero;
return false;
}
#endregion Helpers
}
}
| |
namespace MaterialDesignThemes.Wpf
{
/// ******************************************
/// This code is auto generated. Do not amend.
/// ******************************************
/// <summary>
/// List of available icons for use with <see cref="PackIcon" />.
/// </summary>
/// <remarks>
/// All icons sourced from Material Design Icons Font - <see cref="https://materialdesignicons.com/"/> - in accordance of
/// <see cref="https://github.com/Templarian/MaterialDesign/blob/master/license.txt"/>.
/// </remarks>
public enum PackIconKind
{
AccessPoint,
Wireless=AccessPoint,
AccessPointNetwork,
Account,
Person=Account,
User=Account,
AccountAlert,
UserAlert=AccountAlert,
AccountWarning=AccountAlert,
UserWarning=AccountAlert,
AccountAlertOutline,
UserAlertOutline=AccountAlertOutline,
AccountWarningOutline=AccountAlertOutline,
AccountArrowLeft,
UserArrowLeft=AccountArrowLeft,
AccountArrowLeftOutline,
UserArrowLeftOutline=AccountArrowLeftOutline,
AccountArrowRight,
UserArrowRight=AccountArrowRight,
AccountArrowRightOutline,
UserArrowRightOutline=AccountArrowRightOutline,
AccountBox,
Selfie=AccountBox,
UserBox=AccountBox,
AccountBoxMultiple,
SwitchAccount=AccountBoxMultiple,
UserBoxMultiple=AccountBoxMultiple,
AccountBoxes=AccountBoxMultiple,
UserBoxes=AccountBoxMultiple,
AccountBoxOutline,
SelfieOutline=AccountBoxOutline,
UserBoxOutline=AccountBoxOutline,
Portrait=AccountBoxOutline,
AccountCardDetails,
IdentificationCard=AccountCardDetails,
UserCardDetails=AccountCardDetails,
AccountCheck,
UserCheck=AccountCheck,
AccountTick=AccountCheck,
UserTick=AccountCheck,
AccountChild,
UserChild=AccountChild,
AccountChildCircle,
UserChildCircle=AccountChildCircle,
AccountCircle,
UserCircle=AccountCircle,
AccountCircleOutline,
UserCircleOutline=AccountCircleOutline,
AccountClock,
UserClock=AccountClock,
AccountPending=AccountClock,
AccountClockOutline,
UserClockOutline=AccountClockOutline,
AccountPendingOutline=AccountClockOutline,
AccountConvert,
UserConvert=AccountConvert,
AccountDetails,
UserSettingsVariant=AccountDetails,
UserDetails=AccountDetails,
AccountEdit,
UserEdit=AccountEdit,
AccountGroup,
UserGroup=AccountGroup,
AccountGroupOutline,
UserGroupOutline=AccountGroupOutline,
AccountHeart,
UserHeart=AccountHeart,
AccountKey,
UserKey=AccountKey,
AccountLocation,
UserAddress=AccountLocation,
AccountAddress=AccountLocation,
UserLocation=AccountLocation,
AccountMinus,
UserMinus=AccountMinus,
AccountMinusOutline,
UserMinusOutline=AccountMinusOutline,
AccountMultiple,
People=AccountMultiple,
UserMultiple=AccountMultiple,
Accounts=AccountMultiple,
Users=AccountMultiple,
AccountMultipleCheck,
UserMultipleCheck=AccountMultipleCheck,
AccountMultipleTick=AccountMultipleCheck,
AccountsCheck=AccountMultipleCheck,
AccountsTick=AccountMultipleCheck,
UsersCheck=AccountMultipleCheck,
UsersTick=AccountMultipleCheck,
UserMultipleTick=AccountMultipleCheck,
AccountMultipleMinus,
UserMultipleMinus=AccountMultipleMinus,
AccountsMinus=AccountMultipleMinus,
UsersMinus=AccountMultipleMinus,
AccountMultipleOutline,
UserMultipleOutline=AccountMultipleOutline,
PeopleOutline=AccountMultipleOutline,
AccountsOutline=AccountMultipleOutline,
UsersOutline=AccountMultipleOutline,
AccountMultiplePlus,
UserMultiplePlus=AccountMultiplePlus,
GroupAdd=AccountMultiplePlus,
AccountsPlus=AccountMultiplePlus,
UsersPlus=AccountMultiplePlus,
AccountMultiplePlusOutline,
GroupAddOutline=AccountMultiplePlusOutline,
UserMultiplePlusOutline=AccountMultiplePlusOutline,
AccountsPlusOutline=AccountMultiplePlusOutline,
UsersPlusOutline=AccountMultiplePlusOutline,
AccountNetwork,
UserNetwork=AccountNetwork,
AccountOff,
UserOff=AccountOff,
AccountOutline,
UserOutline=AccountOutline,
PermIdentity=AccountOutline,
PersonOutline=AccountOutline,
AccountPlus,
Register=AccountPlus,
UserPlus=AccountPlus,
PersonAdd=AccountPlus,
AccountPlusOutline,
PersonAddOutline=AccountPlusOutline,
RegisterOutline=AccountPlusOutline,
UserPlusOutline=AccountPlusOutline,
AccountQuestion,
UserHelp=AccountQuestion,
AccountQuestionMark=AccountQuestion,
AccountQuestionOutline,
AccountQuestionMarkOutline=AccountQuestionOutline,
UserHelpOutline=AccountQuestionOutline,
AccountRemove,
UserRemove=AccountRemove,
AccountRemoveOutline,
UserRemoveOutline=AccountRemoveOutline,
AccountSearch,
UserSearch=AccountSearch,
AccountSearchOutline,
UserSearchOutline=AccountSearchOutline,
AccountSettings,
UserSettings=AccountSettings,
AccountStar,
UserStar=AccountStar,
AccountSupervisor,
UserSupervisor=AccountSupervisor,
AccountSupervisorCircle,
UserSupervisorCircle=AccountSupervisorCircle,
AccountSwitch,
UserSwitch=AccountSwitch,
AccountsSwitch=AccountSwitch,
UsersSwitch=AccountSwitch,
Accusoft,
Adjust,
Adobe,
AirConditioner,
AcUnit=AirConditioner,
Airballoon,
HotAirBalloon=Airballoon,
Airplane,
Aeroplane=Airplane,
AirplanemodeActive=Airplane,
Flight=Airplane,
LocalAirport=Airplane,
AirplaneLanding,
AeroplaneLanding=AirplaneLanding,
FlightLand=AirplaneLanding,
AirplaneOff,
AeroplaneOff=AirplaneOff,
AirplanemodeInactive=AirplaneOff,
AirplaneTakeoff,
AeroplaneTakeoff=AirplaneTakeoff,
FlightTakeoff=AirplaneTakeoff,
Airplay,
Airport,
Alarm,
AccessAlarms=Alarm,
AlarmBell,
AlarmCheck,
AlarmOn=AlarmCheck,
AlarmTick=AlarmCheck,
AlarmLight,
AlarmMultiple,
Alarms=AlarmMultiple,
AlarmOff,
AlarmPlus,
AddAlarm=AlarmPlus,
AlarmSnooze,
Album,
Vinyl=Album,
Alert,
Warning=Alert,
ReportProblem=Alert,
AlertBox,
WarningBox=AlertBox,
AlertCircle,
WarningCircle=AlertCircle,
Error=AlertCircle,
AlertCircleOutline,
WarningCircleOutline=AlertCircleOutline,
ErrorOutline=AlertCircleOutline,
AlertDecagram,
NewReleases=AlertDecagram,
WarningDecagram=AlertDecagram,
AlertOctagon,
WarningOctagon=AlertOctagon,
Report=AlertOctagon,
AlertOctagram,
WarningOctagram=AlertOctagram,
AlertOutline,
WarningOutline=AlertOutline,
Alien,
AllInclusive,
Alpha,
AlphaA,
AlphabetA=AlphaA,
LetterA=AlphaA,
AlphaABox,
AlphabetABox=AlphaABox,
LetterABox=AlphaABox,
AlphaB,
AlphabetB=AlphaB,
LetterB=AlphaB,
AlphaBBox,
AlphabetBBox=AlphaBBox,
LetterBBox=AlphaBBox,
AlphaC,
AlphabetC=AlphaC,
LetterC=AlphaC,
AlphaCBox,
AlphabetCBox=AlphaCBox,
LetterCBox=AlphaCBox,
AlphaD,
AlphabetD=AlphaD,
LetterD=AlphaD,
AlphaDBox,
AlphabetDBox=AlphaDBox,
LetterDBox=AlphaDBox,
AlphaE,
AlphabetE=AlphaE,
LetterE=AlphaE,
AlphaEBox,
AlphabetEBox=AlphaEBox,
LetterEBox=AlphaEBox,
AlphaF,
AlphabetF=AlphaF,
LetterF=AlphaF,
AlphaFBox,
AlphabetFBox=AlphaFBox,
LetterFBox=AlphaFBox,
AlphaG,
AlphabetG=AlphaG,
LetterG=AlphaG,
AlphaGBox,
AlphabetGBox=AlphaGBox,
LetterGBox=AlphaGBox,
AlphaH,
AlphabetH=AlphaH,
LetterH=AlphaH,
AlphaHBox,
AlphabetHBox=AlphaHBox,
LetterHBox=AlphaHBox,
AlphaI,
AlphabetI=AlphaI,
LetterI=AlphaI,
AlphaIBox,
AlphabetIBox=AlphaIBox,
LetterIBox=AlphaIBox,
AlphaJ,
AlphabetJ=AlphaJ,
LetterJ=AlphaJ,
AlphaJBox,
AlphabetJBox=AlphaJBox,
LetterJBox=AlphaJBox,
AlphaK,
AlphabetK=AlphaK,
LetterK=AlphaK,
AlphaKBox,
AlphabetKBox=AlphaKBox,
LetterKBox=AlphaKBox,
AlphaL,
AlphabetL=AlphaL,
LetterL=AlphaL,
AlphaLBox,
AlphabetLBox=AlphaLBox,
LetterLBox=AlphaLBox,
AlphaM,
AlphabetM=AlphaM,
LetterM=AlphaM,
AlphaMBox,
AlphabetMBox=AlphaMBox,
LetterMBox=AlphaMBox,
AlphaN,
AlphabetN=AlphaN,
LetterN=AlphaN,
AlphaNBox,
AlphabetNBox=AlphaNBox,
LetterNBox=AlphaNBox,
AlphaO,
AlphabetO=AlphaO,
LetterO=AlphaO,
AlphaOBox,
AlphabetOBox=AlphaOBox,
LetterOBox=AlphaOBox,
AlphaP,
AlphabetP=AlphaP,
LetterP=AlphaP,
AlphaPBox,
AlphabetPBox=AlphaPBox,
LetterPBox=AlphaPBox,
AlphaQ,
AlphabetQ=AlphaQ,
LetterQ=AlphaQ,
AlphaQBox,
AlphabetQBox=AlphaQBox,
LetterQBox=AlphaQBox,
AlphaR,
AlphabetR=AlphaR,
LetterR=AlphaR,
AlphaRBox,
AlphabetRBox=AlphaRBox,
LetterRBox=AlphaRBox,
AlphaS,
AlphabetS=AlphaS,
LetterS=AlphaS,
AlphaSBox,
AlphabetSBox=AlphaSBox,
LetterSBox=AlphaSBox,
AlphaT,
AlphabetT=AlphaT,
LetterT=AlphaT,
AlphaTBox,
AlphabetTBox=AlphaTBox,
LetterTBox=AlphaTBox,
AlphaU,
AlphabetU=AlphaU,
LetterU=AlphaU,
AlphaUBox,
AlphabetUBox=AlphaUBox,
LetterUBox=AlphaUBox,
AlphaV,
AlphabetV=AlphaV,
LetterV=AlphaV,
AlphaVBox,
AlphabetVBox=AlphaVBox,
LetterVBox=AlphaVBox,
AlphaW,
AlphabetW=AlphaW,
LetterW=AlphaW,
AlphaWBox,
AlphabetWBox=AlphaWBox,
LetterWBox=AlphaWBox,
AlphaX,
AlphabetX=AlphaX,
LetterX=AlphaX,
AlphaXBox,
AlphabetXBox=AlphaXBox,
LetterXBox=AlphaXBox,
AlphaY,
AlphabetY=AlphaY,
LetterY=AlphaY,
AlphaYBox,
AlphabetYBox=AlphaYBox,
LetterYBox=AlphaYBox,
AlphaZ,
AlphabetZ=AlphaZ,
LetterZ=AlphaZ,
AlphaZBox,
AlphabetZBox=AlphaZBox,
LetterZBox=AlphaZBox,
Alphabetical,
Letters=Alphabetical,
ABC=Alphabetical,
Abc=Alphabetical,
Altimeter,
Amazon,
AmazonAlexa,
AmazonDrive,
AmazonClouddrive=AmazonDrive,
Ambulance,
Ampersand,
And=Ampersand,
Amplifier,
Anchor,
Android,
AndroidAuto,
AndroidDebugBridge,
Adb=AndroidDebugBridge,
AndroidHead,
AndroidStudio,
MathCompassVariant=AndroidStudio,
AngleAcute,
AngleObtuse,
AngleRight,
Angular,
Angularjs,
Animation,
AutoAwesomeMotion=Animation,
AnimationOutline,
AnimationPlay,
AnimationPlayOutline,
Anvil,
Apple,
AppleFinder,
AppleIcloud,
AppleMobileme=AppleIcloud,
AppleIos,
AppleKeyboardCaps,
AppleKeyboardCommand,
AppleKeyboardControl,
AppleKeyboardOption,
AppleKeyboardShift,
AppleSafari,
Application,
WebAsset=Application,
Apps,
Arch,
Archive,
ArrangeBringForward,
ArrangeBringToFront,
ArrangeSendBackward,
ArrangeSendToBack,
ArrowAll,
ArrowBottomLeft,
ArrowBottomLeftBoldOutline,
ArrowBottomLeftThick,
ArrowBottomRight,
ArrowBottomRightBoldOutline,
ArrowBottomRightThick,
ArrowCollapse,
ArrowCompress=ArrowCollapse,
ArrowCollapseAll,
ArrowCompressAll=ArrowCollapseAll,
ArrowCollapseDown,
ArrowCompressDown=ArrowCollapseDown,
ArrowCollapseHorizontal,
ArrowCollapseLeft,
ArrowCompressLeft=ArrowCollapseLeft,
ArrowCollapseRight,
ArrowCompressRight=ArrowCollapseRight,
ArrowCollapseUp,
ArrowCompressUp=ArrowCollapseUp,
ArrowCollapseVertical,
Compress=ArrowCollapseVertical,
ArrowDecision,
ArrowDecisionAuto,
ArrowDecisionAutoOutline,
ArrowDecisionOutline,
ArrowDown,
ArrowDownward=ArrowDown,
ArrowDownBold,
ArrowDownBoldBox,
ArrowDownBoldBoxOutline,
ArrowDownBoldCircle,
ArrowDownBoldCircleOutline,
ArrowDownBoldHexagonOutline,
ArrowDownBoldOutline,
ArrowDownBox,
ArrowDownDropCircle,
ArrowDropDownCircle=ArrowDownDropCircle,
ArrowDownDropCircleOutline,
ArrowDownThick,
ArrowExpand,
ArrowExpandAll,
ArrowExpandDown,
ArrowExpandHorizontal,
ArrowExpandLeft,
ArrowExpandRight,
ArrowExpandUp,
ArrowExpandVertical,
ArrowLeft,
ArrowBack=ArrowLeft,
ArrowLeftBold,
ArrowLeftBoldBox,
ArrowLeftBoldBoxOutline,
ArrowLeftBoldCircle,
ArrowLeftBoldCircleOutline,
ArrowLeftBoldHexagonOutline,
ArrowLeftBoldOutline,
ArrowLeftBox,
ArrowLeftDropCircle,
ArrowLeftDropCircleOutline,
ArrowLeftRightBoldOutline,
ArrowLeftThick,
ArrowRight,
ArrowForward=ArrowRight,
ArrowRightBold,
ArrowRightBoldBox,
ArrowRightBoldBoxOutline,
ArrowRightBoldCircle,
ArrowRightBoldCircleOutline,
ArrowRightBoldHexagonOutline,
ArrowRightBoldOutline,
ArrowRightBox,
ArrowRightDropCircle,
ArrowRightDropCircleOutline,
ArrowRightThick,
ArrowSplitHorizontal,
ArrowSplitVertical,
ArrowTopLeft,
ArrowTopLeftBoldOutline,
ArrowTopLeftThick,
ArrowTopRight,
ArrowTopRightBoldOutline,
ArrowTopRightThick,
ArrowUp,
ArrowUpward=ArrowUp,
ArrowUpBold,
ArrowUpBoldBox,
ArrowUpBoldBoxOutline,
ArrowUpBoldCircle,
ArrowUpBoldCircleOutline,
ArrowUpBoldHexagonOutline,
ArrowUpBoldOutline,
ArrowUpBox,
ArrowUpDownBoldOutline,
ArrowUpDropCircle,
ArrowUpDropCircleOutline,
ArrowUpThick,
Artist,
Artstation,
AspectRatio,
Assistant,
Asterisk,
At,
AlternateEmail=At,
Atlassian,
Atom,
Attachment,
PaperclipHorizontal=Attachment,
AudioVideo,
Audiobook,
AugmentedReality,
AutoFix,
Magic=AutoFix,
Wand=AutoFix,
AutoFixHigh=AutoFix,
AutoUpload,
Autorenew,
AvTimer,
Axe,
Azure,
Babel,
Baby,
BabyBuggy,
ChildFriendly=BabyBuggy,
Backburger,
HamburgerMenuBack=Backburger,
Backspace,
BackspaceOutline,
BackupRestore,
SettingsBackupRestore=BackupRestore,
Badminton,
Shuttlecock=Badminton,
Balloon,
Ballot,
BallotOutline,
Bandcamp,
Bank,
AccountBalance=Bank,
Museum=Bank,
BankTransfer,
BankTransferIn,
BankTransferOut,
Barcode,
BarcodeScan,
BarcodeScanner=BarcodeScan,
Barley,
Grain=Barley,
BarleyOff,
GlutenFree=BarleyOff,
GrainOff=BarleyOff,
Barn,
Barrel,
Baseball,
BaseballBat,
Basecamp,
Basket,
ShoppingBasket=Basket,
BasketFill,
BasketUnfill,
Basketball,
YoutubeSports=Basketball,
Bat,
Battery,
BatteryFull=Battery,
BatteryStd=Battery,
Battery100=Battery,
Battery10,
Battery10Bluetooth,
Battery20,
Battery20Bluetooth,
Battery30,
Battery30Bluetooth,
Battery40,
Battery40Bluetooth,
Battery50,
Battery50Bluetooth,
Battery60,
Battery60Bluetooth,
Battery70,
Battery70Bluetooth,
Battery80,
Battery80Bluetooth,
Battery90,
Battery90Bluetooth,
BatteryAlert,
BatteryWarning=BatteryAlert,
BatteryAlertBluetooth,
BatteryWarningBluetooth=BatteryAlertBluetooth,
BatteryBluetooth,
BatteryBluetooth100=BatteryBluetooth,
BatteryBluetoothFull=BatteryBluetooth,
BatteryBluetoothVariant,
BatteryCharging,
BatteryChargingFull=BatteryCharging,
BatteryCharging10,
BatteryCharging100,
BatteryCharging20,
BatteryCharging30,
BatteryCharging40,
BatteryCharging50,
BatteryCharging60,
BatteryCharging70,
BatteryCharging80,
BatteryCharging90,
BatteryChargingOutline,
BatteryChargingWireless,
BatteryChargingWirelessFull=BatteryChargingWireless,
BatteryChargingWireless100=BatteryChargingWireless,
BatteryChargingWireless10,
BatteryChargingWireless20,
BatteryChargingWireless30,
BatteryChargingWireless40,
BatteryChargingWireless50,
BatteryChargingWireless60,
BatteryChargingWireless70,
BatteryChargingWireless80,
BatteryChargingWireless90,
BatteryChargingWirelessAlert,
BatteryChargingWirelessWarning=BatteryChargingWirelessAlert,
BatteryChargingWirelessOutline,
BatteryChargingWirelessEmpty=BatteryChargingWirelessOutline,
BatteryChargingWireless0=BatteryChargingWirelessOutline,
BatteryMinus,
BatteryNegative,
BatteryOutline,
Battery0=BatteryOutline,
BatteryEmpty=BatteryOutline,
BatteryPlus,
BatterySaver=BatteryPlus,
BatteryPositive,
BatteryUnknown,
BatteryUnknownBluetooth,
Battlenet,
BattleNet=Battlenet,
Beach,
Parasol=Beach,
Beaker,
Beats,
BedEmpty,
Beer,
Behance,
Bell,
Notifications=Bell,
BellOff,
NotificationsOff=BellOff,
BellOffOutline,
BellOutline,
NotificationsNone=BellOutline,
BellPlus,
AddAlert=BellPlus,
BellPlusOutline,
BellRing,
NotificationsActive=BellRing,
BellRingOutline,
BellSleep,
NotificationsPaused=BellSleep,
BellSleepOutline,
Beta,
Betamax,
Bible,
Bike,
Bicycle=Bike,
Cycling=Bike,
DirectionsBike=Bike,
Billiards,
EightBall=Billiards,
BilliardsRack,
PoolTable=BilliardsRack,
PoolRack=BilliardsRack,
SnookerRack=BilliardsRack,
PoolTriangle=BilliardsRack,
BilliardsTriangle=BilliardsRack,
SnookerTriangle=BilliardsRack,
Bing,
Binoculars,
Bio,
Biohazard,
Bitbucket,
Bitcoin,
BlackMesa,
Blackberry,
Blender,
Blinds,
BlockHelper,
Blogger,
Bluetooth,
BluetoothAudio,
BluetoothSearching=BluetoothAudio,
BluetoothConnect,
BluetoothConnected=BluetoothConnect,
BluetoothOff,
BluetoothDisabled=BluetoothOff,
BluetoothSettings,
SettingsBluetooth=BluetoothSettings,
BluetoothTransfer,
Blur,
BlurOn=Blur,
BlurLinear,
BlurOff,
BlurRadial,
BlurCircular=BlurRadial,
Bomb,
BombOff,
Bone,
Book,
BookLock,
BookSecure=BookLock,
BookLockOpen,
BookUnsecure=BookLockOpen,
BookMinus,
BookMultiple,
Books=BookMultiple,
BookMultipleMinus,
BooksMinus=BookMultipleMinus,
BookMultiplePlus,
BooksPlus=BookMultiplePlus,
BookMultipleRemove,
BooksRemove=BookMultipleRemove,
BookMultipleVariant,
BooksVariant=BookMultipleVariant,
BookOpen,
ChromeReaderMode=BookOpen,
BookOpenOutline,
BookOpenPageVariant,
AutoStories=BookOpenPageVariant,
BookOpenVariant,
ImportContacts=BookOpenVariant,
BookOutline,
BookPlus,
BookRemove,
BookVariant,
Class=BookVariant,
Bookmark,
TurnedIn=Bookmark,
BookmarkCheck,
BookmarkTick=BookmarkCheck,
BookmarkMinus,
BookmarkMinusOutline,
BookmarkMusic,
BookmarkOff,
BookmarkOffOutline,
BookmarkOutline,
BookmarkBorder=BookmarkOutline,
TurnedInNot=BookmarkOutline,
BookmarkPlus,
BookmarkPlusOutline,
BookmarkRemove,
Boombox,
Bootstrap,
BorderAll,
BorderAllVariant,
BorderBottom,
BorderBottomVariant,
BorderColor,
BorderColour=BorderColor,
BorderHorizontal,
BorderInside,
BorderLeft,
BorderLeftVariant,
BorderNone,
BorderClear=BorderNone,
BorderNoneVariant,
BorderOutside,
BorderOuter=BorderOutside,
BorderRight,
BorderRightVariant,
BorderStyle,
BorderTop,
BorderTopVariant,
BorderVertical,
BottleWine,
BowTie,
Bowl,
Bowling,
Box,
BoxCutter,
BoxShadow,
BoxingGlove,
Braille,
Brain,
Bridge,
Briefcase,
Work=Briefcase,
BriefcaseCheck,
BriefcaseTick=BriefcaseCheck,
BriefcaseDownload,
BriefcaseEdit,
BriefcaseMinus,
BriefcaseOutline,
BriefcasePlus,
BriefcaseRemove,
BriefcaseSearch,
BriefcaseUpload,
Brightness1,
Brightness2,
Brightness3,
Brightness4,
Brightness5,
BrightnessLow=Brightness5,
Brightness6,
BrightnessMedium=Brightness6,
Brightness7,
BrightnessHigh=Brightness7,
BrightnessAuto,
Broom,
Brush,
Paintbrush=Brush,
Buddhism,
Dharmachakra=Buddhism,
DharmaWheel=Buddhism,
ReligionBuddhist=Buddhism,
Buffer,
Bug,
BugReport=Bug,
BugCheck,
BugTick=BugCheck,
BugCheckOutline,
BugTickOutline=BugCheckOutline,
BugOutline,
Bulldozer,
BulletinBoard,
Bullhorn,
Announcement=Bullhorn,
Megaphone=Bullhorn,
BullhornOutline,
AnnouncementOutline=BullhornOutline,
MegaphoneOutline=BullhornOutline,
Bullseye,
BullseyeArrow,
TargetArrow=BullseyeArrow,
Bus,
DirectionsBus=Bus,
BusAlert,
BusWarning=BusAlert,
BusArticulatedEnd,
BusArticulatedFront,
BusClock,
DepartureBoard=BusClock,
BusDoubleDecker,
BusSchool,
BusSide,
Cached,
Cake,
CakeLayered,
CakeVariant,
Calculator,
CalculatorVariant,
Calendar,
Event=Calendar,
InsertInvitation=Calendar,
CalendarAlert,
EventAlert=CalendarAlert,
CalendarWarning=CalendarAlert,
CalendarBlank,
CalendarBlankOutline,
EventBlankOutline=CalendarBlankOutline,
CalendarCheck,
EventAvailable=CalendarCheck,
CalendarTask=CalendarCheck,
CalendarTick=CalendarCheck,
EventTick=CalendarCheck,
EventCheck=CalendarCheck,
CalendarClock,
EventClock=CalendarClock,
EventTime=CalendarClock,
CalendarTime=CalendarClock,
CalendarEdit,
EventEdit=CalendarEdit,
CalendarExport,
CalendarHeart,
EventHeart=CalendarHeart,
CalendarImport,
CalendarMultiple,
EventMultiple=CalendarMultiple,
Calendars=CalendarMultiple,
Events=CalendarMultiple,
CalendarMultipleCheck,
EventMultipleCheck=CalendarMultipleCheck,
CalendarMultipleTick=CalendarMultipleCheck,
CalendarsCheck=CalendarMultipleCheck,
CalendarsTick=CalendarMultipleCheck,
EventMultipleTick=CalendarMultipleCheck,
EventsCheck=CalendarMultipleCheck,
EventsTick=CalendarMultipleCheck,
CalendarMultiselect,
CalendarOutline,
EventOutline=CalendarOutline,
CalendarPlus,
EventPlus=CalendarPlus,
CalendarQuestion,
CalendarRsvp=CalendarQuestion,
EventQuestion=CalendarQuestion,
CalendarRange,
DateRange=CalendarRange,
EventRange=CalendarRange,
CalendarRangeOutline,
EventRangeOutline=CalendarRangeOutline,
CalendarRemove,
EventBusy=CalendarRemove,
CalendarSearch,
EventSearch=CalendarSearch,
CalendarStar,
EventStar=CalendarStar,
CalendarText,
EventNote=CalendarText,
CalendarToday,
CalendarDay=CalendarToday,
CalendarWeek,
EventWeek=CalendarWeek,
CalendarWeekBegin,
EventWeekBegin=CalendarWeekBegin,
CallMade,
CallMerge,
MergeType=CallMerge,
CallMissed,
CallReceived,
CallSplit,
Camcorder,
CamcorderBox,
CamcorderBoxOff,
CamcorderOff,
Camera,
Photography=Camera,
CameraAlt=Camera,
LocalSee=Camera,
PhotoCamera=Camera,
CameraAccount,
CameraUser=CameraAccount,
CameraBurst,
BurstMode=CameraBurst,
CameraControl,
CameraEnhance,
CameraEnhanceOutline,
CameraFront,
CameraFrontVariant,
CameraGopro,
CameraImage,
CameraIris,
CameraMeteringCenter,
CameraMeteringCentre=CameraMeteringCenter,
CameraMeteringMatrix,
CameraMeteringPartial,
CameraMeteringSpot,
CameraOff,
CameraPartyMode,
CameraRear,
CameraRearVariant,
CameraSwitch,
SwitchCamera=CameraSwitch,
CameraTimer,
Cancel,
Prohibited=Cancel,
Ban=Cancel,
DoNotDisturbAlt=Cancel,
Candle,
Candycane,
Cannabis,
CapsLock,
Car,
DirectionsCar=Car,
DriveEta=Car,
TimeToLeave=Car,
CarBattery,
CarConnected,
CarConvertible,
CarDoor,
CarElectric,
CarEstate,
CarHatchback,
CarKey,
CarLimousine,
CarMultiple,
CarPickup,
CarSide,
CarSports,
CarWash,
LocalCarWash=CarWash,
Caravan,
Card,
CardBulleted,
CardBulletedOff,
CardBulletedOffOutline,
CardBulletedOutline,
CardBulletedSettings,
CardBulletedSettingsOutline,
CardOutline,
CardText,
CardTextOutline,
Cards,
CardsClub,
SuitClubs=CardsClub,
CardsDiamond,
SuitDiamonds=CardsDiamond,
CardsHeart,
SuitHearts=CardsHeart,
CardsOutline,
CardsPlayingOutline,
CardsSpade,
SuitSpades=CardsSpade,
CardsVariant,
Carrot,
Cart,
Trolley=Cart,
LocalGroceryStore=Cart,
ShoppingCart=Cart,
CartOff,
TrolleyOff=CartOff,
RemoveShoppingCart=CartOff,
CartOutline,
TrolleyOutline=CartOutline,
CartPlus,
TrolleyPlus=CartPlus,
AddShoppingCart=CartPlus,
CaseSensitiveAlt,
Cash,
Money=Cash,
Cash100,
Money100=Cash100,
CashMultiple,
CashRefund,
CashUsd,
LocalAtm=CashUsd,
MoneyUsd=CashUsd,
Cassette,
Tape=Cassette,
Cast,
CastConnected,
CastOff,
Castle,
Cat,
Cctv,
ClosedCircuitTelevision=Cctv,
SecurityCamera=Cctv,
CeilingLight,
Cellphone,
MobilePhone=Cellphone,
Smartphone=Cellphone,
StayCurrentPortrait=Cellphone,
StayPrimaryPortrait=Cellphone,
CellphoneAndroid,
MobilePhoneAndroid=CellphoneAndroid,
SmartphoneAndroid=CellphoneAndroid,
CellphoneArrowDown,
CellphoneSystemUpdate=CellphoneArrowDown,
MobilePhoneArrowDown=CellphoneArrowDown,
SmartphoneArrowDown=CellphoneArrowDown,
CellphoneBasic,
MobilePhoneBasic=CellphoneBasic,
CellphoneDock,
MobilePhoneDock=CellphoneDock,
SmartphoneDock=CellphoneDock,
CellphoneErase,
PhonelinkErase=CellphoneErase,
MobilePhoneErase=CellphoneErase,
SmartphoneErase=CellphoneErase,
CellphoneIphone,
MobilePhoneIphone=CellphoneIphone,
SmartphoneIphone=CellphoneIphone,
CellphoneKey,
MobilePhoneKey=CellphoneKey,
SmartphoneKey=CellphoneKey,
CellphoneLink,
MobilePhoneLink=CellphoneLink,
SmartphoneLink=CellphoneLink,
Devices=CellphoneLink,
CellphoneLinkOff,
MobilePhoneLinkOff=CellphoneLinkOff,
SmartphoneLinkOff=CellphoneLinkOff,
PhonelinkOff=CellphoneLinkOff,
CellphoneLock,
PhonelinkLock=CellphoneLock,
MobilePhoneLock=CellphoneLock,
SmartphoneLock=CellphoneLock,
CellphoneMessage,
MobilePhoneMessage=CellphoneMessage,
SmartphoneMessage=CellphoneMessage,
CellphoneOff,
MobilePhoneOff=CellphoneOff,
SmartphoneOff=CellphoneOff,
MobileOff=CellphoneOff,
CellphoneScreenshot,
CellphoneSettings,
MobilePhoneSettings=CellphoneSettings,
SmartphoneSettings=CellphoneSettings,
SettingsCell=CellphoneSettings,
CellphoneSettingsVariant,
PhonelinkSetup=CellphoneSettingsVariant,
MobilePhoneSettingsVariant=CellphoneSettingsVariant,
SmartphoneSettingsVariant=CellphoneSettingsVariant,
CellphoneSound,
PhonelinkRing=CellphoneSound,
MobilePhoneSound=CellphoneSound,
SmartphoneSound=CellphoneSound,
CellphoneText,
MobilePhoneText=CellphoneText,
SmartphoneText=CellphoneText,
CellphoneWireless,
MobilePhoneWireless=CellphoneWireless,
SmartphoneWireless=CellphoneWireless,
Certificate,
ChairSchool,
ChartArc,
ChartAreaspline,
ChartBar,
ChartBarStacked,
ChartBubble,
BubbleChart=ChartBubble,
ChartDonut,
ChartDoughnut=ChartDonut,
DataUsage=ChartDonut,
ChartDonutVariant,
ChartDoughnutVariant=ChartDonutVariant,
ChartGantt,
ChartHistogram,
ChartLine,
ChartLineStacked,
ChartLineVariant,
ShowChart=ChartLineVariant,
ChartMultiline,
ChartPie,
ChartScatterplotHexbin,
ChartTimeline,
Chat,
ChatAlert,
ChatWarning=ChatAlert,
ChatProcessing,
Check,
Tick=Check,
Done=Check,
CheckAll,
TickAll=CheckAll,
DoneAll=CheckAll,
CheckMultiple=CheckAll,
Checks=CheckAll,
Ticks=CheckAll,
CheckCircle,
TickCircle=CheckCircle,
CheckCircleOutline,
TickCircleOutline=CheckCircleOutline,
CheckDecagram,
DecagramCheck=CheckDecagram,
Approve=CheckDecagram,
Approval=CheckDecagram,
TickDecagram=CheckDecagram,
CheckOutline,
DoneOutline=CheckOutline,
TickOutline=CheckOutline,
Checkbook,
Chequebook=Checkbook,
ChequeBook=Checkbook,
CheckboxBlank,
CheckboxBlankCircle,
CheckboxBlankCircleOutline,
CheckboxBlankOutline,
CheckBoxOutlineBlank=CheckboxBlankOutline,
CheckboxIntermediate,
CheckboxMarked,
CheckBox=CheckboxMarked,
CheckboxMarkedCircle,
CheckboxMarkedCircleOutline,
CheckboxMarkedOutline,
CheckboxMultipleBlank,
CheckboxesBlank=CheckboxMultipleBlank,
CheckboxMultipleBlankCircle,
CheckboxesBlankCircle=CheckboxMultipleBlankCircle,
CheckboxMultipleBlankCircleOutline,
CheckboxesBlankCircleOutline=CheckboxMultipleBlankCircleOutline,
CheckboxMultipleBlankOutline,
CheckboxesBlankOutline=CheckboxMultipleBlankOutline,
CheckboxMultipleMarked,
CheckboxesMultipleMarked=CheckboxMultipleMarked,
CheckboxesMarked=CheckboxMultipleMarked,
CheckboxMultipleMarkedCircle,
CheckboxesMarkedCircle=CheckboxMultipleMarkedCircle,
CheckboxMultipleMarkedCircleOutline,
CheckboxesMarkedCircleOutline=CheckboxMultipleMarkedCircleOutline,
CheckboxMultipleMarkedOutline,
CheckboxesMarkedOutline=CheckboxMultipleMarkedOutline,
Checkerboard,
ChefHat,
ChemicalWeapon,
ChessBishop,
ChessKing,
ChessKnight,
ChessHorse=ChessKnight,
ChessPawn,
ChessQueen,
ChessRook,
ChessCastle=ChessRook,
ChevronDoubleDown,
ChevronDoubleLeft,
ChevronDoubleRight,
ChevronDoubleUp,
ChevronDown,
ExpandMore=ChevronDown,
KeyboardArrowDown=ChevronDown,
ChevronDownBox,
ChevronDownBoxOutline,
ChevronDownCircle,
ChevronDownCircleOutline,
ChevronLeft,
KeyboardArrowLeft=ChevronLeft,
NavigateBefore=ChevronLeft,
ChevronLeftBox,
ChevronLeftBoxOutline,
ChevronLeftCircle,
ChevronLeftCircleOutline,
ChevronRight,
KeyboardArrowRight=ChevronRight,
NavigateNext=ChevronRight,
ChevronRightBox,
ChevronRightBoxOutline,
ChevronRightCircle,
ChevronRightCircleOutline,
ChevronUp,
ExpandLess=ChevronUp,
KeyboardArrowUp=ChevronUp,
ChevronUpBox,
ChevronUpBoxOutline,
ChevronUpCircle,
ChevronUpCircleOutline,
ChiliHot,
ChilliHot=ChiliHot,
ChiliMedium,
ChilliMedium=ChiliMedium,
ChiliMild,
ChilliMild=ChiliMild,
Chip,
Christianity,
ReligionChristian=Christianity,
Cross=Christianity,
Church,
Circle,
Lens=Circle,
CircleEditOutline,
CircleMedium,
CircleOutline,
CircleSlice1,
CircleSlice2,
CircleSlice3,
CircleSlice4,
CircleSlice5,
CircleSlice6,
CircleSlice7,
CircleSlice8,
CircleSmall,
Bullet=CircleSmall,
CiscoWebex,
City,
LocationCity=City,
CityVariant,
CityVariantOutline,
Clipboard,
ClipboardAccount,
ClipboardUser=ClipboardAccount,
AssignmentInd=ClipboardAccount,
ClipboardAlert,
ClipboardWarning=ClipboardAlert,
AssignmentLate=ClipboardAlert,
ClipboardArrowDown,
AssignmentReturned=ClipboardArrowDown,
ClipboardArrowLeft,
AssignmentReturn=ClipboardArrowLeft,
ClipboardCheck,
AssignmentTurnedIn=ClipboardCheck,
ClipboardTick=ClipboardCheck,
ClipboardCheckOutline,
ClipboardTickOutline=ClipboardCheckOutline,
ClipboardFlow,
ClipboardOutline,
ClipboardPlus,
ClipboardPulse,
ClipboardPulseOutline,
ClipboardText,
Assignment=ClipboardText,
ClipboardTextOutline,
Clippy,
Clock,
WatchLater=Clock,
ClockAlert,
ClockWarning=ClockAlert,
ClockAlertOutline,
ClockEnd,
ClockFast,
ClockIn,
ClockOut,
ClockOutline,
AccessTime=ClockOutline,
QueryBuilder=ClockOutline,
Schedule=ClockOutline,
ClockStart,
Close,
Clear=Close,
CloseBox,
CloseBoxOutline,
CloseCircle,
RemoveCircle=CloseCircle,
CloseCircleOutline,
HighlightOff=CloseCircleOutline,
CloseNetwork,
CloseOctagon,
Dangerous=CloseOctagon,
CloseOctagonOutline,
CloseOutline,
ClosedCaption,
Cc=ClosedCaption,
Cloud,
WbCloudy=Cloud,
CloudAlert,
CloudWarning=CloudAlert,
CloudBraces,
CloudJson=CloudBraces,
CloudCheck,
CloudDone=CloudCheck,
CloudTick=CloudCheck,
CloudCircle,
CloudDownload,
CloudDownloadOutline,
CloudOffOutline,
CloudOutline,
CloudQueue=CloudOutline,
CloudPrint,
CloudPrintOutline,
CloudQuestion,
CloudSearch,
CloudSearchOutline,
CloudSync,
CloudTags,
CloudXml=CloudTags,
CloudUpload,
Backup=CloudUpload,
CloudUploadOutline,
BackupOutline=CloudUploadOutline,
Clover,
Luck=Clover,
CodeArray,
CodeBraces,
CodeBrackets,
SquareBrackets=CodeBrackets,
CodeEqual,
CodeGreaterThan,
CodeGreaterThanOrEqual,
CodeLessThan,
CodeLessThanOrEqual,
CodeNotEqual,
CodeNotEqualVariant,
CodeParentheses,
CodeString,
CodeTags,
CodeTagsCheck,
CodeTagsTick=CodeTagsCheck,
Codepen,
Coffee,
Tea=Coffee,
FreeBreakfast=Coffee,
LocalCafe=Coffee,
CoffeeOutline,
TeaOutline=CoffeeOutline,
CupOutline=CoffeeOutline,
CoffeeToGo,
Coffin,
Cogs,
Manufacturing=Cogs,
Coin,
Coins,
Toll=Coins,
Collage,
AutoAwesomeMosaic=Collage,
CollapseAll,
AnimationMinus=CollapseAll,
CollapseAllOutline,
AnimationMinusOutline=CollapseAllOutline,
ColorHelper,
ColourHelper=ColorHelper,
Comment,
CommentAccount,
CommentUser=CommentAccount,
CommentAccountOutline,
CommentUserOutline=CommentAccountOutline,
CommentAlert,
CommentWarning=CommentAlert,
CommentAlertOutline,
CommentWarningOutline=CommentAlertOutline,
CommentArrowLeft,
CommentPrevious=CommentArrowLeft,
CommentArrowLeftOutline,
CommentPreviousOutline=CommentArrowLeftOutline,
CommentArrowRight,
CommentNext=CommentArrowRight,
CommentArrowRightOutline,
CommentNextOutline=CommentArrowRightOutline,
CommentCheck,
CommentTick=CommentCheck,
CommentCheckOutline,
CommentTickOutline=CommentCheckOutline,
CommentEye,
CommentEyeOutline,
CommentMultiple,
Comments=CommentMultiple,
CommentMultipleOutline,
CommentsOutline=CommentMultipleOutline,
CommentOutline,
CommentPlus,
CommentPlusOutline,
CommentProcessing,
CommentProcessingOutline,
CommentQuestion,
CommentQuestionOutline,
CommentRemove,
CommentRemoveOutline,
CommentSearch,
CommentSearchOutline,
CommentText,
CommentTextMultiple,
CommentsText=CommentTextMultiple,
CommentTextMultipleOutline,
CommentsTextOutline=CommentTextMultipleOutline,
CommentTextOutline,
Compare,
Compass,
Explore=Compass,
CompassOff,
CompassOffOutline,
CompassOutline,
Console,
Terminal=Console,
ConsoleLine,
TerminalLine=ConsoleLine,
ConsoleNetwork,
TerminalNetwork=ConsoleNetwork,
ContactMail,
Contacts,
Contain,
ContainEnd,
ContainStart,
ContentCopy,
ContentCut,
Scissors=ContentCut,
Clip=ContentCut,
ContentDuplicate,
ContentPaste,
ContentSave,
ContentSaveAll,
ContentSaveOutline,
ContentSaveSettings,
ContentSaveSettingsOutline,
Contrast,
ContrastBox,
ContrastCircle,
ControllerClassic,
ControllerClassicOutline,
Cookie,
Copyright,
Cordova,
Corn,
Counter,
Score=Counter,
Numbers=Counter,
Cow,
Crane,
Creation,
AutoAwesome=Creation,
CreditCard,
Payment=CreditCard,
CreditCardMultiple,
CreditCards=CreditCardMultiple,
CreditCardOff,
CreditCardPlus,
CreditCardRefund,
CreditCardScan,
CreditCardSettings,
PaymentSettings=CreditCardSettings,
Crop,
CropFree,
CropLandscape,
Crop54=CropLandscape,
CropPortrait,
CropRotate,
CropSquare,
Crosshairs,
GpsNotFixed=Crosshairs,
LocationSearching=Crosshairs,
CrosshairsGps,
GpsFixed=CrosshairsGps,
MyLocation=CrosshairsGps,
Crown,
Cryengine,
CrystalBall,
Cube,
CubeOutline,
CubeScan,
ViewInAr=CubeScan,
ViewInAugmentedReality=CubeScan,
CubeSend,
CubeUnfolded,
Cup,
CupOff,
CupWater,
LocalDrink=CupWater,
Cupcake,
Curling,
CurrencyBdt,
Taka=CurrencyBdt,
BangladeshiTaka=CurrencyBdt,
CurrencyBrl,
BrazilianReal=CurrencyBrl,
CurrencyBtc,
CurrencyChf,
Franc=CurrencyChf,
CurrencyCny,
Yuan=CurrencyCny,
Renminbi=CurrencyCny,
CurrencyEth,
Xi=CurrencyEth,
CurrencyEur,
Euro=CurrencyEur,
EuroSymbol=CurrencyEur,
CurrencyGbp,
Sterling=CurrencyGbp,
CurrencyInr,
Rupee=CurrencyInr,
CurrencyJpy,
Yen=CurrencyJpy,
CurrencyKrw,
Won=CurrencyKrw,
CurrencyKzt,
KazakhstaniTenge=CurrencyKzt,
CurrencyNgn,
Naira=CurrencyNgn,
CurrencyPhp,
PhilippinePeso=CurrencyPhp,
CurrencyRub,
Ruble=CurrencyRub,
CurrencySign,
CurrencyScarab=CurrencySign,
CurrencyTry,
Lira=CurrencyTry,
CurrencyTwd,
NewTaiwanDollar=CurrencyTwd,
CurrencyUsd,
AttachMoney=CurrencyUsd,
CurrencyUsdOff,
MoneyOff=CurrencyUsdOff,
CurrentAc,
AlternatingCurrent=CurrentAc,
CurrentDc,
DirectCurrent=CurrentDc,
CursorDefault,
CursorDefaultOutline,
CursorMove,
CursorPointer,
CursorHand=CursorPointer,
CursorText,
Database,
DatabaseCheck,
DatabaseTick=DatabaseCheck,
DatabaseEdit,
DatabaseExport,
DatabaseImport,
DatabaseLock,
DatabaseMinus,
DatabasePlus,
DatabaseSearch,
DeathStar,
DeathStarVariant,
DeathlyHallows,
HarryPotter=DeathlyHallows,
Debian,
DebugStepInto,
DebugStepOut,
DebugStepOver,
Decagram,
Starburst=Decagram,
DecagramOutline,
StarburstOutline=DecagramOutline,
DecimalDecrease,
DecimalIncrease,
Delete,
Trash=Delete,
Bin=Delete,
Rubbish=Delete,
Garbage=Delete,
RubbishBin=Delete,
GarbageCan=Delete,
DeleteCircle,
TrashCircle=DeleteCircle,
BinCircle=DeleteCircle,
GarbageCanCircle=DeleteCircle,
GarbageCircle=DeleteCircle,
RubbishBinCircle=DeleteCircle,
RubbishCircle=DeleteCircle,
TrashCanCircle=DeleteCircle,
DeleteCircleOutline,
BinCircleOutline=DeleteCircleOutline,
GarbageCanCircleOutline=DeleteCircleOutline,
GarbageCircleOutline=DeleteCircleOutline,
RubbishBinCircleOutline=DeleteCircleOutline,
RubbishCircleOutline=DeleteCircleOutline,
TrashCanCircleOutline=DeleteCircleOutline,
TrashCircleOutline=DeleteCircleOutline,
DeleteEmpty,
TrashEmpty=DeleteEmpty,
BinEmpty=DeleteEmpty,
RubbishEmpty=DeleteEmpty,
RubbishBinEmpty=DeleteEmpty,
TrashCanEmpty=DeleteEmpty,
GarbageEmpty=DeleteEmpty,
GarbageCanEmpty=DeleteEmpty,
DeleteForever,
DeleteForeverOutline,
DeleteOutline,
GarbageOutline=DeleteOutline,
BinOutline=DeleteOutline,
RubbishOutline=DeleteOutline,
GarbageCanOutline=DeleteOutline,
RubbishBinOutline=DeleteOutline,
TrashOutline=DeleteOutline,
DeleteRestore,
TrashRestore=DeleteRestore,
BinRestore=DeleteRestore,
RestoreFromTrash=DeleteRestore,
DeleteSweep,
DeleteVariant,
TrashVariant=DeleteVariant,
BinVariant=DeleteVariant,
Delta,
ChangeHistory=Delta,
DeskLamp,
Deskphone,
DesktopClassic,
ComputerClassic=DesktopClassic,
DesktopMac,
DesktopMacDashboard,
DesktopTower,
DesktopTowerMonitor,
Details,
DeveloperBoard,
Deviantart,
Dialpad,
Keypad=Dialpad,
Diamond,
DiamondOutline,
DiamondStone,
Jewel=DiamondStone,
Dice1,
Die1=Dice1,
DiceOne=Dice1,
Dice2,
Die2=Dice2,
DiceTwo=Dice2,
Dice3,
Die3=Dice3,
DiceThree=Dice3,
Dice4,
Die4=Dice4,
DiceFour=Dice4,
Dice5,
Die5=Dice5,
DiceFive=Dice5,
Dice6,
Die6=Dice6,
DiceSix=Dice6,
DiceD10,
DieD10=DiceD10,
DiceD12,
DiceD20,
DieD20=DiceD20,
DiceD4,
DieD4=DiceD4,
DiceD6,
DieD6=DiceD6,
DiceD8,
DieD8=DiceD8,
DiceMultiple,
DieMultiple=DiceMultiple,
Dictionary,
DipSwitch,
Directions,
DirectionsFork,
Disc,
DiscAlert,
DiscFull=DiscAlert,
DiscWarning=DiscAlert,
DiscPlayer,
Discord,
Dishwasher,
Disqus,
DisqusOutline,
Division,
DivisionBox,
Dlna,
Dna,
Helix=Dna,
Dns,
DnsOutline,
DoNotDisturb,
NoEntry=DoNotDisturb,
DoNotDisturbOff,
Docker,
Doctor,
Dog,
DogService,
GuideDog=DogService,
DogSide,
Dolby,
Domain,
Building=Domain,
Company=Domain,
Business=Domain,
Donkey,
Door,
DoorClosed,
DoorOpen,
DoorbellVideo,
DotNet,
DotsHorizontal,
EllipsisHorizontal=DotsHorizontal,
MoreHoriz=DotsHorizontal,
DotsHorizontalCircle,
EllipsisHorizontalCircle=DotsHorizontalCircle,
MoreCircle=DotsHorizontalCircle,
DotsHorizontalCircleOutline,
EllipsisHorizontalCircleOutline=DotsHorizontalCircleOutline,
MoreCircleOutline=DotsHorizontalCircleOutline,
DotsVertical,
EllipsisVertical=DotsVertical,
MoreVert=DotsVertical,
DotsVerticalCircle,
EllipsisVerticalCircle=DotsVerticalCircle,
DotsVerticalCircleOutline,
EllipsisVerticalCircleOutline=DotsVerticalCircleOutline,
Douban,
Download,
GetApp=Download,
DownloadMultiple,
Downloads=DownloadMultiple,
DownloadNetwork,
DownloadOutline,
Drag,
DragHorizontal,
DragVariant,
DragVertical,
Drawing,
DrawingBox,
Dribbble,
DribbbleBox,
Drone,
Dropbox,
Drupal,
Duck,
Dumbbell,
Weights=Dumbbell,
EarHearing,
EarHearingOff,
HearingImpaired=EarHearingOff,
Earth,
Globe=Earth,
Public=Earth,
Planet=Earth,
EarthBox,
EarthBoxOff,
EarthOff,
Edge,
MicrosoftEdge=Edge,
Egg,
EggEaster,
EightTrack,
Eject,
EjectOutline,
Elephant,
ElevationDecline,
ElevationRise,
Elevator,
Email,
LocalPostOffice=Email,
Mail=Email,
Markunread=Email,
Envelope=Email,
EmailAlert,
EmailWarning=EmailAlert,
EnvelopeAlert=EmailAlert,
EnvelopeWarning=EmailAlert,
EmailCheck,
EmailTick=EmailCheck,
EmailCheckOutline,
EmailTickOutline=EmailCheckOutline,
EmailLock,
EnvelopeSecure=EmailLock,
EmailSecure=EmailLock,
EnvelopeLock=EmailLock,
EmailMarkAsUnread,
EmailOpen,
Drafts=EmailOpen,
EnvelopeOpen=EmailOpen,
EmailOpenOutline,
EnvelopeOpenOutline=EmailOpenOutline,
EmailOutline,
MailOutline=EmailOutline,
EnvelopeOutline=EmailOutline,
EmailPlus,
EmailPlusOutline,
EmailSearch,
EmailSearchOutline,
EmailVariant,
EnvelopeVariant=EmailVariant,
Ember,
Emby,
Emoticon,
Smiley=Emoticon,
InsertEmoticon=Emoticon,
Mood=Emoticon,
SentimentVerySatisfied=Emoticon,
EmoticonCool,
SmileyCool=EmoticonCool,
EmoticonDead,
SmileyDead=EmoticonDead,
EmoticonDevil,
SmileyDevil=EmoticonDevil,
EmoticonExcited,
SmileyExcited=EmoticonExcited,
EmoticonHappy,
SmileyHappy=EmoticonHappy,
EmoticonNeutral,
SmileyNeutral=EmoticonNeutral,
EmoticonPoop,
SmileyPoop=EmoticonPoop,
EmoticonSad,
SmileySad=EmoticonSad,
EmoticonTongue,
SmileyTongue=EmoticonTongue,
Engine,
Motor=Engine,
EngineOff,
MotorOff=EngineOff,
EngineOffOutline,
MotorOffOutline=EngineOffOutline,
EngineOutline,
MotorOutline=EngineOutline,
Equal,
EqualBox,
Eraser,
EraserVariant,
Escalator,
Et,
Ethereum,
Ethernet,
EthernetCable,
EthernetCableOff,
Etsy,
EvStation,
Eventbrite,
Evernote,
Exclamation,
ExitRun,
EmergencyExit=ExitRun,
ExitToApp,
ExpandAll,
AnimationPlus=ExpandAll,
ExpandAllOutline,
AnimationPlusOutline=ExpandAllOutline,
Exponent,
ExponentBox,
Export,
ExportVariant,
Eye,
Show=Eye,
Visibility=Eye,
RemoveRedEye=Eye,
EyeCircle,
EyeCircleOutline,
EyeOff,
Hide=EyeOff,
VisibilityOff=EyeOff,
EyeOffOutline,
HideOutline=EyeOffOutline,
VisibilityOffOutline=EyeOffOutline,
EyeOutline,
ShowOutline=EyeOutline,
VisibilityOutline=EyeOutline,
EyePlus,
EyePlusOutline,
EyeSettings,
EyeSettingsOutline,
Eyedropper,
EyedropperVariant,
Colorize=EyedropperVariant,
Colourise=EyedropperVariant,
Face,
FaceOutline,
FaceProfile,
Facebook,
FacebookBox,
FacebookMessenger,
FacebookWorkplace,
Factory,
Industrial=Factory,
Fan,
FanOff,
FastForward,
FastForwardOutline,
Fax,
Feather,
FeatureSearch,
FeatureSearchOutline,
Fedora,
Ferry,
CargoShip=Ferry,
Boat=Ferry,
Ship=Ferry,
DirectionsBoat=Ferry,
DirectionsFerry=Ferry,
File,
InsertDriveFile=File,
Draft=File,
FileAccount,
FileUser=FileAccount,
FileAlert,
FileWarning=FileAlert,
FileAlertOutline,
FileWarningOutline=FileAlertOutline,
FileCabinet,
FilingCabinet=FileCabinet,
FileChart,
FileReport=FileChart,
FileCheck,
FileTick=FileCheck,
FileCloud,
FileCompare,
FileDelimited,
FileCsv=FileDelimited,
FileDocument,
FileDocumentBox,
FileDocumentBoxMultiple,
FileDocumentBoxes=FileDocumentBoxMultiple,
FileDocumentBoxMultipleOutline,
FileDocumentBoxesOutline=FileDocumentBoxMultipleOutline,
FileDocumentBoxOutline,
FileDocumentOutline,
FileDownload,
FileDownloadOutline,
FileExcel,
FileExcelBox,
FileExport,
FileFind,
PrintPreview=FileFind,
FindInPage=FileFind,
FileFindOutline,
FileHidden,
FileImage,
FileImport,
FileLock,
FileMove,
FileMultiple,
Files=FileMultiple,
FileMusic,
FileOutline,
FilePdf,
FilePdfBox,
FilePercent,
FilePlus,
NoteAdd=FilePlus,
FilePowerpoint,
FilePowerpointBox,
FilePresentationBox,
FileQuestion,
FileRemove,
FileReplace,
FileReplaceOutline,
FileRestore,
RestorePage=FileRestore,
FileSend,
FileTree,
Subtasks=FileTree,
FileUndo,
FileRevert=FileUndo,
FileDiscard=FileUndo,
FileUpload,
FileUploadOutline,
FileVideo,
FileWord,
FileWordBox,
FileXml,
Film,
CameraRoll=Film,
Filmstrip,
LocalMovies=Filmstrip,
Theaters=Filmstrip,
FilmstripOff,
Filter,
Funnel=Filter,
FilterOutline,
FunnelOutline=FilterOutline,
FilterRemove,
FunnelRemove=FilterRemove,
FilterRemoveOutline,
FunnelRemoveOutline=FilterRemoveOutline,
FilterVariant,
FilterList=FilterVariant,
Finance,
ChartFinance=Finance,
FindReplace,
Fingerprint,
Fire,
Whatshot=Fire,
Flame=Fire,
FireTruck,
FireEngine=FireTruck,
Firebase,
Firefox,
MozillaFirefox=Firefox,
Fish,
Flag,
AssistantPhoto=Flag,
FlagCheckered,
FlagMinus,
FlagOutline,
FlagPlus,
FlagRemove,
FlagTriangle,
FlagVariant,
FlagVariantOutline,
Flash,
LightningBolt=Flash,
FlashOn=Flash,
Electricity=Flash,
FlashAuto,
FlashCircle,
Amp=FlashCircle,
OfflineBolt=FlashCircle,
LightningBoltCircle=FlashCircle,
FlashOff,
FlashOutline,
LightningBoltOutline=FlashOutline,
FlashRedEye,
Flashlight,
Torch=Flashlight,
FlashlightOff,
TorchOff=FlashlightOff,
Flask,
FlaskEmpty,
FlaskEmptyOutline,
FlaskOutline,
Flattr,
FlipToBack,
FlipToFront,
FloorLamp,
FloorPlan,
Floppy,
FloppyVariant,
Flower,
LocalFlorist=Flower,
FlowerOutline,
LocalFloristOutline=FlowerOutline,
FlowerTulip,
FlowerTulipOutline,
Folder,
FolderAccount,
FolderUser=FolderAccount,
FolderShared=FolderAccount,
FolderAccountOutline,
FolderUserOutline=FolderAccountOutline,
FolderSharedOutline=FolderAccountOutline,
FolderClock,
FolderClockOutline,
FolderDownload,
FolderEdit,
FolderGoogleDrive,
FolderMydrive=FolderGoogleDrive,
FolderImage,
FolderKey,
FolderKeyNetwork,
FolderLock,
FolderLockOpen,
FolderMove,
FolderMultiple,
Folders=FolderMultiple,
FolderMultipleImage,
PermMedia=FolderMultipleImage,
FoldersImage=FolderMultipleImage,
FolderMultipleOutline,
FoldersOutline=FolderMultipleOutline,
FolderNetwork,
FolderOpen,
FolderOutline,
FolderPlus,
CreateNewFolder=FolderPlus,
FolderPlusOutline,
CreateNewFolderOutline=FolderPlusOutline,
FolderRemove,
FolderRemoveOutline,
FolderSearch,
FolderSearchOutline,
FolderStar,
FolderSpecial=FolderStar,
FolderStarOutline,
FolderSpecialOutline=FolderStarOutline,
FolderUpload,
FontAwesome,
Food,
FoodApple,
FoodCroissant,
FoodForkDrink,
FoodOff,
FoodVariant,
Football,
FootballAmerican=Football,
FootballAustralian,
FootballHelmet,
Forklift,
FormatAlignBottom,
FormatAlignCenter,
FormatAlignCentre=FormatAlignCenter,
FormatAlignJustify,
FormatAlignLeft,
FormatAlignMiddle,
FormatAlignRight,
FormatAlignTop,
FormatAnnotationMinus,
FormatAnnotationPlus,
FormatBold,
FormatClear,
FormatColorFill,
FormatColourFill=FormatColorFill,
FormatColorText,
FormatColourText=FormatColorText,
FormatColumns,
FormatFloatCenter,
FormatFloatCentre=FormatFloatCenter,
FormatFloatLeft,
FormatFloatNone,
FormatFloatRight,
FormatFont,
FormatFontSizeDecrease,
FormatFontSizeIncrease,
FormatHeader1,
FormatHeader2,
FormatHeader3,
FormatHeader4,
FormatHeader5,
FormatHeader6,
FormatHeaderDecrease,
FormatHeaderEqual,
FormatHeaderIncrease,
FormatHeaderPound,
FormatHorizontalAlignCenter,
FormatHorizontalAlignCentre=FormatHorizontalAlignCenter,
FormatHorizontalAlignLeft,
FormatHorizontalAlignRight,
FormatIndentDecrease,
FormatIndentIncrease,
FormatItalic,
FormatLetterCase,
FormatLetterCaseLower,
FormatLowercase=FormatLetterCaseLower,
FormatLetterCaseUpper,
FormatUppercase=FormatLetterCaseUpper,
FormatLineSpacing,
FormatLineStyle,
FormatLineWeight,
FormatListBulleted,
FormatListBulletedType,
FormatListCheckbox,
FormatListChecks,
FormatListNumbers,
FormatListNumbered=FormatListNumbers,
FormatPageBreak,
FormatPaint,
FormatParagraph,
FormatPilcrow,
FormatQuoteClose,
FormatQuoteOpen,
FormatRotate90,
Rotate90DegreesCcw=FormatRotate90,
FormatRotateNinety=FormatRotate90,
FormatSection,
FormatSize,
FormatStrikethrough,
FormatStrikethroughVariant,
StrikethroughS=FormatStrikethroughVariant,
FormatSubscript,
FormatSuperscript,
FormatText,
FormatTextdirectionLToR,
FormatTextdirectionRToL,
FormatTitle,
FormatUnderline,
FormatUnderlined=FormatUnderline,
FormatVerticalAlignBottom,
FormatVerticalAlignCenter,
FormatVerticalAlignCentre=FormatVerticalAlignCenter,
FormatVerticalAlignTop,
FormatWrapInline,
FormatWrapSquare,
FormatWrapTight,
FormatWrapTopBottom,
Forum,
MessageGroup=Forum,
QuestionAnswer=Forum,
ForumOutline,
ChatOutline=ForumOutline,
Forward,
Fountain,
Foursquare,
Freebsd,
Fridge,
RefrigeratorFilled=Fridge,
FridgeFilled=Fridge,
Refrigerator=Fridge,
FridgeBottom,
RefrigeratorFilledTop=FridgeBottom,
FridgeOutline,
Kitchen=FridgeOutline,
RefrigeratorOutline=FridgeOutline,
FridgeTop,
RefrigeratorFilledBottom=FridgeTop,
Fuel,
Fullscreen,
FullscreenExit,
Function,
FunctionVariant,
Gamepad,
Games=Gamepad,
GamepadVariant,
Garage,
GarageAlert,
GarageWarning=GarageAlert,
GarageOpen,
GasCylinder,
GasStation,
GasPump=GasStation,
PetrolPump=GasStation,
PetrolStation=GasStation,
LocalGasStation=GasStation,
Gate,
GateAnd,
LogicGateAnd=GateAnd,
GateNand,
LogicGateNand=GateNand,
GateNor,
LogicGateNor=GateNor,
GateNot,
LogicGateNot=GateNot,
GateOr,
LogicGateOr=GateOr,
GateXnor,
LogicGateXnor=GateXnor,
GateXor,
LogicGateXor=GateXor,
Gauge,
SwapDrivingAppsWheel=Gauge,
GaugeEmpty,
GaugeFull,
GaugeLow,
Gavel,
CourtHammer=Gavel,
GenderFemale,
GenderMale,
GenderMaleFemale,
GenderTransgender,
Gentoo,
Gesture,
GestureDoubleTap,
InteractionDoubleTap=GestureDoubleTap,
HandDoubleTap=GestureDoubleTap,
GesturePinch,
GestureSpread,
GestureSwipeDown,
GestureSwipeHorizontal,
GestureSwipeLeft,
GestureSwipeRight,
GestureSwipeUp,
GestureSwipeVertical,
GestureTap,
InteractionTap=GestureTap,
HandTap=GestureTap,
GestureTwoDoubleTap,
GestureTwoTap,
Ghost,
Inky=Ghost,
Blinky=Ghost,
Pinky=Ghost,
Clyde=Ghost,
GhostOff,
Gift,
Donate=Gift,
Present=Gift,
Git,
GithubBox,
GithubCircle,
GithubFace,
Gitlab,
GlassCocktail,
LocalBar=GlassCocktail,
Cocktail=GlassCocktail,
Martini=GlassCocktail,
GlassFlute,
GlassMug,
GlassStange,
GlassTulip,
GlassWine,
Glassdoor,
Glasses,
GlobeModel,
Gmail,
Gnome,
Gog,
GogCom=Gog,
Golf,
GolfCourse=Golf,
Gondola,
CableCar=Gondola,
Google,
GoogleAllo,
GoogleAnalytics,
GoogleAssistant,
GoogleCardboard,
GoogleChrome,
Chromecast=GoogleChrome,
GoogleCircles,
GoogleCirclesCommunities,
GoogleCirclesExtended,
GoogleCirclesGroup,
GoogleController,
GoogleControllerOff,
GoogleDrive,
AttachDrive=GoogleDrive,
GoogleEarth,
GoogleFit,
GoogleGlass,
GoogleHangouts,
GoogleHome,
GoogleKeep,
GoogleLens,
GoogleMaps,
GoogleNearby,
GooglePages,
GooglePhotos,
GooglePhysicalWeb,
GooglePlay,
GooglePlus,
GooglePlusBox,
GoogleSpreadsheet,
GoogleTranslate,
GTranslate=GoogleTranslate,
GoogleWallet,
WalletProduct=GoogleWallet,
Gpu,
Gradient,
Graphql,
GraveStone,
Headstone=GraveStone,
Tombstone=GraveStone,
Cemetery=GraveStone,
Graveyard=GraveStone,
GreasePencil,
GreaterThan,
GreaterThanOrEqual,
Grid,
GridOn=Grid,
GridLarge,
GridOff,
Group,
GuitarAcoustic,
GuitarElectric,
GuitarPick,
GuitarPickOutline,
GuyFawkesMask,
Hackernews,
Hail,
Halloween,
PumpkinFace=Halloween,
PumpkinCarved=Halloween,
JackOLantern=Halloween,
Hamburger,
Hammer,
Hand,
HandOkay,
HandPeace,
HandPeaceVariant,
HandPointingDown,
HandPointingLeft,
HandPointingRight,
HandPointingUp,
Hanger,
HardHat,
Harddisk,
HatFedora,
Headphones,
HeadphonesBluetooth,
HeadphonesBox,
HeadphonesOff,
HeadphonesSettings,
Headset,
HeadsetMic=Headset,
HeadsetDock,
HeadsetOff,
Heart,
Favorite=Heart,
Favourite=Heart,
HeartBox,
HeartBoxOutline,
HeartBroken,
HeartCircle,
HeartCircleOutline,
HeartHalf,
HeartHalfFull,
HeartHalfOutline,
HeartMultiple,
Hearts=HeartMultiple,
HeartMultipleOutline,
HeartsOutline=HeartMultipleOutline,
HeartOff,
HeartOutline,
FavoriteBorder=HeartOutline,
FavouriteBorder=HeartOutline,
FavoriteOutline=HeartOutline,
FavouriteOutline=HeartOutline,
HeartPulse,
Helicopter,
Help,
QuestionMark=Help,
HelpBox,
QuestionMarkBox=HelpBox,
HelpCircle,
QuestionMarkCircle=HelpCircle,
HelpCircleOutline,
HelpOutline=HelpCircleOutline,
QuestionMarkCircleOutline=HelpCircleOutline,
HelpNetwork,
QuestionNetwork=HelpNetwork,
HelpRhombus,
QuestionMarkRhombus=HelpRhombus,
HelpRhombusOutline,
QuestionMarkRhombusOutline=HelpRhombusOutline,
Hexagon,
HexagonMultiple,
Hexagons=HexagonMultiple,
HexagonOutline,
HexagonSlice1,
HexagonSlice2,
HexagonSlice3,
HexagonSlice4,
HexagonSlice5,
HexagonSlice6,
Hexagram,
HexagramOutline,
HighDefinition,
Hd=HighDefinition,
HighDefinitionBox,
HdBox=HighDefinitionBox,
Highway,
Autobahn=Highway,
Motorway=Highway,
Hinduism,
ReligionHindu=Hinduism,
Om=Hinduism,
History,
Recent=History,
Latest=History,
ClockArrow=History,
Counterclockwise=History,
HockeyPuck,
HockeySticks,
Hololens,
Home,
House=Home,
HomeAccount,
HomeUser=HomeAccount,
HomeAlert,
HomeWarning=HomeAlert,
HomeAssistant,
HomeAutomation,
HomeCircle,
HouseCircle=HomeCircle,
HomeCurrencyUsd,
HomeHeart,
Family=HomeHeart,
HomeLock,
HomeLockOpen,
HomeMapMarker,
HouseMapMarker=HomeMapMarker,
HomeMinus,
HomeModern,
HouseModern=HomeModern,
HomeOutline,
HouseOutline=HomeOutline,
HomePlus,
HomeVariant,
HouseVariant=HomeVariant,
HomeVariantOutline,
HouseVariantOutline=HomeVariantOutline,
Hook,
HookOff,
Hops,
Horseshoe,
Hospital,
LocalHospital=Hospital,
HospitalBuilding,
HospitalMarker,
HotTub,
Hotel,
Bed=Hotel,
LocalHotel=Hotel,
Houzz,
HouzzBox,
Hulu,
Human,
Accessibility=Human,
HumanChild,
HumanFemale,
Woman=HumanFemale,
HumanFemaleBoy,
Mother=HumanFemaleBoy,
Mom=HumanFemaleBoy,
WomanChild=HumanFemaleBoy,
Mum=HumanFemaleBoy,
HumanFemaleFemale,
WomanWoman=HumanFemaleFemale,
Women=HumanFemaleFemale,
HumanFemaleGirl,
HumanGreeting,
HumanHandsdown,
HumanHandsup,
HumanMale,
Man=HumanMale,
HumanMaleBoy,
Father=HumanMaleBoy,
Dad=HumanMaleBoy,
ManChild=HumanMaleBoy,
HumanMaleFemale,
Wc=HumanMaleFemale,
ManWoman=HumanMaleFemale,
HumanMaleGirl,
HumanMaleMale,
ManMan=HumanMaleMale,
Men=HumanMaleMale,
HumanPregnant,
PregnantWoman=HumanPregnant,
HumbleBundle,
IceCream,
Image,
InsertPhoto=Image,
ImageAlbum,
PhotoAlbum=ImageAlbum,
ImageArea,
ImageAreaClose,
ImageBroken,
ImageBrokenVariant,
BrokenImage=ImageBrokenVariant,
ImageFilter,
ImageMultipleOutline=ImageFilter,
ImagesOutline=ImageFilter,
ImageFilterBlackWhite,
FilterBAndW=ImageFilterBlackWhite,
ImageFilterCenterFocus,
ImageFilterCentreFocus=ImageFilterCenterFocus,
ImageFilterCenterFocusWeak,
ImageFilterCentreFocusWeak=ImageFilterCenterFocusWeak,
ImageFilterDrama,
ImageFilterFrames,
ImageFilterHdr,
Mountain=ImageFilterHdr,
Landscape=ImageFilterHdr,
ImageFilterNone,
ImageFilterTiltShift,
ImageFilterVintage,
ImageMove,
ImageMultiple,
Collections=ImageMultiple,
PhotoLibrary=ImageMultiple,
Images=ImageMultiple,
ImageOff,
ImageOutline,
ImagePlus,
ImageSearch,
ImageSearchOutline,
Import,
Inbox,
InboxArrowDown,
MoveToInbox=InboxArrowDown,
InboxArrowUp,
InboxMultiple,
Inboxes=InboxMultiple,
InboxMultipleOutline,
InboxesOutline=InboxMultipleOutline,
Incognito,
Infinity,
Information,
About=Information,
InformationOutline,
InfoOutline=InformationOutline,
AboutOutline=InformationOutline,
InformationVariant,
Instagram,
Instapaper,
InternetExplorer,
InvertColors,
InvertColours=InvertColors,
Ip,
IpNetwork,
Islam,
ReligionIslamic=Islam,
StarAndCrescent=Islam,
ReligionMuslim=Islam,
Itunes,
Jeepney,
Jira,
Jquery,
Jsfiddle,
Json,
Judaism,
Jewish=Judaism,
ReligionJudaic=Judaism,
StarOfDavid=Judaism,
MagenDavid=Judaism,
Karate,
MartialArts=Karate,
Kickboxing=Karate,
Keg,
Kettle,
Key,
VpnKey=Key,
KeyChange,
KeyMinus,
KeyPlus,
KeyRemove,
KeyVariant,
Keyboard,
KeyboardBackspace,
KeyboardCaps,
KeyboardCapslock=KeyboardCaps,
KeyboardClose,
KeyboardHide=KeyboardClose,
KeyboardOff,
KeyboardOutline,
KeyboardReturn,
KeyboardSettings,
KeyboardSettingsOutline,
KeyboardTab,
KeyboardVariant,
Kickstarter,
Knife,
KnifeMilitary,
Dagger=KnifeMilitary,
Kodi,
Label,
LabelOff,
LabelOffOutline,
LabelOutline,
LabelVariant,
LabelVariantOutline,
Ladybug,
Bugfood=Ladybug,
Ladybird=Ladybug,
Lambda,
Lamp,
Lan,
LanConnect,
LanDisconnect,
LanPending,
LanguageC,
LanguageCpp,
LanguageCsharp,
LanguageCss3,
LanguageGo,
LanguageHtml5,
LanguageJava,
LanguageJavascript,
LanguageLua,
LanguagePhp,
LanguagePython,
LanguagePythonText,
LanguageR,
LanguageRubyOnRails,
LanguageSwift,
LanguageTypescript,
Laptop,
Computer=Laptop,
LaptopChromebook,
LaptopMac,
LaptopOff,
LaptopWindows,
Laravel,
Lastfm,
Lastpass,
Launch,
LavaLamp,
Layers,
LayersOff,
LayersClear=LayersOff,
LayersOffOutline,
LayersOutline,
LeadPencil,
Leaf,
LedOff,
LedOn,
LedOutline,
LedStrip,
LedVariantOff,
LedVariantOn,
LedVariantOutline,
LessThan,
LessThanOrEqual,
Library,
LocalLibrary=Library,
LibraryBooks,
LibraryMusic,
LibraryPlus,
AddToPhotos=LibraryPlus,
LibraryAdd=LibraryPlus,
Queue=LibraryPlus,
LibraryShelves,
Lifebuoy,
LifePreserver=Lifebuoy,
Support=Lifebuoy,
LightSwitch,
Lightbulb,
LightbulbOn,
LightbulbOnOutline,
LightbulbOutline,
Lighthouse,
Beacon=Lighthouse,
LighthouseOn,
Link,
InsertLink=Link,
LinkOff,
LinkVariant,
LinkVariantOff,
Linkedin,
LinkedinBox,
Linux,
Tux=Linux,
LinuxMint,
Litecoin,
Loading,
Lock,
Https=Lock,
LockAlert,
LockWarning=LockAlert,
LockClock,
ConfidentialMode=LockClock,
LockOpen,
LockOpenOutline,
LockOutline,
LockPattern,
LockPlus,
EnhancedEncryption=LockPlus,
LockQuestion,
ForgotPassword=LockQuestion,
LockReset,
PasswordReset=LockReset,
LockSmart,
Locker,
LockerMultiple,
Lockers=LockerMultiple,
Login,
LoginVariant,
Logout,
LogoutVariant,
Looks,
Rainbow=Looks,
Loop,
Loupe,
Lumx,
Lyft,
Magnet,
MagnetOn,
Magnify,
Search=Magnify,
MagnifyClose,
MagnifyMinus,
ZoomOut=MagnifyMinus,
MagnifyMinusCursor,
ZoomOutCursor=MagnifyMinusCursor,
MagnifyMinusOutline,
ZoomOutOutline=MagnifyMinusOutline,
MagnifyPlus,
ZoomIn=MagnifyPlus,
MagnifyPlusCursor,
ZoomInCursor=MagnifyPlusCursor,
MagnifyPlusOutline,
ZoomInOutline=MagnifyPlusOutline,
MailRu,
Mailbox,
MarkunreadMailbox=Mailbox,
Map,
MapLegend,
MapMarker,
Location=MapMarker,
AddressMarker=MapMarker,
LocationOn=MapMarker,
Place=MapMarker,
Room=MapMarker,
MapMarkerCircle,
ExploreNearby=MapMarkerCircle,
MapMarkerDistance,
MapMarkerMinus,
MapMarkerMultiple,
MapMarkers=MapMarkerMultiple,
MapMarkerOff,
LocationOff=MapMarkerOff,
MapMarkerOutline,
MapMarkerPlus,
AddLocation=MapMarkerPlus,
MapMarkerRadius,
MapMinus,
MapOutline,
MapPlus,
MapSearch,
MapSearchOutline,
Mapbox,
Margin,
Markdown,
Marker,
Highlighter=Marker,
MarkerCheck,
Beenhere=MarkerCheck,
MarkerTick=MarkerCheck,
Mastodon,
MastodonVariant,
MaterialDesign,
MaterialUi,
MathCompass,
Matrix,
Maxcdn,
Medal,
MedicalBag,
FirstAidKit=MedicalBag,
Medium,
Meetup,
Memory,
Menu,
HamburgerMenu=Menu,
MenuDown,
ArrowDropDown=MenuDown,
MenuDownOutline,
MenuLeft,
MenuLeftOutline,
MenuOpen,
MenuRight,
MenuRightOutline,
MenuSwap,
MenuSwapOutline,
MenuUp,
ArrowDropUp=MenuUp,
MenuUpOutline,
Message,
ChatBubble=Message,
MessageAlert,
Feedback=MessageAlert,
MessageWarning=MessageAlert,
SmsFailed=MessageAlert,
MessageAlertOutline,
FeedbackOutline=MessageAlertOutline,
MessageWarningOutline=MessageAlertOutline,
SmsFailedOutline=MessageAlertOutline,
MessageBulleted,
SpeakerNotes=MessageBulleted,
MessageBulletedOff,
SpeakerNotesOff=MessageBulletedOff,
MessageDraw,
RateReview=MessageDraw,
MessageImage,
Mms=MessageImage,
MessageOutline,
ChatBubbleOutline=MessageOutline,
MessagePlus,
MessageProcessing,
Sms=MessageProcessing,
Textsms=MessageProcessing,
MessageReply,
ModeComment=MessageReply,
MessageReplyText,
InsertComment=MessageReplyText,
MessageSettings,
MessageSettingsVariant,
MessageText,
MessageTextOutline,
MessageVideo,
VoiceChat=MessageVideo,
Meteor,
Metronome,
MetronomeTick,
MicroSd,
Microphone,
KeyboardVoice=Microphone,
MicrophoneMinus,
MicrophoneOff,
MicOff=MicrophoneOff,
MicrophoneOutline,
MicNone=MicrophoneOutline,
MicrophonePlus,
MicrophoneSettings,
SettingsVoice=MicrophoneSettings,
MicrophoneVariant,
MicrophoneVariantOff,
Microscope,
Microsoft,
MicrosoftDynamics,
Midi,
MidiPort,
Minecraft,
MiniSd,
Minidisc,
Minus,
Remove=Minus,
MinusBox,
IndeterminateCheckBox=MinusBox,
MinusBoxOutline,
CheckboxIndeterminateOutline=MinusBoxOutline,
MinusCircle,
DoNotDisturbOn=MinusCircle,
MinusCircleOutline,
RemoveCircleOutline=MinusCircleOutline,
MinusNetwork,
Mixcloud,
MixedReality,
Mixer,
Molecule,
Monitor,
DesktopWindows=Monitor,
MonitorCellphone,
MonitorMobilePhone=MonitorCellphone,
MonitorSmartphone=MonitorCellphone,
MonitorCellphoneStar,
ImportantDevices=MonitorCellphoneStar,
MonitorMobilePhoneStar=MonitorCellphoneStar,
MonitorSmartphoneStar=MonitorCellphoneStar,
MonitorDashboard,
MonitorMultiple,
Monitors=MonitorMultiple,
More,
Motorbike,
Motorcycle=Motorbike,
Mouse,
MouseBluetooth,
MouseOff,
MouseVariant,
MouseVariantOff,
MoveResize,
MoveResizeVariant,
Movie,
Slate=Movie,
Clapperboard=Movie,
MovieCreation=Movie,
MovieRoll,
FilmReel=MovieRoll,
Muffin,
Multiplication,
MultiplicationBox,
Mushroom,
MushroomOutline,
Music,
MusicBox,
MusicBoxOutline,
MusicCircle,
MusicCircleOutline,
MusicNote,
MusicNoteBluetooth,
MusicNoteBluetoothOff,
MusicNoteEighth,
MusicNoteHalf,
MusicNoteOff,
MusicNoteQuarter,
MusicNoteSixteenth,
MusicNoteWhole,
MusicOff,
Nas,
NetworkAttachedStorage=Nas,
Nativescript,
Nature,
NaturePeople,
Navigation,
ArrowCompass=Navigation,
NearMe,
Needle,
Syringe=Needle,
Injection=Needle,
Netflix,
Network,
NetworkStrength1,
NetworkStrength1Alert,
NetworkStrength1Warning=NetworkStrength1Alert,
NetworkStrength2,
NetworkStrength2Alert,
NetworkStrength2Warning=NetworkStrength2Alert,
NetworkStrength3,
NetworkStrength3Alert,
NetworkStrength3Warning=NetworkStrength3Alert,
NetworkStrength4,
NetworkStrength4Alert,
NetworkStrength4Warning=NetworkStrength4Alert,
NetworkStrengthOff,
NetworkStrengthOffOutline,
NetworkStrengthOutline,
NetworkStrength0=NetworkStrengthOutline,
NewBox,
FiberNew=NewBox,
Newspaper,
Nfc,
NfcTap,
NfcVariant,
Ninja,
NintendoSwitch,
NintendoSwitchOnline=NintendoSwitch,
Nodejs,
NotEqual,
NotEqualVariant,
Note,
NoteMultiple,
Notes=NoteMultiple,
NoteMultipleOutline,
NotesOutline=NoteMultipleOutline,
NoteOutline,
NotePlus,
NotePlusOutline,
NoteText,
Notebook,
NotificationClearAll,
Npm,
NpmVariant,
NpmVariantOutline,
Nuke,
Null,
Numeric,
OneTwoThree=Numeric,
Numeric0,
Number0=Numeric0,
NumericZero=Numeric0,
Numeric0Box,
NumericZeroBox=Numeric0Box,
Number0Box=Numeric0Box,
Numeric0BoxMultipleOutline,
NumericZeroBoxMultipleOutline=Numeric0BoxMultipleOutline,
Numeric0BoxesOutline=Numeric0BoxMultipleOutline,
Number0BoxMultipleOutline=Numeric0BoxMultipleOutline,
Numeric0BoxOutline,
NumericZeroBoxOutline=Numeric0BoxOutline,
Number0BoxOutline=Numeric0BoxOutline,
Numeric1,
Number1=Numeric1,
NumericOne=Numeric1,
Numeric1Box,
LooksOne=Numeric1Box,
NumericOneBox=Numeric1Box,
Number1Box=Numeric1Box,
Numeric1BoxMultipleOutline,
Filter1=Numeric1BoxMultipleOutline,
NumericOneBoxMultipleOutline=Numeric1BoxMultipleOutline,
Numeric1BoxesOutline=Numeric1BoxMultipleOutline,
Number1BoxMultipleOutline=Numeric1BoxMultipleOutline,
Numeric1BoxOutline,
NumericOneBoxOutline=Numeric1BoxOutline,
Number1BoxOutline=Numeric1BoxOutline,
Numeric2,
Number2=Numeric2,
NumericTwo=Numeric2,
Numeric2Box,
LooksTwo=Numeric2Box,
NumericTwoBox=Numeric2Box,
Number2Box=Numeric2Box,
Numeric2BoxMultipleOutline,
Filter2=Numeric2BoxMultipleOutline,
NumericTwoBoxMultipleOutline=Numeric2BoxMultipleOutline,
Numeric2BoxesOutline=Numeric2BoxMultipleOutline,
Number2BoxMultipleOutline=Numeric2BoxMultipleOutline,
Numeric2BoxOutline,
NumericTwoBoxOutline=Numeric2BoxOutline,
Number2BoxOutline=Numeric2BoxOutline,
Numeric3,
Number3=Numeric3,
NumericThree=Numeric3,
Numeric3Box,
Looks3=Numeric3Box,
NumericThreeBox=Numeric3Box,
Number3Box=Numeric3Box,
Numeric3BoxMultipleOutline,
Filter3=Numeric3BoxMultipleOutline,
NumericThreeBoxMultipleOutline=Numeric3BoxMultipleOutline,
Numeric3BoxesOutline=Numeric3BoxMultipleOutline,
Number3BoxMultipleOutline=Numeric3BoxMultipleOutline,
Numeric3BoxOutline,
NumericThreeBoxOutline=Numeric3BoxOutline,
Number3BoxOutline=Numeric3BoxOutline,
Numeric4,
Number4=Numeric4,
NumericFour=Numeric4,
Numeric4Box,
Looks4=Numeric4Box,
NumericFourBox=Numeric4Box,
Number4Box=Numeric4Box,
Numeric4BoxMultipleOutline,
Filter4=Numeric4BoxMultipleOutline,
NumericFourBoxMultipleOutline=Numeric4BoxMultipleOutline,
Numeric4BoxesOutline=Numeric4BoxMultipleOutline,
Number4BoxMultipleOutline=Numeric4BoxMultipleOutline,
Numeric4BoxOutline,
NumericFourBoxOutline=Numeric4BoxOutline,
Number4BoxOutline=Numeric4BoxOutline,
Numeric5,
Number5=Numeric5,
NumericFive=Numeric5,
Numeric5Box,
Looks5=Numeric5Box,
NumericFiveBox=Numeric5Box,
Number5Box=Numeric5Box,
Numeric5BoxMultipleOutline,
Filter5=Numeric5BoxMultipleOutline,
NumericFiveBoxMultipleOutline=Numeric5BoxMultipleOutline,
Numeric5BoxesOutline=Numeric5BoxMultipleOutline,
Number5BoxMultipleOutline=Numeric5BoxMultipleOutline,
Numeric5BoxOutline,
NumericFiveBoxOutline=Numeric5BoxOutline,
Number5BoxOutline=Numeric5BoxOutline,
Numeric6,
Number6=Numeric6,
NumericSix=Numeric6,
Numeric6Box,
Looks6=Numeric6Box,
NumericSixBox=Numeric6Box,
Number6Box=Numeric6Box,
Numeric6BoxMultipleOutline,
Filter6=Numeric6BoxMultipleOutline,
NumericSixBoxMultipleOutline=Numeric6BoxMultipleOutline,
Numeric6BoxesOutline=Numeric6BoxMultipleOutline,
Number6BoxMultipleOutline=Numeric6BoxMultipleOutline,
Numeric6BoxOutline,
NumericSixBoxOutline=Numeric6BoxOutline,
Number6BoxOutline=Numeric6BoxOutline,
Numeric7,
Number7=Numeric7,
NumericSeven=Numeric7,
Numeric7Box,
NumericSevenBox=Numeric7Box,
Number7Box=Numeric7Box,
Numeric7BoxMultipleOutline,
Filter7=Numeric7BoxMultipleOutline,
NumericSevenBoxMultipleOutline=Numeric7BoxMultipleOutline,
Numeric7BoxesOutline=Numeric7BoxMultipleOutline,
Number7BoxMultipleOutline=Numeric7BoxMultipleOutline,
Numeric7BoxOutline,
NumericSevenBoxOutline=Numeric7BoxOutline,
Number7BoxOutline=Numeric7BoxOutline,
Numeric8,
Number8=Numeric8,
NumericEight=Numeric8,
Numeric8Box,
NumericEightBox=Numeric8Box,
Number8Box=Numeric8Box,
Numeric8BoxMultipleOutline,
Filter8=Numeric8BoxMultipleOutline,
NumericEightBoxMultipleOutline=Numeric8BoxMultipleOutline,
Numeric8BoxesOutline=Numeric8BoxMultipleOutline,
Number8BoxMultipleOutline=Numeric8BoxMultipleOutline,
Numeric8BoxOutline,
NumericEightBoxOutline=Numeric8BoxOutline,
Number8BoxOutline=Numeric8BoxOutline,
Numeric9,
Number9=Numeric9,
NumericNine=Numeric9,
Numeric9Box,
NumericNineBox=Numeric9Box,
Number9Box=Numeric9Box,
Numeric9BoxMultipleOutline,
Filter9=Numeric9BoxMultipleOutline,
NumericNineBoxMultipleOutline=Numeric9BoxMultipleOutline,
Numeric9BoxesOutline=Numeric9BoxMultipleOutline,
Number9BoxMultipleOutline=Numeric9BoxMultipleOutline,
Numeric9BoxOutline,
NumericNineBoxOutline=Numeric9BoxOutline,
Number9BoxOutline=Numeric9BoxOutline,
Numeric9PlusBox,
NumericNinePlusBox=Numeric9PlusBox,
Number9PlusBox=Numeric9PlusBox,
Numeric9PlusBoxMultipleOutline,
Filter9Plus=Numeric9PlusBoxMultipleOutline,
NumericNinePlusBoxMultipleOutline=Numeric9PlusBoxMultipleOutline,
Numeric9PlusBoxesOutline=Numeric9PlusBoxMultipleOutline,
Number9PlusBoxMultipleOutline=Numeric9PlusBoxMultipleOutline,
Numeric9PlusBoxOutline,
NumericNinePlusBoxOutline=Numeric9PlusBoxOutline,
Number9PlusBoxOutline=Numeric9PlusBoxOutline,
Nut,
Nutrition,
Oar,
Octagon,
OctagonOutline,
Octagram,
OctagramOutline,
Odnoklassniki,
OkRu=Odnoklassniki,
Office,
MicrosoftOffice=Office,
OfficeBuilding,
Oil,
OilTemperature,
Omega,
OneUp,
ExtraLife=OneUp,
Onedrive,
Onenote,
Onepassword,
Opacity,
OpenInApp,
OpenInBrowser=OpenInApp,
OpenInNew,
ExternalLink=OpenInNew,
OpenSourceInitiative,
Openid,
Opera,
Orbit,
Origin,
Ornament,
OrnamentVariant,
Owl,
PacMan,
Package,
PackageDown,
BoxDown=PackageDown,
PackageUp,
Unarchive=PackageUp,
BoxUp=PackageUp,
PackageVariant,
BoxVariant=PackageVariant,
PackageVariantClosed,
BoxVariantClosed=PackageVariantClosed,
PageFirst,
FirstPage=PageFirst,
PageLast,
LastPage=PageLast,
PageLayoutBody,
PageLayoutFooter,
PageLayoutHeader,
PageLayoutSidebarLeft,
PageLayoutSidebarRight,
PageNext,
ReadMore=PageNext,
PageNextOutline,
ReadMoreOutline=PageNextOutline,
PagePrevious,
PagePreviousOutline,
Palette,
ColorLens=Palette,
ColourLens=Palette,
PaletteAdvanced,
PaletteSwatch,
Style=PaletteSwatch,
Pan,
PanBottomLeft,
PanDownLeft=PanBottomLeft,
PanBottomRight,
PanDownRight=PanBottomRight,
PanDown,
PanHorizontal,
PanLeft,
PanRight,
PanTopLeft,
PanUpLeft=PanTopLeft,
PanTopRight,
PanUpRight=PanTopRight,
PanUp,
PanVertical,
Panda,
Pandora,
Panorama,
PanoramaFisheye,
PanoramaFishEye=PanoramaFisheye,
PanoramaHorizontal,
PanoramaVertical,
PanoramaWideAngle,
PaperCutVertical,
Paperclip,
AttachmentVertical=Paperclip,
AttachFile=Paperclip,
Parking,
CarPark=Parking,
LocalParking=Parking,
Passport,
Patreon,
Pause,
PauseCircle,
PauseCircleFilled=PauseCircle,
PauseCircleOutline,
PauseOctagon,
PauseOctagonOutline,
Paw,
Pets=Paw,
PawOff,
Paypal,
Peace,
Pen,
Pencil,
Edit=Pencil,
Create=Pencil,
ModeEdit=Pencil,
PencilBox,
PencilBoxOutline,
PencilCircle,
PencilCircleOutline,
PencilLock,
PencilOff,
EditOff=PencilOff,
Pentagon,
PentagonOutline,
Percent,
PeriodicTable,
PeriodicTableCo2,
PeriodicTableCarbonDioxide=PeriodicTableCo2,
Periscope,
Pharmacy,
Chemist=Pharmacy,
LocalPharmacy=Pharmacy,
Phone,
Call=Phone,
LocalPhone=Phone,
Telephone=Phone,
PhoneBluetooth,
PhoneBluetoothSpeaker=PhoneBluetooth,
TelephoneBluetooth=PhoneBluetooth,
PhoneClassic,
PhoneForward,
PhoneForwarded=PhoneForward,
TelephoneForward=PhoneForward,
PhoneHangup,
CallEnd=PhoneHangup,
TelephoneHangup=PhoneHangup,
PhoneInTalk,
TelephoneInTalk=PhoneInTalk,
PhoneIncoming,
TelephoneIncoming=PhoneIncoming,
PhoneLock,
TelephoneLocked=PhoneLock,
PhoneLocked=PhoneLock,
TelephoneLock=PhoneLock,
PhoneLog,
PhoneMinus,
PhoneMissed,
PhoneOutgoing,
PhonePaused,
PhonePlus,
AddCall=PhonePlus,
PhoneReturn,
PhoneRotateLandscape,
PhoneRotatePortrait,
PhoneSettings,
SettingsPhone=PhoneSettings,
PhoneVoip,
Pi,
PiBox,
Piano,
Pickaxe,
Pier,
PierCrane,
Pig,
Pill,
Medicine=Pill,
Capsule=Pill,
Pillar,
Historic=Pillar,
Column=Pillar,
Pin,
Keep=Pin,
PinOff,
KeepOff=PinOff,
PinOffOutline,
KeepOffOutline=PinOffOutline,
PinOutline,
KeepOutline=PinOutline,
PineTree,
PineTreeBox,
Pinterest,
PinterestBox,
Pinwheel,
Toys=Pinwheel,
PinwheelOutline,
ToysOutline=PinwheelOutline,
Pipe,
PipeDisconnected,
PipeLeak,
Pirate,
Pistol,
Gun=Pistol,
Piston,
Pizza,
Pizzeria=Pizza,
LocalPizza=Pizza,
PlaneShield,
AeroplaneShield=PlaneShield,
AirplaneShield=PlaneShield,
Play,
PlayArrow=Play,
PlayBoxOutline,
Slideshow=PlayBoxOutline,
PlayCircle,
PlayCircleFilled=PlayCircle,
PlayCircleOutline,
PlayNetwork,
MediaNetwork=PlayNetwork,
PlayPause,
PlayProtectedContent,
PlaySpeed,
PlaylistCheck,
Subscriptions=PlaylistCheck,
PlaylistAddCheck=PlaylistCheck,
PlaylistTick=PlaylistCheck,
PlaylistEdit,
PlaylistMinus,
PlaylistPlay,
PlaylistPlus,
PlaylistAdd=PlaylistPlus,
PlaylistRemove,
Playstation,
SonyPlaystation=Playstation,
PlaystationNetwork=Playstation,
Plex,
Plus,
Add=Plus,
PlusBox,
AddBox=PlusBox,
PlusBoxOutline,
PlusCircle,
AddCircle=PlusCircle,
PlusCircleMultipleOutline,
ControlPointDuplicate=PlusCircleMultipleOutline,
PlusCirclesOutline=PlusCircleMultipleOutline,
PlusCircleOutline,
AddCircleOutline=PlusCircleOutline,
ControlPoint=PlusCircleOutline,
CirclesAdd=PlusCircleOutline,
PlusMinus,
PlusMinusBox,
PlusNetwork,
PlusOne,
PlusOutline,
Pocket,
Podcast,
Pokeball,
PokemonGo,
PokerChip,
Polaroid,
Poll,
BarChart=Poll,
PollBox,
Assessment=PollBox,
InsertChart=PollBox,
Polymer,
Pool,
SwimmingPool=Pool,
Popcorn,
Pot,
PotMix,
Pound,
Hashtag=Pound,
PoundBox,
HashtagBox=PoundBox,
Power,
PowerSettingsNew=Power,
Shutdown=Power,
PowerCycle,
PowerOff,
PowerOn,
PowerPlug,
PowerPlugOff,
PowerSettings,
SettingsPower=PowerSettings,
PowerSleep,
PowerSocket,
PlugSocket=PowerSocket,
PowerSocketAu,
PlugSocketAu=PowerSocketAu,
PowerSocketTypeI=PowerSocketAu,
PowerSocketCn=PowerSocketAu,
PowerSocketAr=PowerSocketAu,
PowerSocketNz=PowerSocketAu,
PowerSocketPg=PowerSocketAu,
PowerSocketAustralia=PowerSocketAu,
PowerSocketChina=PowerSocketAu,
PowerSocketArgentina=PowerSocketAu,
PowerSocketNewZealand=PowerSocketAu,
PowerSocketPapuaNewGuinea=PowerSocketAu,
PowerSocketEu,
PlugSocketEu=PowerSocketEu,
PowerSocketEurope=PowerSocketEu,
PowerSocketUk,
PlugSocketUk=PowerSocketUk,
PowerSocketTypeG=PowerSocketUk,
PowerSocketIe=PowerSocketUk,
PowerSocketHk=PowerSocketUk,
PowerSocketMy=PowerSocketUk,
PowerSocketCy=PowerSocketUk,
PowerSocketMt=PowerSocketUk,
PowerSocketSg=PowerSocketUk,
PowerSocketUnitedKingdom=PowerSocketUk,
PowerSocketIreland=PowerSocketUk,
PowerSocketHongKong=PowerSocketUk,
PowerSocketMalaysia=PowerSocketUk,
PowerSocketCyprus=PowerSocketUk,
PowerSocketMalta=PowerSocketUk,
PowerSocketSingapore=PowerSocketUk,
PowerSocketUs,
PlugSocketUs=PowerSocketUs,
PowerSocketJp=PowerSocketUs,
PowerSocketCa=PowerSocketUs,
PowerSocketMx=PowerSocketUs,
PowerSocketTypeB=PowerSocketUs,
PowerSocketUnitedStates=PowerSocketUs,
PowerSocketJapan=PowerSocketUs,
PowerSocketCanada=PowerSocketUs,
PowerSocketMexico=PowerSocketUs,
PowerStandby,
Powershell,
Prescription,
Presentation,
PresentationPlay,
Printer,
LocalPrintshop=Printer,
LocalPrintShop=Printer,
Printer3d,
PrinterAlert,
PrinterWarning=PrinterAlert,
PrinterSettings,
PrinterWireless,
PriorityHigh,
PriorityLow,
LowPriority=PriorityLow,
ProfessionalHexagon,
ProgressCheck,
ProgressTick=ProgressCheck,
ProgressClock,
ProgressDownload,
ProgressUpload,
Projector,
ProjectorScreen,
Publish,
Pulse,
Pumpkin,
Puzzle,
Extension=Puzzle,
Jigsaw=Puzzle,
PuzzleOutline,
JigsawOutline=PuzzleOutline,
ExtensionOutline=PuzzleOutline,
Qi,
Qqchat,
Qrcode,
QrcodeEdit,
QrcodeScan,
Quadcopter,
QualityHigh,
HighQuality=QualityHigh,
Hq=QualityHigh,
QualityLow,
LowQuality=QualityLow,
Lq=QualityLow,
QualityMedium,
MediumQuality=QualityMedium,
Mq=QualityMedium,
Quicktime,
Rabbit,
Bunny=Rabbit,
Radar,
TrackChanges=Radar,
Radiator,
Heater=Radiator,
RadiatorDisabled,
HeaterDisabled=RadiatorDisabled,
RadiatorOff,
HeaterOff=RadiatorOff,
Radio,
RadioHandheld,
RadioTower,
Radioactive,
RadioboxBlank,
RadioButtonUnchecked=RadioboxBlank,
RadioboxMarked,
RadioButtonChecked=RadioboxMarked,
Raspberrypi,
RayEnd,
RayEndArrow,
RayStart,
RayStartArrow,
RayStartEnd,
RayVertex,
React,
Read,
Receipt,
Record,
FiberManualRecord=Record,
RecordPlayer,
RecordRec,
Recycle,
Reddit,
Redo,
Arrow=Redo,
RedoVariant,
ReflectHorizontal,
ReflectVertical,
Refresh,
Regex,
RegisteredTrademark,
RelativeScale,
ImageAspectRatio=RelativeScale,
Reload,
Reminder,
Remote,
SettingsRemote=Remote,
RemoteDesktop,
RenameBox,
ReorderHorizontal,
ReorderVertical,
Repeat,
RepeatOff,
RepeatOnce,
RepeatOne=RepeatOnce,
Replay,
Reply,
ReplyAll,
Reproduction,
Resistor,
ResistorNodes,
Resize,
ResizeBottomRight,
Responsive,
Restart,
Restore,
RestoreClock,
Rewind,
FastRewind=Rewind,
RewindOutline,
Rhombus,
RhombusMedium,
RhombusOutline,
RhombusSplit,
Ribbon,
Rice,
Ring,
Road,
RoadVariant,
Robot,
RobotIndustrial,
RobotVacuum,
Roomba=RobotVacuum,
RobotVacuumVariant,
Neato=RobotVacuumVariant,
Rocket,
Rollupjs,
RollupJs=Rollupjs,
RoomService,
Rotate3d,
RotateLeft,
ArrowRotateLeft=RotateLeft,
RotateLeftVariant,
RotateRight,
ArrowRotateRight=RotateRight,
RotateRightVariant,
RoundedCorner,
RouterWireless,
RouterWirelessSettings,
Routes,
SignRoutes=Routes,
Rowing,
Rss,
RssFeed=Rss,
RssBox,
Ruler,
Run,
DirectionsRun=Run,
RunFast,
Safe,
Sale,
Discount=Sale,
Salesforce,
Sass,
Satellite,
SatelliteUplink,
SatelliteVariant,
Sausage,
Saxophone,
Scale,
ScaleBalance,
ScaleBathroom,
Scanner,
ScannerOff,
School,
GraduationCap=School,
ScissorsCutting,
ScreenRotation,
ScreenRotationLock,
ScreenLockRotation=ScreenRotationLock,
Screwdriver,
Script,
Scroll=Script,
ScriptOutline,
ScrollOutline=ScriptOutline,
ScriptText,
ScrollText=ScriptText,
ScriptTextOutline,
ScrollTextOutline=ScriptTextOutline,
Sd,
SdCard=Sd,
SdStorage=Sd,
Seal,
SearchWeb,
SeatFlat,
AirlineSeatFlat=SeatFlat,
SeatFlatAngled,
AirlineSeatFlatAngled=SeatFlatAngled,
SeatIndividualSuite,
AirlineSeatIndividualSuite=SeatIndividualSuite,
SeatLegroomExtra,
AirlineSeatLegroomExtra=SeatLegroomExtra,
SeatLegroomNormal,
AirlineSeatLegroomNormal=SeatLegroomNormal,
SeatLegroomReduced,
AirlineSeatLegroomReduced=SeatLegroomReduced,
SeatReclineExtra,
AirlineSeatReclineExtra=SeatReclineExtra,
SeatReclineNormal,
AirlineSeatReclineNormal=SeatReclineNormal,
Security,
SecurityAccount,
SecurityAccountOutline,
SecurityClose,
SecurityHome,
SecurityLock,
SecurityNetwork,
SecurityOff,
Select,
SelectAll,
SelectCompare,
SelectDrag,
SelectInverse,
SelectOff,
Selection,
SelectionDrag,
SelectionOff,
Send,
SendLock,
SendSecure=SendLock,
SerialPort,
Server,
ServerMinus,
ServerNetwork,
ServerNetworkOff,
ServerOff,
ServerPlus,
ServerRemove,
ServerSecurity,
SetAll,
SetCenter,
SetCentre=SetCenter,
SetCenterRight,
SetCentreRight=SetCenterRight,
SetLeft,
SetLeftCenter,
SetLeftCentre=SetLeftCenter,
SetLeftRight,
SetNone,
SetRight,
SetTopBox,
Settings,
Cog=Settings,
Gear=Settings,
SettingsBox,
GearBox=SettingsBox,
CogBox=SettingsBox,
SettingsApplications=SettingsBox,
SettingsHelper,
SettingsOutline,
CogOutline=SettingsOutline,
GearOutline=SettingsOutline,
Shape,
Category=Shape,
ShapeCirclePlus,
ShapeOutline,
Theme=ShapeOutline,
ShapePlus,
ShapePolygonPlus,
ShapeRectanglePlus,
ShapeSquarePlus,
Share,
ShareOutline,
ShareVariant,
Shield,
ShieldHalfFull,
ShieldKey,
ShieldKeyOutline,
ShieldOutline,
ShieldPlus,
ShieldPlusOutline,
ShieldRemove,
ShieldRemoveOutline,
ShipWheel,
Voyager=ShipWheel,
ShoeFormal,
ShoeHeel,
Shopify,
Shopping,
LocalMall=Shopping,
ShoppingMusic,
Shovel,
ShovelOff,
Shower,
ShowerHead,
Shredder,
Shuffle,
ShuffleDisabled,
ShuffleVariant,
Sigma,
Summation=Sigma,
SigmaLower,
SignCaution,
SignDirection,
SignText,
Signal,
Signal2g,
Signal3g,
Signal4g,
Signal5g,
SignalCellular1,
SignalCellular2,
SignalCellular3,
SignalCellularOutline,
SignalCellular0=SignalCellularOutline,
SignalHspa,
SignalHspaPlus,
SignalOff,
SignalVariant,
Silo,
Silverware,
LocalDining=Silverware,
RestaurantMenu=Silverware,
LocalRestaurant=Silverware,
SilverwareFork,
SilverwareForkKnife,
Restaurant=SilverwareForkKnife,
Fortnite=SilverwareForkKnife,
SilverwareSpoon,
SilverwareVariant,
Sim,
SimCard=Sim,
SimAlert,
SimWarning=SimAlert,
SimCardAlert=SimAlert,
SimOff,
SignalCellularNoSim=SimOff,
SinaWeibo,
Sitemap,
Workflow=Sitemap,
Flowchart=Sitemap,
SkipBackward,
TitleBackward=SkipBackward,
PreviousTitle=SkipBackward,
SkipForward,
TitleForward=SkipForward,
NextTitle=SkipForward,
SkipNext,
SkipNextCircle,
SkipNextCircleOutline,
SkipPrevious,
SkipPreviousCircle,
SkipPreviousCircleOutline,
Skull,
SkullCrossbones,
JollyRoger=SkullCrossbones,
SkullCrossbonesOutline,
JollyRogerOutline=SkullCrossbonesOutline,
SkullOutline,
Skype,
SkypeBusiness,
Slack,
Slackware,
Sleep,
SleepOff,
Smog,
SmokeDetector,
NestProtect=SmokeDetector,
Smoking,
Cigarette=Smoking,
SmokingArea=Smoking,
SmokingRooms=Smoking,
SmokingOff,
NoSmoking=SmokingOff,
CigaretteOff=SmokingOff,
SmokeFree=SmokingOff,
Snapchat,
Snowflake,
Snowman,
Soccer,
SoccerField,
FootballPitch=SoccerField,
Sofa,
Couch=Sofa,
SolarPower,
Solid,
Sort,
SortAlphabetical,
SortByAlpha=SortAlphabetical,
SortAlphabetically=SortAlphabetical,
SortAscending,
SortDescending,
SortNumeric,
SortNumerically=SortNumeric,
SortVariant,
Soundcloud,
SourceBranch,
SourceCommit,
SourceCommitEnd,
SourceCommitEndLocal,
SourceCommitLocal,
SourceCommitNextLocal,
SourceCommitStart,
SourceCommitStartNextLocal,
SourceFork,
SourceMerge,
SourcePull,
SoySauce,
SoyaSauce=SoySauce,
SpaceInvaders,
Speaker,
SpeakerBluetooth,
SpeakerOff,
SpeakerWireless,
Speedometer,
Spellcheck,
SpiderWeb,
Cobweb=SpiderWeb,
Spotify,
Spotlight,
SpotlightBeam,
Spray,
Paint=Spray,
Aerosol=Spray,
SprayBottle,
Cleaning=SprayBottle,
Square,
SquareEditOutline,
SquareInc,
SquareIncCash,
SquareMedium,
SquareMediumOutline,
SquareOutline,
SquareRoot,
SquareRootBox,
SquareSmall,
Squeegee,
Ssh,
StackExchange,
Stackexchange=StackExchange,
StackOverflow,
Stackoverflow=StackOverflow,
Stadium,
Arena=Stadium,
Stairs,
StandardDefinition,
Star,
Grade=Star,
StarRate=Star,
StarBox,
StarBoxOutline,
StarCircle,
Stars=StarCircle,
StarCircleOutline,
FeatureHighlight=StarCircleOutline,
StarFace,
StarFourPoints,
StarFourPointsOutline,
StarHalf,
StarOff,
StarOutline,
StarBorder=StarOutline,
StarThreePoints,
StarThreePointsOutline,
Steam,
SteamBox,
Steering,
SearchHandsFree=Steering,
SteeringOff,
SearchHandsFreeOff=SteeringOff,
StepBackward,
StepBackward2,
FrameBackward=StepBackward2,
StepForward,
StepForward2,
FrameForward=StepForward2,
Stethoscope,
Sticker,
StickerEmoji,
Stocking,
Stop,
StopCircle,
StopCircleOutline,
Store,
Shop=Store,
StoreMallDirectory=Store,
Store24Hour,
LocalConvenienceStore=Store24Hour,
Shop24Hour=Store24Hour,
Stove,
Cooker=Stove,
Oven=Stove,
Strava,
SubdirectoryArrowLeft,
SubdirectoryArrowRight,
Subtitles,
SubtitlesOutline,
Subway,
Metro=Subway,
Tube=Subway,
Underground=Subway,
SubwayVariant,
MetroVariant=SubwayVariant,
TubeVariant=SubwayVariant,
UndergroundVariant=SubwayVariant,
DirectionsSubway=SubwayVariant,
DirectionsTransit=SubwayVariant,
Summit,
Peak=Summit,
Sunglasses,
SurroundSound,
SurroundSound20,
Stereo=SurroundSound20,
SurroundSound31,
SurroundSound51,
SurroundSound71,
Svg,
SwapHorizontal,
SwapHorizontalBold,
SwapHorizontalVariant,
SwapVertical,
ImportExport=SwapVertical,
SwapVerticalBold,
SwapVerticalVariant,
SwapCalls=SwapVerticalVariant,
Swim,
Switch,
Sword,
SwordCross,
Symfony,
Sync,
SyncAlert,
SyncWarning=SyncAlert,
SyncProblem=SyncAlert,
SyncOff,
SyncDisabled=SyncOff,
Tab,
TabMinus,
TabPlus,
TabRemove,
TabUnselected,
Table,
TableBorder,
TableColumn,
TableColumnPlusAfter,
TableColumnPlusBefore,
TableColumnRemove,
TableColumnWidth,
TableEdit,
TableLarge,
TableMergeCells,
TableOfContents,
Toc=TableOfContents,
TablePlus,
TableRemove,
TableRow,
TableRowHeight,
TableRowPlusAfter,
TableRowPlusBefore,
TableRowRemove,
TableSearch,
TableSettings,
Tablet,
TabletAndroid,
TabletCellphone,
MobileDevices=TabletCellphone,
TabletMobilePhone=TabletCellphone,
TabletSmartphone=TabletCellphone,
TabletIpad,
TabletMac=TabletIpad,
Taco,
Tag,
LocalOffer=Tag,
TagFaces,
TagHeart,
Loyalty=TagHeart,
TagHeartOutline,
TagMinus,
TagMultiple,
Tags=TagMultiple,
TagOutline,
TagPlus,
TagRemove,
TagTextOutline,
TapeMeasure,
MeasuringTape=TapeMeasure,
Target,
RegistrationMark=Target,
TargetAccount,
CrosshairsAccount=TargetAccount,
TargetUser=TargetAccount,
TargetVariant,
Taxi,
LocalTaxi=Taxi,
Teach,
Teacher=Teach,
Teaching=Teach,
Teamviewer,
Telegram,
Telescope,
Television,
Tv=Television,
TelevisionBox,
TvBox=TelevisionBox,
TvGuide=TelevisionBox,
TelevisionClassic,
TvClassic=TelevisionClassic,
TelevisionClassicOff,
TvClassicOff=TelevisionClassicOff,
TelevisionGuide,
TelevisionOff,
TvOff=TelevisionOff,
TemperatureCelsius,
TemperatureCentigrade=TemperatureCelsius,
TemperatureFahrenheit,
TemperatureKelvin,
Tennis,
Tent,
Camping=Tent,
Terrain,
TestTube,
TestTubeEmpty,
TestTubeOff,
Text,
TextShadow,
TextShort,
TextSubject,
TextToSpeech,
TextToSpeechOff,
Textbox,
TextboxPassword,
Texture,
Theater,
Cinema=Theater,
Theatre=Theater,
ThemeLightDark,
SunMoonStars=ThemeLightDark,
Thermometer,
ThermometerLines,
Thermostat,
Nest=Thermostat,
ThermostatBox,
ThoughtBubble,
ComicBubble=ThoughtBubble,
ThoughtBubbleOutline,
ComicThoughtBubbleOutline=ThoughtBubbleOutline,
ThumbDown,
Dislike=ThumbDown,
ThumbsDown=ThumbDown,
ThumbDownOutline,
DislikeOutline=ThumbDownOutline,
ThumbsDownOutline=ThumbDownOutline,
ThumbUp,
Like=ThumbUp,
ThumbsUp=ThumbUp,
ThumbUpOutline,
LikeOutline=ThumbUpOutline,
ThumbsUpOutline=ThumbUpOutline,
ThumbsUpDown,
LikeDislike=ThumbsUpDown,
Ticket,
LocalActivity=Ticket,
LocalPlay=Ticket,
LocalAttraction=Ticket,
TicketAccount,
TicketUser=TicketAccount,
TicketConfirmation,
ConfirmationNumber=TicketConfirmation,
TicketOutline,
TicketPercent,
Coupon=TicketPercent,
Voucher=TicketPercent,
Tie,
Tilde,
Timelapse,
Timeline,
TimelineOutline,
TimelineText,
TimelineTextOutline,
Timer,
Stopwatch=Timer,
Timer10,
TimerTen=Timer10,
Timer3,
TimerThree=Timer3,
TimerOff,
StopwatchOff=TimerOff,
TimerSand,
Hourglass=TimerSand,
TimerSandEmpty,
HourglassEmpty=TimerSandEmpty,
TimerSandFull,
HourglassFull=TimerSandFull,
Timetable,
ToggleSwitch,
ToggleSwitchOff,
ToggleSwitchOffOutline,
ToggleSwitchOutline,
Toilet,
Toolbox,
ToolboxOutline,
ServiceToolbox=ToolboxOutline,
Tooltip,
TooltipEdit,
TooltipImage,
TooltipImageOutline,
TooltipOutline,
TooltipPlus,
TooltipPlusOutline,
TooltipOutlinePlus=TooltipPlusOutline,
TooltipText,
TooltipTextOutline,
Tooth,
ToothOutline,
Tor,
Tournament,
Bracket=Tournament,
TowerBeach,
TowerFire,
Towing,
AutoTowing=Towing,
TrackLight,
Trackpad,
TrackpadLock,
Tractor,
Trademark,
Tm=Trademark,
TrafficLight,
Train,
DirectionsRailway=Train,
TrainCar,
Commute=TrainCar,
Transportation=TrainCar,
Travel=TrainCar,
TrainVariant,
Tram,
Transcribe,
TranscribeClose,
Transfer,
TransitTransfer,
TransferWithinAStation=TransitTransfer,
Transition,
Motion=Transition,
TransitionMasked,
MaskedTransitions=TransitionMasked,
Translate,
Language=Translate,
TrashCan,
Trashcan=TrashCan,
TrashCanOutline,
TrashcanOutline=TrashCanOutline,
TreasureChest,
Tree,
Trello,
TrendingDown,
TrendingNeutral,
TrendingFlat=TrendingNeutral,
TrendingUp,
Triangle,
TriangleOutline,
Triforce,
Zelda=Triforce,
Trophy,
Achievement=Trophy,
TrophyAward,
AchievementAward=TrophyAward,
TrophyOutline,
AchievementOutline=TrophyOutline,
TrophyVariant,
AchievementVariant=TrophyVariant,
TrophyVariantOutline,
AchievementVariantOutline=TrophyVariantOutline,
Truck,
Lorry=Truck,
LocalShipping=Truck,
TruckDelivery,
LorryDelivery=TruckDelivery,
TruckFast,
LorryFast=TruckFast,
TruckTrailer,
TshirtCrew,
TShirtCrew=TshirtCrew,
TshirtCrewOutline,
TShirtCrewOutline=TshirtCrewOutline,
TshirtV,
TShirtV=TshirtV,
TshirtVOutline,
TShirtVOutline=TshirtVOutline,
TumbleDryer,
Tumblr,
TumblrBox,
TumblrReblog,
Tune,
MixerSettings=Tune,
Equaliser=Tune,
TuneVertical,
EqualiserVertical=TuneVertical,
InstantMix=TuneVertical,
Twitch,
Twitter,
TwitterBox,
TwitterCircle,
TwitterRetweet,
TwoFactorAuthentication,
Uber,
Ubisoft,
Uplay=Ubisoft,
Ubuntu,
UltraHighDefinition,
Uhd=UltraHighDefinition,
Umbraco,
Umbrella,
UmbrellaClosed,
UmbrellaOutline,
Undo,
UndoVariant,
UnfoldLessHorizontal,
ChevronDownUp=UnfoldLessHorizontal,
CollapseHorizontal=UnfoldLessHorizontal,
UnfoldLessVertical,
ChevronRightLeft=UnfoldLessVertical,
CollapseVertical=UnfoldLessVertical,
UnfoldMoreHorizontal,
ChevronUpDown=UnfoldMoreHorizontal,
ExpandHorizontal=UnfoldMoreHorizontal,
UnfoldMoreVertical,
ChevronLeftRight=UnfoldMoreVertical,
ExpandVertical=UnfoldMoreVertical,
Ungroup,
Unity,
Unreal,
UnrealEngine=Unreal,
Untappd,
Update,
Clockwise=Update,
Upload,
UploadMultiple,
Uploads=UploadMultiple,
UploadNetwork,
Usb,
VanPassenger,
VanUtility,
VanCandy=VanUtility,
Vanish,
Variable,
VectorArrangeAbove,
VectorArrangeBelow,
VectorBezier,
VectorCircle,
VectorCircleVariant,
VectorCombine,
VectorCurve,
Bezier=VectorCurve,
VectorDifference,
VectorDifferenceAb,
VectorDifferenceBa,
VectorEllipse,
VectorIntersection,
VectorLine,
VectorPoint,
VectorPolygon,
VectorPolyline,
VectorRadius,
VectorRectangle,
VectorSelection,
VectorSquare,
Mdi=VectorSquare,
VectorTriangle,
VectorUnion,
Venmo,
Verified,
ShieldCheck=Verified,
VerifiedUser=Verified,
ShieldTick=Verified,
Vhs,
VideoHomeSystem=Vhs,
VhsCassette=Vhs,
VhsTape=Vhs,
Vibrate,
Vibration=Vibrate,
Video,
Videocam=Video,
Video3d,
Video4kBox,
VideoAccount,
VideoUser=VideoAccount,
VideoImage,
VideoInputAntenna,
SettingsInputAntenna=VideoInputAntenna,
VideoInputComponent,
VideoInputComposite=VideoInputComponent,
SettingsInputComponent=VideoInputComponent,
SettingsInputComposite=VideoInputComponent,
VideoInputYpbpr=VideoInputComponent,
Rca=VideoInputComponent,
VideoInputHdmi,
SettingsInputHdmi=VideoInputHdmi,
VideoInputSvideo,
SettingsInputSvideo=VideoInputSvideo,
VideoMinus,
VideoOff,
VideocamOff=VideoOff,
VideoOffOutline,
VideocamOffOutline=VideoOffOutline,
VideoOutline,
VideocamOutline=VideoOutline,
VideoPlus,
VideoCall=VideoPlus,
VideoStabilization,
VideoStabilisation=VideoStabilization,
VideoSwitch,
SwitchVideo=VideoSwitch,
VideoVintage,
VideoFilm=VideoVintage,
VideoClassic=VideoVintage,
ViewAgenda,
ViewArray,
ViewCarousel,
ViewColumn,
ViewDashboard,
ViewDashboardOutline,
ViewDashboardVariant,
ViewDay,
ViewGrid,
ViewHeadline,
ViewList,
ViewModule,
ViewParallel,
ViewQuilt,
ViewSequential,
ViewSplitHorizontal,
ViewSplitVertical,
ViewStream,
ViewWeek,
Vimeo,
Violin,
VirtualReality,
Vr=VirtualReality,
VisualStudio,
Visualstudio=VisualStudio,
VisualStudioCode,
Vk,
Vkontakte=Vk,
VkBox,
VkontakteBox=VkBox,
VkCircle,
VkontakteCircle=VkCircle,
Vlc,
Voice,
RecordVoiceOver=Voice,
Speak=Voice,
Talk=Voice,
Speaking=Voice,
Talking=Voice,
Voicemail,
Volleyball,
VolumeHigh,
Audio=VolumeHigh,
Speakerphone=VolumeHigh,
VolumeLow,
VolumeMedium,
VolumeMinus,
VolumeMute,
VolumeOff,
Mute=VolumeOff,
AudioOff=VolumeOff,
SpeakerphoneOff=VolumeOff,
VolumePlus,
Vote,
HowToVote=Vote,
VoteOutline,
HowToVoteOutline=VoteOutline,
Vpn,
VirtualPrivateNetwork=Vpn,
Vuejs,
VueJs=Vuejs,
Walk,
DirectionsWalk=Walk,
Wall,
WallSconce,
WallSconceFlat,
WallSconceVariant,
Wallet,
AccountBalanceWallet=Wallet,
WalletGiftcard,
CardGiftcard=WalletGiftcard,
Redeem=WalletGiftcard,
WalletMembership,
CardMembership=WalletMembership,
WalletOutline,
AccountBalanceWalletOutline=WalletOutline,
WalletTravel,
CardTravel=WalletTravel,
Wan,
WashingMachine,
Laundrette=WashingMachine,
LocalLaundryService=WashingMachine,
Watch,
WatchExport,
WatchExportVariant,
WatchImport,
WatchImportVariant,
WatchVariant,
WatchVibrate,
Water,
WaterOff,
FormatColorReset=WaterOff,
WaterPercent,
Humidity=WaterPercent,
WaterPump,
Watermark,
BrandingWatermark=Watermark,
Waves,
Waze,
WeatherCloudy,
WeatherFog,
WeatherHail,
WeatherHurricane,
WeatherLightning,
WeatherLightningRainy,
WeatherNight,
MoonAndStars=WeatherNight,
NightSky=WeatherNight,
WeatherPartlycloudy,
WeatherPouring,
WeatherRainy,
WeatherSnowy,
WeatherSnowyRainy,
WeatherSunny,
WeatherSunset,
WeatherSunsetDown,
WeatherSunsetUp,
WeatherWindy,
WeatherWindyVariant,
Web,
Webcam,
Webhook,
Webpack,
Wechat,
Weight,
WeightKilogram,
WeightKg=WeightKilogram,
WeightPound,
WeightLb=WeightPound,
Whatsapp,
WheelchairAccessibility,
Accessible=WheelchairAccessibility,
Whistle,
WhiteBalanceAuto,
WbAuto=WhiteBalanceAuto,
WhiteBalanceIncandescent,
WbIncandescent=WhiteBalanceIncandescent,
WhiteBalanceIridescent,
WbIridescent=WhiteBalanceIridescent,
WhiteBalanceSunny,
WbSunny=WhiteBalanceSunny,
Widgets,
Wifi,
WifiOff,
WifiStrength1,
WifiStrength1Alert,
WifiStrength1Warning=WifiStrength1Alert,
WifiStrength1Lock,
WifiStrength2,
WifiStrength2Alert,
WifiStrength2Warning=WifiStrength2Alert,
WifiStrength2Lock,
WifiStrength3,
WifiStrength3Alert,
WifiStrength3Warning=WifiStrength3Alert,
WifiStrength3Lock,
WifiStrength4,
WifiStrength4Alert,
WifiStrength4Warning=WifiStrength4Alert,
WifiStrength4Lock,
WifiStrengthAlertOutline,
WifiStrengthWarningOutline=WifiStrengthAlertOutline,
WifiStrength0Alert=WifiStrengthAlertOutline,
WifiStrength0Warning=WifiStrengthAlertOutline,
WifiStrengthLockOutline,
WifiStrength0Lock=WifiStrengthLockOutline,
WifiStrengthOff,
WifiStrengthOffOutline,
WifiStrengthOutline,
WifiStrength0=WifiStrengthOutline,
Wii,
NintendoWii=Wii,
Wiiu,
NintendoWiiu=Wiiu,
Wikipedia,
WindowClose,
WindowClosed,
WindowMaximize,
WindowMinimize,
WindowOpen,
WindowRestore,
Windows,
MicrosoftWindows=Windows,
WindowsClassic,
MicrosoftWindowsClassic=WindowsClassic,
Wiper,
Wordpress,
Worker,
Wrap,
WrapDisabled,
Unwrap=WrapDisabled,
Wrench,
Build=Wrench,
WrenchOutline,
BuildOutline=WrenchOutline,
Wunderlist,
Xamarin,
MicrosoftXamarin=Xamarin,
XamarinOutline,
MicrosoftXamarinOutline=XamarinOutline,
Xaml,
Xbox,
XboxLive=Xbox,
XboxController,
XboxControllerBatteryAlert,
XboxControllerBatteryWarning=XboxControllerBatteryAlert,
XboxControllerBatteryCharging,
XboxControllerBatteryEmpty,
XboxControllerBatteryFull,
XboxControllerBatteryLow,
XboxControllerBatteryMedium,
XboxControllerBatteryUnknown,
XboxControllerOff,
Xda,
Xing,
XingBox,
XingCircle,
Xml,
Xmpp,
Yahoo,
Yammer,
Yeast,
Yelp,
YinYang,
Taoism=YinYang,
Youtube,
VideoYoutube=Youtube,
YoutubePlay=Youtube,
YoutubeCreatorStudio,
YoutubeGaming,
YoutubeTv,
ZWave,
Zwave=ZWave,
Zend,
ZipBox,
ZipDisk,
ZodiacAquarius,
HoroscopeAquarius=ZodiacAquarius,
ZodiacAries,
HoroscopeAries=ZodiacAries,
ZodiacCancer,
HoroscopeCancer=ZodiacCancer,
ZodiacCapricorn,
HoroscopeCapricorn=ZodiacCapricorn,
ZodiacGemini,
HoroscopeGemini=ZodiacGemini,
ZodiacLeo,
HoroscopeLeo=ZodiacLeo,
ZodiacLibra,
HoroscopeLibra=ZodiacLibra,
ZodiacPisces,
HoroscopePisces=ZodiacPisces,
ZodiacSagittarius,
HoroscopeSagittarius=ZodiacSagittarius,
ZodiacScorpio,
HoroscopeScorpio=ZodiacScorpio,
ZodiacTaurus,
HoroscopeTaurus=ZodiacTaurus,
ZodiacVirgo,
HoroscopeVirgo=ZodiacVirgo }
}
| |
// 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.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitAuthorizationsOperations operations.
/// </summary>
internal partial class ExpressRouteCircuitAuthorizationsOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteCircuitAuthorizationsOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteCircuitAuthorizationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExpressRouteCircuitAuthorizationsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-08-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ExpressRouteCircuitAuthorization> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-08-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-08-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (authorizationParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-08-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("authorizationParameters", authorizationParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(authorizationParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(authorizationParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Tests
{
public static class LazyTests
{
[Fact]
public static void Test_Ctor()
{
var lazyString = new Lazy<string>();
VerifyLazy(lazyString, "", false);
var lazyObject = new Lazy<int>();
VerifyLazy(lazyObject, 0, true);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestCtor_Bool(bool isThreadSafe)
{
var lazyString = new Lazy<string>(isThreadSafe);
VerifyLazy(lazyString, "", false);
}
[Fact]
public static void TestCtor_ValueFactory()
{
var lazyString = new Lazy<string>(() => "foo");
VerifyLazy(lazyString, "foo", true);
var lazyInt = new Lazy<int>(() => 1);
VerifyLazy(lazyInt, 1, true);
}
[Fact]
public static void TestCtor_ValueFactory_Invalid()
{
Assert.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null)); // Value factory is null
}
[Fact]
public static void TestCtor_LazyThreadSafetyMode()
{
var lazyString = new Lazy<string>(LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyString, "", false);
}
[Fact]
public static void TestCtor_LazyThreadSafetyMode_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(LazyThreadSafetyMode.None - 1)); // Invalid thread saftety mode
Assert.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(LazyThreadSafetyMode.ExecutionAndPublication + 1)); // Invalid thread saftety mode
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestCtor_ValueFactor_Bool(bool isThreadSafe)
{
var lazyString = new Lazy<string>(() => "foo", isThreadSafe);
VerifyLazy(lazyString, "foo", true);
}
[Fact]
public static void TestCtor_ValueFactory_Bool_NullValueFactory_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null, false)); // Value factory is null
}
[Fact]
public static void TestCtor_ValueFactor_LazyThreadSafetyMode()
{
var lazyString = new Lazy<string>(() => "foo", LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyString, "foo", true);
var lazyInt = new Lazy<int>(() => 1, LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyInt, 1, true);
}
[Fact]
public static void TestCtor_ValueFactor_LazyThreadSafetyMode_Invalid()
{
Assert.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null, LazyThreadSafetyMode.PublicationOnly)); // Value factory is null
Assert.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(() => "foo", LazyThreadSafetyMode.None - 1)); // Invalid thread saftety mode
Assert.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(() => "foof", LazyThreadSafetyMode.ExecutionAndPublication + 1)); // Invalid thread saftety mode
}
[Fact]
public static void TestToString_DoesntForceAllocation()
{
var lazy = new Lazy<object>(() => 1);
Assert.NotEqual("1", lazy.ToString());
Assert.False(lazy.IsValueCreated);
object tmp = lazy.Value;
Assert.Equal("1", lazy.ToString());
}
[Fact]
public static void TestValue_Invalid()
{
string lazilyAllocatedValue = "abc";
int x = 0;
Lazy<string> lazy = null;
lazy = new Lazy<string>(() => x++ < 5 ? lazy.Value : "Test", true);
Assert.Throws<InvalidOperationException>(() => lazilyAllocatedValue = lazy.Value);
Assert.Equal("abc", lazilyAllocatedValue);
}
[Theory]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
[InlineData(LazyThreadSafetyMode.None)]
public static void TestValue_ThrownException_DoesntCreateValue(LazyThreadSafetyMode mode)
{
var lazy = new Lazy<string>(() => { throw new DivideByZeroException(); }, mode);
Exception exception1 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Exception exception2 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Assert.Same(exception1, exception2);
Assert.False(lazy.IsValueCreated);
}
[Fact]
public static void TestValue_ThrownException_DoesntCreateValue_PublicationOnly()
{
var lazy = new Lazy<string>(() => { throw new DivideByZeroException(); }, LazyThreadSafetyMode.PublicationOnly);
Exception exception1 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Exception exception2 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Assert.NotSame(exception1, exception2);
Assert.False(lazy.IsValueCreated);
}
[Fact]
public static void TestEnsureInitalized_SimpleRefTypes()
{
var hdcTemplate = new HasDefaultCtor();
string strTemplate = "foo";
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
Assert.NotNull(LazyInitializer.EnsureInitialized(ref a));
Assert.Same(a, LazyInitializer.EnsureInitialized(ref a));
Assert.NotNull(a);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b));
Assert.Same(b, LazyInitializer.EnsureInitialized(ref b));
Assert.Equal(hdcTemplate, b);
// Func based initialization (uninitialized).
string c = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, () => strTemplate));
Assert.Same(c, LazyInitializer.EnsureInitialized(ref c));
Assert.Equal(strTemplate, c);
// Func based initialization (already initialized).
string d = strTemplate;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, () => strTemplate + "bar"));
Assert.Same(d, LazyInitializer.EnsureInitialized(ref d));
Assert.Equal(strTemplate, d);
}
[Fact]
public static void TestEnsureInitalized_SimpleRefTypes_Invalid()
{
// Func based initialization (nulls not permitted).
string e = null;
Assert.Throws<InvalidOperationException>(() => LazyInitializer.EnsureInitialized(ref e, () => null));
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized(ref ndc));
}
[Fact]
public static void TestEnsureInitialized_ComplexRefTypes()
{
string strTemplate = "foo";
var hdcTemplate = new HasDefaultCtor();
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
bool aInit = false;
object aLock = null;
Assert.NotNull(LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock));
Assert.NotNull(a);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
bool bInit = true;
object bLock = null;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock));
Assert.Equal(hdcTemplate, b);
// Func based initialization (uninitialized).
string c = null;
bool cInit = false;
object cLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => strTemplate));
Assert.Equal(strTemplate, c);
// Func based initialization (already initialized).
string d = strTemplate;
bool dInit = true;
object dLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => strTemplate + "bar"));
Assert.Equal(strTemplate, d);
// Func based initialization (nulls *ARE* permitted).
string e = null;
bool einit = false;
object elock = null;
int initCount = 0;
Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return null; }));
Assert.Null(e);
Assert.Equal(1, initCount);
Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return null; }));
}
[Fact]
public static void TestEnsureInitalized_ComplexRefTypes_Invalid()
{
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
bool ndcInit = false;
object ndcLock = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized(ref ndc, ref ndcInit, ref ndcLock));
}
[Fact]
public static void TestLazyInitializerComplexValueTypes()
{
var empty = new LIX();
var template = new LIX(33);
// Activator.CreateInstance (uninitialized).
LIX a = default(LIX);
bool aInit = false;
object aLock = null;
LIX ensuredValA = LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock);
Assert.Equal(empty, ensuredValA);
Assert.Equal(empty, a);
// Activator.CreateInstance (already initialized).
LIX b = template;
bool bInit = true;
object bLock = null;
LIX ensuredValB = LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock);
Assert.Equal(template, ensuredValB);
Assert.Equal(template, b);
// Func based initialization (uninitialized).
LIX c = default(LIX);
bool cInit = false;
object cLock = null;
LIX ensuredValC = LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => template);
Assert.Equal(template, c);
Assert.Equal(template, ensuredValC);
// Func based initialization (already initialized).
LIX d = template;
bool dInit = true;
object dLock = null;
LIX template2 = new LIX(template.f * 2);
LIX ensuredValD = LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => template2);
Assert.Equal(template, ensuredValD);
Assert.Equal(template, d);
}
private static void VerifyLazy<T>(Lazy<T> lazy, T expectedValue, bool hasValue)
{
Assert.False(lazy.IsValueCreated);
if (hasValue)
{
Assert.Equal(expectedValue, lazy.Value);
Assert.True(lazy.IsValueCreated);
}
else
{
Assert.Throws<MissingMemberException>(() => lazy.Value); // Value could not be created
Assert.False(lazy.IsValueCreated);
}
}
private class HasDefaultCtor { }
private class NoDefaultCtor
{
public NoDefaultCtor(int x) { }
}
private struct LIX
{
public int f;
public LIX(int f) { this.f = f; }
public override bool Equals(object other) => other is LIX && ((LIX)other).f == f;
public override int GetHashCode() => f.GetHashCode();
public override string ToString() => "LIX<" + f + ">";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Test.ModuleCore;
using System;
using System.IO;
using System.Text;
using System.Xml;
using XmlCoreTest.Common;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
//[TestCase(Name = "ReadContentAsBase64", Desc = "ReadContentAsBase64")]
public partial class TCReadContentAsBase64 : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public const string strNumBase64 = "0123456789+/";
public override void Init()
{
base.Init();
CreateBase64TestFile(pBase64Xml);
}
public override void Terminate()
{
DeleteTestFile(pBase64Xml);
base.Terminate();
}
private bool VerifyInvalidReadBase64(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadContentAsBase64(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestOnInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnNodeType(DataReader, nt);
if (!DataReader.CanReadBinaryContent) return;
try
{
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1);
}
catch (InvalidOperationException ioe)
{
if (ioe.ToString().IndexOf(nt.ToString()) < 0)
TestLog.Compare(false, "Call threw wrong invalid operation exception on " + nt);
else
return;
}
TestLog.Compare(false, "Call succeeded on " + nt);
}
protected void TestOnNopNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.Compare(nBytes, 0, "nBytes");
TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn");
}
//[Variation("ReadBase64 Element with all valid value")]
public void TestReadBase64_1()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid Num value", Priority = 0)]
public void TestReadBase64_2()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, strNumBase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid Text value")]
public void TestReadBase64_3()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, strTextBase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid value (from concatenation), Priority=0")]
public void TestReadBase64_5()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with Long valid value (from concatenation), Priority=0")]
public void TestReadBase64_6()
{
int base64len = 0;
byte[] base64 = new byte[2000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
string strExpbase64 = "";
for (int i = 0; i < 10; i++)
strExpbase64 += (strTextBase64 + strNumBase64);
TestLog.Compare(strActbase64, strExpbase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 with count > buffer size")]
public void ReadBase64_7()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 6, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 with count < 0")]
public void ReadBase64_8()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 2, -1, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 with index > buffer size")]
public void ReadBase64_9()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 5, 1, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 with index < 0")]
public void ReadBase64_10()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, -1, 1, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 with index + count exceeds buffer")]
public void ReadBase64_11()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 10, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 index & count =0")]
public void ReadBase64_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
iCount = DataReader.ReadContentAsBase64(buffer, 0, 0);
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBase64 Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBase64_13()
{
int base64len = 20;
byte[] base64 = new byte[base64len];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
DataReader.ReadContentAsBase64(base64, i, 2);
strActbase64 = (System.BitConverter.ToChar(base64, i)).ToString();
TestLog.Compare(String.Compare(strActbase64, 0, strTextBase64, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBase64 with buffer == null")]
public void TestReadBase64_14()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadContentAsBase64(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBase64 after failure")]
public void TestReadBase64_15()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemErr");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_InvalidBase64Value", e, 0, 1);
}
}
//[Variation("Read after partial ReadBase64", Priority = 0)]
public void TestReadBase64_16()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadContentAsBase64(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "1vn");
}
//[Variation("Current node on multiple calls")]
public void TestReadBase64_17()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadContentAsBase64(buffer, 0, 2);
TestLog.Compare(nRead, 2, "0");
nRead = DataReader.ReadContentAsBase64(buffer, 0, 23);
TestLog.Compare(nRead, 22, "1");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype not end element");
TestLog.Compare(DataReader.Name, "ElemText", "Nodetype not end element");
}
//[Variation("No op node types")]
public void TestReadBase64_18()
{
TestOnInvalidNodeType(XmlNodeType.DocumentType);
TestOnInvalidNodeType(XmlNodeType.EndElement);
}
//[Variation("ReadBase64 with incomplete sequence")]
public void TestTextReadBase64_23()
{
byte[] expected = new byte[] { 0, 16, 131, 16, 81 };
byte[] buffer = new byte[10];
string strxml = "<r><ROOT>ABCDEFG</ROOT></r>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "ROOT");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBase64(buffer, result, 1)) > 0)
result += nRead;
TestLog.Compare(result, expected.Length, "res");
for (int i = 0; i < result; i++)
TestLog.Compare(buffer[i], expected[i], "buffer[" + i + "]");
}
//[Variation("ReadBase64 when end tag doesn't exist")]
public void TestTextReadBase64_24()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('c', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
DataReader.ReadContentAsBase64(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("ReadBase64 with whitespaces in the mIddle")]
public void TestTextReadBase64_26()
{
byte[] buffer = new byte[1];
string strxml = "<abc> AQID B B </abc>";
int nRead;
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
for (int i = 0; i < 4; i++)
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 1, "res" + i);
TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 0, "nRead 0");
}
//[Variation("ReadBase64 with = in the mIddle")]
public void TestTextReadBase64_27()
{
byte[] buffer = new byte[1];
string strxml = "<abc>AQI=ID</abc>";
int nRead;
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
for (int i = 0; i < 2; i++)
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 1, "res" + i);
TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
try
{
DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.WriteLine("ReadBase64 with = in the middle succeeded");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_InvalidBase64Value", e, 0, 1);
}
}
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "1000000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000000" })]
public void RunBase64DoesnNotRunIntoOverflow()
{
int totalfilesize = Convert.ToInt32(Variation.Params[0].ToString());
string ascii = new string('c', totalfilesize);
byte[] bits = Encoding.Unicode.GetBytes(ascii);
string base64str = Convert.ToBase64String(bits);
string fileName = "bug105376_" + Variation.Params[0].ToString() + ".xml";
FilePathUtil.addStream(fileName, new MemoryStream());
StreamWriter sw = new StreamWriter(FilePathUtil.getStream(fileName));
sw.Write("<root><base64>");
sw.Write(base64str);
sw.Write("</base64></root>");
sw.Flush();
XmlReader DataReader = GetReader(fileName);
int SIZE = (totalfilesize - 30);
int SIZE64 = SIZE * 3 / 4;
PositionOnElement(DataReader, "base64");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] base64 = new byte[SIZE64];
int startPos = 0;
int readSize = 4096;
int currentSize = 0;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, readSize, "Read other than first chunk");
readSize = SIZE64 - readSize;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, readSize, "Read other than remaining Chunk Size");
readSize = 0;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, 0, "Read other than Zero Bytes");
DataReader.Dispose();
}
}
//[TestCase(Name = "ReadElementContentAsBase64", Desc = "ReadElementContentAsBase64")]
public partial class TCReadElementContentAsBase64 : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public const string strNumBase64 = "0123456789+/";
public override void Init()
{
base.Init();
CreateBase64TestFile(pBase64Xml);
}
public override void Terminate()
{
DeleteTestFile(pBase64Xml);
base.Terminate();
}
private bool VerifyInvalidReadBase64(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadContentAsBase64(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestOnInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnNodeType(DataReader, nt);
if (!DataReader.CanReadBinaryContent) return;
try
{
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
}
catch (InvalidOperationException ioe)
{
if (ioe.ToString().IndexOf(nt.ToString()) < 0)
TestLog.Compare(false, "Call threw wrong invalid operation exception on " + nt);
else
return;
}
TestLog.Compare(false, "Call succeeded on " + nt);
}
//[Variation("ReadBase64 Element with all valid value")]
public void TestReadBase64_1()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid Num value", Priority = 0)]
public void TestReadBase64_2()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, strNumBase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid Text value")]
public void TestReadBase64_3()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, strTextBase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid value (from concatenation), Priority=0")]
public void TestReadBase64_5()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with Long valid value (from concatenation), Priority=0")]
public void TestReadBase64_6()
{
int base64len = 0;
byte[] base64 = new byte[2000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
string strExpbase64 = "";
for (int i = 0; i < 10; i++)
strExpbase64 += (strTextBase64 + strNumBase64);
TestLog.Compare(strActbase64, strExpbase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 with count > buffer size")]
public void ReadBase64_7()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 with count < 0")]
public void ReadBase64_8()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 with index > buffer size")]
public void ReadBase64_9()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 with index < 0")]
public void ReadBase64_10()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 with index + count exceeds buffer")]
public void ReadBase64_11()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 index & count =0")]
public void ReadBase64_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
iCount = DataReader.ReadElementContentAsBase64(buffer, 0, 0);
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBase64 Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBase64_13()
{
int base64len = 20;
byte[] base64 = new byte[base64len];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
DataReader.ReadElementContentAsBase64(base64, i, 2);
strActbase64 = (System.BitConverter.ToChar(base64, i)).ToString();
TestLog.Compare(String.Compare(strActbase64, 0, strTextBase64, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBase64 with buffer == null")]
public void TestReadBase64_14()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadElementContentAsBase64(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBase64 after failure")]
public void TestReadBase64_15()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemErr");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_InvalidBase64Value", e, 0, 1);
}
}
//[Variation("Read after partial ReadBase64", Priority = 0)]
public void TestReadBase64_16()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemNum");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "1vn");
}
//[Variation("Current node on multiple calls")]
public void TestReadBase64_17()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemNum");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 2);
TestLog.Compare(nRead, 2, "0");
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 23);
TestLog.Compare(nRead, 22, "1");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Nodetype not end element");
TestLog.Compare(DataReader.Name, "ElemNum", "Nodetype not end element");
}
//[Variation("No op node types")]
public void TestReadBase64_18()
{
TestOnInvalidNodeType(XmlNodeType.DocumentType);
}
//[Variation("ReadBase64 with incomplete sequence")]
public void TestTextReadBase64_23()
{
byte[] expected = new byte[] { 0, 16, 131, 16, 81 };
byte[] buffer = new byte[10];
string strxml = "<r><ROOT>ABCDEFG</ROOT></r>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "ROOT");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBase64(buffer, result, 1)) > 0)
result += nRead;
TestLog.Compare(result, expected.Length, "res");
for (int i = 0; i < result; i++)
TestLog.Compare(buffer[i], expected[i], "buffer[" + i + "]");
}
//[Variation("ReadBase64 when end tag doesn't exist")]
public void TestTextReadBase64_24()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('c', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
if (!DataReader.CanReadBinaryContent) return;
DataReader.ReadElementContentAsBase64(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("ReadBase64 with whitespaces in the mIddle")]
public void TestTextReadBase64_26()
{
byte[] buffer = new byte[1];
string strxml = "<abc> AQID B B </abc>";
int nRead;
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
for (int i = 0; i < 4; i++)
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 1, "res" + i);
TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 0, "nRead 0");
}
//[Variation("ReadBase64 with = in the mIddle")]
public void TestTextReadBase64_27()
{
byte[] buffer = new byte[1];
string strxml = "<abc>AQI=ID</abc>";
int nRead;
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
for (int i = 0; i < 2; i++)
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 1, "res" + i);
TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
try
{
DataReader.ReadElementContentAsBase64(buffer, 0, 1);
TestLog.WriteLine("ReadBase64 with = in the middle succeeded");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_InvalidBase64Value", e, 0, 1);
}
}
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "1000000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000000" })]
public void ReadBase64DoesNotRunIntoOverflow2()
{
int totalfilesize = Convert.ToInt32(Variation.Params[0].ToString());
string ascii = new string('c', totalfilesize);
byte[] bits = Encoding.Unicode.GetBytes(ascii);
string base64str = Convert.ToBase64String(bits);
string fileName = "bug105376_" + Variation.Params[0].ToString() + ".xml";
FilePathUtil.addStream(fileName, new MemoryStream());
StreamWriter sw = new StreamWriter(FilePathUtil.getStream(fileName));
sw.Write("<root><base64>");
sw.Write(base64str);
sw.Write("</base64></root>");
sw.Flush();
XmlReader DataReader = GetReader(fileName);
int SIZE = (totalfilesize - 30);
int SIZE64 = SIZE * 3 / 4;
PositionOnElement(DataReader, "base64");
if (!DataReader.CanReadBinaryContent) return;
byte[] base64 = new byte[SIZE64];
int startPos = 0;
int readSize = 4096;
int currentSize = 0;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, readSize, "Read other than first chunk");
readSize = SIZE64 - readSize;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, readSize, "Read other than remaining Chunk Size");
readSize = 0;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, 0, "Read other than Zero Bytes");
DataReader.Dispose();
}
//[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBase64")]
public void SubtreeReaderInsertedAttributesWontWorkWithReadContentAsBase64()
{
string strxml1 = "<root xmlns='";
string strxml2 = "'><bar/></root>";
string[] binValue = new string[] { "AAECAwQFBgcI==", "0102030405060708090a0B0c" };
for (int i = 0; i < binValue.Length; i++)
{
string strxml = strxml1 + binValue[i] + strxml2;
using (XmlReader r = GetReader(new StringReader(strxml)))
{
r.Read();
r.Read();
using (XmlReader sr = r.ReadSubtree())
{
if (!sr.CanReadBinaryContent) return;
sr.Read();
sr.MoveToFirstAttribute();
sr.MoveToFirstAttribute();
byte[] bytes = new byte[4];
while ((sr.ReadContentAsBase64(bytes, 0, bytes.Length)) > 0) { }
}
}
}
}
}
}
}
}
| |
//
// PodcastService.cs
//
// Authors:
// Mike Urbanski <michael.c.urbanski@gmail.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Michael C. Urbanski
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Mono.Unix;
using Hyena;
using Banshee.Base;
using Banshee.ServiceStack;
using Migo.TaskCore;
using Migo.Syndication;
using Migo.DownloadCore;
using Banshee.Networking;
using Banshee.MediaEngine;
using Banshee.Podcasting.Gui;
using Banshee.Podcasting.Data;
using Banshee.Collection.Database;
using Banshee.Configuration;
namespace Banshee.Podcasting
{
public partial class PodcastService : IExtensionService, IDisposable, IDelayedInitializeService
{
private readonly string tmp_download_path = Paths.Combine (Paths.ExtensionCacheRoot, "podcasting", "partial-downloads");
private uint refresh_timeout_id = 0;
private bool disposed;
private DownloadManager download_manager;
private DownloadManagerInterface download_manager_iface;
private FeedsManager feeds_manager;
private PodcastSource source;
//private PodcastImportManager import_manager;
private readonly object sync = new object ();
public PodcastService ()
{
Migo.Net.AsyncWebClient.DefaultUserAgent = Banshee.Web.Browser.UserAgent;
}
private void MigrateLegacyIfNeeded ()
{
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) == 0) {
if (ServiceManager.DbConnection.TableExists ("Podcasts") &&
ServiceManager.DbConnection.Query<int> ("select count(*) from podcastsyndications") == 0) {
Hyena.Log.Information ("Migrating Podcast Feeds and Items");
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastSyndications (FeedID, Title, Url, Link,
Description, ImageUrl, LastBuildDate, AutoDownload, IsSubscribed)
SELECT
PodcastFeedID,
Title,
FeedUrl,
Link,
Description,
Image,
strftime(""%s"", LastUpdated),
SyncPreference,
1
FROM PodcastFeeds
");
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastItems (ItemID, FeedID, Title, Link, PubDate,
Description, Author, Active, Guid)
SELECT
PodcastID,
PodcastFeedID,
Title,
Link,
strftime(""%s"", PubDate),
Description,
Author,
Active,
Url
FROM Podcasts
");
// Note: downloaded*3 is because the value was 0 or 1, but is now 0 or 3 (FeedDownloadStatus.None/Downloaded)
ServiceManager.DbConnection.Execute(@"
INSERT INTO PodcastEnclosures (ItemID, LocalPath, Url, MimeType, FileSize, DownloadStatus)
SELECT
PodcastID,
LocalPath,
Url,
MimeType,
Length,
Downloaded*3
FROM Podcasts
");
// Finally, move podcast items from the Music Library to the Podcast source
int [] primary_source_ids = new int [] { ServiceManager.SourceManager.MusicLibrary.DbId };
int moved = 0;
foreach (FeedEnclosure enclosure in FeedEnclosure.Provider.FetchAllMatching ("LocalPath IS NOT NULL AND LocalPath != ''")) {
SafeUri uri = new SafeUri (enclosure.LocalPath);
int track_id = DatabaseTrackInfo.GetTrackIdForUri (uri, primary_source_ids);
if (track_id > 0) {
PodcastTrackInfo pi = new PodcastTrackInfo (DatabaseTrackInfo.Provider.FetchSingle (track_id));
pi.Item = enclosure.Item;
pi.Track.PrimarySourceId = source.DbId;
pi.SyncWithFeedItem ();
pi.Track.Save (false);
moved++;
}
}
if (moved > 0) {
ServiceManager.SourceManager.MusicLibrary.Reload ();
source.Reload ();
}
Hyena.Log.Information ("Done Migrating Podcast Feeds and Items");
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 1);
}
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 3) {
// We were using the Link as the fallback if the actual Guid was missing, but that was a poor choice
// since it is not always unique. We now use the title and pubdate combined.
ServiceManager.DbConnection.Execute ("UPDATE PodcastItems SET Guid = NULL");
foreach (FeedItem item in FeedItem.Provider.FetchAll ()) {
item.Guid = null;
if (item.Feed == null || FeedItem.Exists (item.Feed.DbId, item.Guid)) {
item.Delete (false);
} else {
item.Save ();
}
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 3);
}
// Intentionally skpping 4 here because this needs to get run again for anybody who ran it
// before it was fixed, but only once if you never ran it
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 5) {
ReplaceNewlines ("CoreTracks", "Title");
ReplaceNewlines ("CoreTracks", "TitleLowered");
ReplaceNewlines ("PodcastItems", "Title");
ReplaceNewlines ("PodcastItems", "Description");
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 5);
}
// Initialize the new StrippedDescription field
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 6) {
foreach (FeedItem item in FeedItem.Provider.FetchAll ()) {
item.UpdateStrippedDescription ();
item.Save ();
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 6);
}
}
private void MigrateDownloadCache ()
{
string old_download_dir = Path.Combine (Paths.ApplicationData, "downloads");
if (Directory.Exists (old_download_dir)) {
foreach (string old_subdir in Directory.GetDirectories (old_download_dir)) {
string subdir_name = Path.GetFileName (old_subdir);
string new_subdir = Path.Combine (tmp_download_path, subdir_name);
Directory.Move (old_subdir, new_subdir);
}
Directory.Delete (old_download_dir);
}
}
private void ReplaceNewlines (string table, string column)
{
string cmd = String.Format ("UPDATE {0} SET {1}=replace({1}, ?, ?)", table, column);
ServiceManager.DbConnection.Execute (cmd, "\r\n", String.Empty);
ServiceManager.DbConnection.Execute (cmd, "\n", String.Empty);
ServiceManager.DbConnection.Execute (cmd, "\r", String.Empty);
}
public void Initialize ()
{
}
public void DelayedInitialize ()
{
download_manager = new DownloadManager (2, tmp_download_path);
download_manager_iface = new DownloadManagerInterface (download_manager);
download_manager_iface.Initialize ();
feeds_manager = new FeedsManager (ServiceManager.DbConnection, download_manager, null);
// Migrate data from 0.13.2 podcast tables, if they exist
MigrateLegacyIfNeeded ();
// Move incomplete downloads to the new cache location
try {
MigrateDownloadCache ();
} catch (Exception e) {
Hyena.Log.Exception ("Couldn't migrate podcast download cache", e);
}
source = new PodcastSource ();
ServiceManager.SourceManager.AddSource (source);
InitializeInterface ();
ThreadAssist.SpawnFromMain (delegate {
feeds_manager.PodcastStorageDirectory = source.BaseDirectory;
feeds_manager.FeedManager.ItemAdded += OnItemAdded;
feeds_manager.FeedManager.ItemChanged += OnItemChanged;
feeds_manager.FeedManager.ItemRemoved += OnItemRemoved;
feeds_manager.FeedManager.FeedsChanged += OnFeedsChanged;
if (DatabaseConfigurationClient.Client.Get<int> ("Podcast", "Version", 0) < 7) {
Banshee.Library.LibrarySource music_lib = ServiceManager.SourceManager.MusicLibrary;
if (music_lib != null) {
string old_path = Path.Combine (music_lib.BaseDirectory, "Podcasts");
string new_path = source.BaseDirectory;
SafeUri old_uri = new SafeUri (old_path);
SafeUri new_uri = new SafeUri (new_path);
if (old_path != null && new_path != null && old_path != new_path &&
Banshee.IO.Directory.Exists (old_path) && !Banshee.IO.Directory.Exists (new_path)) {
Banshee.IO.Directory.Move (new SafeUri (old_path), new SafeUri (new_path));
ServiceManager.DbConnection.Execute (String.Format (
"UPDATE {0} SET LocalPath = REPLACE(LocalPath, ?, ?) WHERE LocalPath IS NOT NULL",
FeedEnclosure.Provider.TableName), old_path, new_path);
ServiceManager.DbConnection.Execute (
"UPDATE CoreTracks SET Uri = REPLACE(Uri, ?, ?) WHERE Uri LIKE 'file://%' AND PrimarySourceId = ?",
old_uri.AbsoluteUri, new_uri.AbsoluteUri, source.DbId);
Hyena.Log.DebugFormat ("Moved Podcasts from {0} to {1}", old_path, new_path);
}
}
DatabaseConfigurationClient.Client.Set<int> ("Podcast", "Version", 7);
}
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StateChange);
ServiceManager.Get<DBusCommandService> ().ArgumentPushed += OnCommandLineArgument;
RefreshFeeds ();
// Every 10 minutes try to refresh again
refresh_timeout_id = Application.RunTimeout (1000 * 60 * 10, RefreshFeeds);
ServiceManager.Get<Network> ().StateChanged += OnNetworkStateChanged;
});
source.UpdateFeedMessages ();
}
private void OnNetworkStateChanged (object o, NetworkStateChangedArgs args)
{
RefreshFeeds ();
}
bool disposing;
public void Dispose ()
{
lock (sync) {
if (disposing | disposed) {
return;
} else {
disposing = true;
}
}
Application.IdleTimeoutRemove (refresh_timeout_id);
refresh_timeout_id = 0;
ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);
ServiceManager.Get<DBusCommandService> ().ArgumentPushed -= OnCommandLineArgument;
ServiceManager.Get<Network> ().StateChanged -= OnNetworkStateChanged;
if (download_manager_iface != null) {
download_manager_iface.Dispose ();
download_manager_iface = null;
}
if (feeds_manager != null) {
feeds_manager.Dispose ();
feeds_manager = null;
}
if (download_manager != null) {
download_manager.Dispose ();
download_manager = null;
}
DisposeInterface ();
lock (sync) {
disposing = false;
disposed = true;
}
}
private bool RefreshFeeds ()
{
if (!ServiceManager.Get<Network> ().Connected)
return true;
Hyena.Log.Debug ("Refreshing any podcasts that haven't been updated in over an hour");
Banshee.Kernel.Scheduler.Schedule (new Banshee.Kernel.DelegateJob (delegate {
DateTime now = DateTime.Now;
foreach (Feed feed in Feed.Provider.FetchAll ()) {
if (feed.IsSubscribed && (now - feed.LastDownloadTime).TotalHours > 1) {
feed.Update ();
RefreshArtworkFor (feed);
}
}
}));
return true;
}
private void OnCommandLineArgument (string argument, object value, bool isFile)
{
if (isFile) {
ProcessFile (argument, null);
} else if (argument == "podcast") {
var podcast = Hyena.Json.JsonObject.FromString (value as string);
if (podcast != null) {
ProcessFile ((string)podcast["uri"], (string)podcast["name"]);
}
}
}
private void ProcessFile (string uri, string title)
{
if (String.IsNullOrEmpty (uri)) {
return;
}
if (uri.Contains ("opml") || uri.EndsWith (".miro") || uri.EndsWith (".democracy")) {
// Handle OPML files
try {
OpmlParser opml_parser = new OpmlParser (uri, true);
foreach (string feed in opml_parser.Feeds) {
ProcessFile (feed, title);
}
} catch (Exception e) {
Log.Exception (e);
}
} else if (uri.Contains ("xml") || uri.Contains ("rss") || uri.Contains ("feed") || uri.StartsWith ("itpc") || uri.StartsWith ("pcast")) {
// Handle normal XML/RSS URLs
if (uri.StartsWith ("feed://") || uri.StartsWith ("itpc://")) {
uri = String.Format ("http://{0}", uri.Substring (7));
} else if (uri.StartsWith ("pcast://")) {
uri = String.Format ("http://{0}", uri.Substring (8));
}
AddFeed (uri, title);
} else if (uri.StartsWith ("itms://")) {
// Handle iTunes podcast URLs
System.Threading.ThreadPool.QueueUserWorkItem (delegate {
try {
var feed = new ItmsPodcast (uri);
if (feed.FeedUrl != null) {
ThreadAssist.ProxyToMain (delegate {
AddFeed (feed.FeedUrl, feed.Title ?? title);
});
}
} catch (Exception e) {
Hyena.Log.Exception (e);
}
});
}
}
private void AddFeed (string uri, string title)
{
// TODO replace autodownload w/ actual default preference
FeedsManager.Instance.FeedManager.CreateFeed (uri, title, FeedAutoDownload.None, 0);
source.NotifyUser ();
source.UpdateFeedMessages ();
}
private void RefreshArtworkFor (Feed feed)
{
if (!String.IsNullOrEmpty (feed.ImageUrl) && !CoverArtSpec.CoverExists (PodcastService.ArtworkIdFor (feed))) {
Banshee.Kernel.Scheduler.Schedule (new PodcastImageFetchJob (feed), Banshee.Kernel.JobPriority.BelowNormal);
}
}
private DatabaseTrackInfo GetTrackByItemId (long item_id)
{
return DatabaseTrackInfo.Provider.FetchFirstMatching ("PrimarySourceID = ? AND ExternalID = ?", source.DbId, item_id);
}
private void OnItemAdded (FeedItem item)
{
if (item.Enclosure != null) {
DatabaseTrackInfo track = new DatabaseTrackInfo ();
track.ExternalId = item.DbId;
track.PrimarySource = source;
(track.ExternalObject as PodcastTrackInfo).SyncWithFeedItem ();
track.Save (false);
RefreshArtworkFor (item.Feed);
} else {
// We're only interested in items that have enclosures
item.Delete (false);
}
}
private void OnItemRemoved (FeedItem item)
{
DatabaseTrackInfo track = GetTrackByItemId (item.DbId);
if (track != null) {
DatabaseTrackInfo.Provider.Delete (track);
}
}
internal static bool IgnoreItemChanges = false;
private void OnItemChanged (FeedItem item)
{
if (IgnoreItemChanges) {
return;
}
DatabaseTrackInfo track = GetTrackByItemId (item.DbId);
if (track != null) {
PodcastTrackInfo pi = track.ExternalObject as PodcastTrackInfo;
if (pi != null) {
pi.SyncWithFeedItem ();
track.Save (true);
}
}
}
private void OnFeedsChanged (object o, EventArgs args)
{
source.Reload ();
source.NotifyTracksChanged ();
source.UpdateFeedMessages ();
}
/*private void OnFeedAddedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Add (args.Feed);
}
}
private void OnFeedRemovedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Remove (args.Feed);
args.Feed.Delete ();
}
}
private void OnFeedRenamedHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Sort ();
}
}
private void OnFeedUpdatingHandler (object sender, FeedEventArgs args)
{
lock (sync) {
source.FeedModel.Reload ();
}
}
private void OnFeedDownloadCountChangedHandler (object sender, FeedDownloadCountChangedEventArgs args)
{
lock (sync) {
source.FeedModel.Reload ();
}
}*/
/*private void OnFeedItemAddedHandler (object sender, FeedItemEventArgs args)
{
lock (sync) {
if (args.Item != null) {
AddFeedItem (args.Item);
} else if (args.Items != null) {
foreach (FeedItem item in args.Items) {
AddFeedItem (item);
}
}
}
}*/
public void AddFeedItem (FeedItem item)
{
if (item.Enclosure != null) {
PodcastTrackInfo pi = new PodcastTrackInfo (new DatabaseTrackInfo (), item);
pi.Track.PrimarySource = source;
pi.Track.Save (true);
source.NotifyUser ();
} else {
item.Delete (false);
}
}
/*private void OnFeedItemRemovedHandler (object sender, FeedItemEventArgs e)
{
lock (sync) {
if (e.Item != null) {
PodcastItem.DeleteWithFeedId (e.Item.DbId);
} else if (e.Items != null) {
foreach (FeedItem fi in e.Items) {
PodcastItem.DeleteWithFeedId (fi.DbId);
}
}
source.Reload ();
}
}
private void OnFeedItemCountChanged (object sender,
FeedItemCountChangedEventArgs e)
{
//UpdateCount ();
}*/
/*private void OnFeedDownloadCompletedHandler (object sender,
FeedDownloadCompletedEventArgs e)
{
lock (sync) {
Feed f = feedDict[e.Feed.DbId];
if (e.Error == FeedDownloadError.None) {
if (String.IsNullOrEmpty(e.Feed.LocalEnclosurePath)) {
e.Feed.LocalEnclosurePath = Path.Combine (
tmp_enclosure_path, SanitizeName (e.Feed.Name)
);
}
if (f.AutoDownload != FeedAutoDownload.None) {
ReadOnlyCollection<FeedItem> items = e.Feed.Items;
if (items != null) {
if (f.AutoDownload == FeedAutoDownload.One &&
items.Count > 0) {
items[0].Enclosure.AsyncDownload ();
} else {
foreach (FeedItem fi in items) {
fi.Enclosure.AsyncDownload ();
}
}
}
}
}
source.Reload ();
}
}*/
/*private void OnTaskAssociated (object sender, EventArgs e)
{
lock (sync) {
source.Reload ();
}
}
private void OnTaskStatusChanged (object sender,
TaskStatusChangedEventArgs e)
{
lock (sync) {
source.Reload ();
}
}
private void TaskStartedHandler (object sender,
TaskEventArgs<HttpFileDownloadTask> e)
{
lock (sync) {
source.Reload ();
}
}
private void OnTaskStoppedHandler (object sender,
TaskEventArgs<HttpFileDownloadTask> e)
{
// TODO merge
lock (sync) {
if (e.Task != null && e.Task.Status == TaskStatus.Succeeded) {
FeedEnclosure enc = e.Task.UserState as FeedEnclosure;
if (enc != null) {
FeedItem item = enc.Item;
DatabaseTrackInfo track = null;
if (itemDict.ContainsKey (item.DbId)) {
PodcastItem pi = itemDict[item.DbId];
track = import_manager.ImportPodcast (enc.LocalPath);
if (track != null) {
pi.Track = track;
pi.New = true;
pi.Save ();
}
item.IsRead = true;
}
}
}
source.Reload ();
}
}*/
private void OnPlayerEvent (PlayerEventArgs args)
{
lock (sync) {
//source.Reload ();
}
}
public static string ArtworkIdFor (Feed feed)
{
string digest = Banshee.Base.CoverArtSpec.Digest (feed.Title);
return digest == null ? null : String.Format ("podcast-{0}", digest);
}
// Via Monopod
/*private static string SanitizeName (string s)
{
// remove /, : and \ from names
return s.Replace ('/', '_').Replace ('\\', '_').Replace (':', '_').Replace (' ', '_');
}*/
public string ServiceName {
get { return "PodcastService"; }
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* 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 MindTouch.Dream;
namespace MindTouch.Xml {
/// <summary>
/// Provides an a base Xml document abstraction based on <see cref="XDoc"/> with additional methods to ease creating Atom documents.
/// </summary>
public abstract class XAtomBase : XDoc {
//--- Constants ---
/// <summary>
/// Atom xml namespace
/// </summary>
public const string ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
//--- Types ---
/// <summary>
/// Atom link rel attribute enumeration.
/// </summary>
public enum LinkRelation {
/// <summary>
/// Signifies a link that points to an alternate version of the current resource.
/// </summary>
Alternate,
/// <summary>
/// Signifies a link that points to a resource that is related to the current content.
/// </summary>
Related,
/// <summary>
/// Signifies a link to a resource that is the equivalent of the current content.
/// </summary>
Self,
/// <summary>
/// Signifies a link to a related resource that may be large in size or requires special handling.
/// </summary>
Enclosure,
/// <summary>
/// Signifies a link to a resource that is the source of the materail of the current content.
/// </summary>
Via,
/// <summary>
/// Signifies a link to the resource that allows editing of the current content.
/// </summary>
Edit,
/// <summary>
/// Signifies a link to furthest preceeding resource in a series of resources.
/// </summary>
First,
/// <summary>
/// Signifies a link to furthest following resource in a series of resources.
/// </summary>
Last,
/// <summary>
/// Signifies a link to immediately following resource in a series of resources.
/// </summary>
Next,
/// <summary>
/// Signifies a link to immediately preceeding resource in a series of resources.
/// </summary>
Previous
}
//--- Constructors ---
/// <summary>
/// Create a new Atom document from an existing document.
/// </summary>
/// <param name="doc">The source document.</param>
public XAtomBase(XDoc doc) : base(doc) { }
/// <summary>
/// Creates an Atom document with a given root tag and updated date.
/// </summary>
/// <param name="tag">Root tag.</param>
/// <param name="updated">Date the document was last updated.</param>
public XAtomBase(string tag, DateTime updated) : base(tag, ATOM_NAMESPACE) {
Start("generator").Attr("version", DreamUtil.DreamVersion).Value("MindTouch Dream XAtom").End();
Start("updated").Value(updated).End();
}
//--- Properties ---
/// <summary>
/// Atom Id uri.
/// </summary>
public XUri Id {
get {
return this["id"].AsUri;
}
set {
if(value == null) {
this["id"].Remove();
} else if(this["id"].IsEmpty) {
Elem("id", value);
} else {
this["id"].ReplaceValue(value);
}
}
}
//--- Methods ---
/// <summary>
/// Add an author to the document.
/// </summary>
/// <param name="name">Author name.</param>
/// <param name="uri">Uri to Author resource.</param>
/// <param name="email">Author email.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomBase AddAuthor(string name, XUri uri, string email) {
return AddPerson("author", name, uri, email);
}
/// <summary>
/// Add a contributor to the document.
/// </summary>
/// <param name="name">Contributor name.</param>
/// <param name="uri">Uri to Contributor resource.</param>
/// <param name="email">Contributor email.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomBase AddContributor(string name, XUri uri, string email) {
return AddPerson("contributor", name, uri, email);
}
/// <summary>
/// Add a category to the document.
/// </summary>
/// <param name="term">Category term.</param>
/// <param name="scheme">Category scheme.</param>
/// <param name="label">Category label.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomBase AddCategory(string term, XUri scheme, string label) {
if(string.IsNullOrEmpty(term)) {
throw new ArgumentNullException("term");
}
Start("category");
Attr("term", term);
if(scheme != null) {
Attr("scheme", scheme);
}
if(!string.IsNullOrEmpty(label)) {
Attr("label", label);
}
End();
return this;
}
/// <summary>
/// Add a link to the document.
/// </summary>
/// <param name="href">Uri to the linked resource.</param>
/// <param name="relation">Relationship of the linked resource to the current document.</param>
/// <param name="type">Type of resource being linked.</param>
/// <param name="length">Size in bytes.</param>
/// <param name="title">Title of the linked resource.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomBase AddLink(XUri href, LinkRelation relation, MimeType type, long? length, string title) {
Start("link");
Attr("href", href);
Attr("rel", relation.ToString().ToLowerInvariant());
if(type != null) {
Attr("type", type.FullType);
}
if(length != null) {
Attr("length", length ?? 0);
}
if(!string.IsNullOrEmpty(title)) {
Attr("title", title);
}
End();
return this;
}
/// <summary>
/// Add text to the document.
/// </summary>
/// <param name="tag">Enclosing tag for the text.</param>
/// <param name="type">Type attribute for the enclosed.</param>
/// <param name="text">Text content to add.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomBase AddText(string tag, string type, string text) {
Start(tag).Attr("type", type).Value(text).End();
return this;
}
/// <summary>
/// Add text to the document.
/// </summary>
/// <param name="tag">Enclosing tag for the text.</param>
/// <param name="mime">Mime type of the enclosed text.</param>
/// <param name="data">The text body as a byte array.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomBase AddText(string tag, MimeType mime, byte[] data) {
Start(tag).Attr("type", mime.FullType).Value(data).End();
return this;
}
/// <summary>
/// Add text to the document.
/// </summary>
/// <param name="tag">Enclosing tag for the text.</param>
/// <param name="mime">Mime type of the enclosed text.</param>
/// <param name="xml">The body document to add.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomBase AddText(string tag, MimeType mime, XDoc xml) {
if(mime.Match(MimeType.XHTML)) {
Start(tag).Attr("type", "xhtml");
// add content and normalize the root node
XDoc added = xml.Clone().Rename("div");
if(added["@xmlns"].IsEmpty) {
added.Attr("xmlns", "http://www.w3.org/1999/xhtml");
}
Add(added);
} else if(mime.Match(MimeType.HTML)) {
Start(tag).Attr("type", "html");
// embed HTML as text
Value(xml.ToInnerXHtml());
} else {
Start(tag).Attr("type", mime.FullType);
Add(xml);
}
// close element
End();
return this;
}
/// <summary>
/// Add a person reference to the document.
/// </summary>
/// <param name="tag">Enclosing tag for the person entry.</param>
/// <param name="name">Person name.</param>
/// <param name="uri">Uri to Person resource.</param>
/// <param name="email">Person email.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomBase AddPerson(string tag, string name, XUri uri, string email) {
Start(tag);
Elem("name", name ?? string.Empty);
if(uri != null) {
Elem("uri", uri);
}
if(!string.IsNullOrEmpty(email)) {
Elem("email", email);
}
End();
return this;
}
}
/// <summary>
/// Provides a Atom feed document abstraction based on <see cref="XDoc"/>.
/// </summary>
public class XAtomFeed : XAtomBase {
//--- Constructors ---
/// <summary>
/// Parse an existing Atom feed into the <see cref="XAtomFeed"/> representation.
/// </summary>
/// <param name="doc">The document to parse as an atom feed.</param>
public XAtomFeed(XDoc doc) : base(doc) {
if(doc.Name != "feed") {
throw new ArgumentException("doc");
}
UsePrefix("georss", "http://www.georss.org/georss");
UsePrefix("gml", "http://www.opengis.net/gml");
}
/// <summary>
/// Create a new Atom feed.
/// </summary>
/// <param name="title">Title of the feed.</param>
/// <param name="link">Canonical uri to the feed resource.</param>
/// <param name="updated">Last time the feed was updated.</param>
public XAtomFeed(string title, XUri link, DateTime updated) : base("feed", updated) {
if(string.IsNullOrEmpty(title)) {
throw new ArgumentNullException("title");
}
if(link == null) {
throw new ArgumentNullException("link");
}
// feed elements
Start("title").Attr("type", "text").Value(title).End();
Start("link").Attr("rel", "self").Attr("href", link).End();
}
//--- Properties ---
/// <summary>
/// Get an array of all entries in the feed.
/// </summary>
public XAtomEntry[] Entries {
get {
return Array.ConvertAll<XDoc, XAtomEntry>(Root["_:entry"].ToList().ToArray(), entry => new XAtomEntry(entry));
}
}
//--- Methods ---
/// <summary>
/// Start a new entry block.
/// </summary>
/// <remarks>Behaves like the normal <see cref="XDoc.Start(string)"/> and sets the cursor to the new entry until a matching
/// <see cref="XDoc.End()"/> is encountered.</remarks>
/// <param name="title">Entry title.</param>
/// <param name="published">Entry publication date.</param>
/// <param name="updated">Last time the entry was updated.</param>
/// <returns>A new <see cref="XAtomEntry"/> as a node in the current document.</returns>
public XAtomEntry StartEntry(string title, DateTime published, DateTime updated) {
Start("entry");
AddText("title", "text", title);
Elem("published", published);
Elem("updated", updated);
return new XAtomEntry(this);
}
}
/// <summary>
/// Provides a Atom feed entry document abstraction based on <see cref="XDoc"/>.
/// </summary>
public class XAtomEntry : XAtomBase {
//--- Constructors ---
/// <summary>
/// Parse an existing Atom feed entry into the <see cref="XAtomEntry"/> representation.
/// </summary>
/// <param name="doc">Document in the Atom feed entry format.</param>
public XAtomEntry(XDoc doc) : base(doc) {
if(doc.Name != "entry") {
throw new ArgumentException("doc");
}
UsePrefix("georss", "http://www.georss.org/georss");
UsePrefix("gml", "http://www.opengis.net/gml");
}
/// <summary>
/// Create a new Atom feed entry document.
/// </summary>
/// <param name="title">Entry title.</param>
/// <param name="published">Entry publication date.</param>
/// <param name="updated">Last time the entry was updated.</param>
public XAtomEntry(string title, DateTime published, DateTime updated) : base("entry", updated) {
Attr("xmlns:georss", "http://www.georss.org/georss");
UsePrefix("georss", "http://www.georss.org/georss");
Attr("xmlns:gml", "http://www.opengis.net/gml");
UsePrefix("gml", "http://www.opengis.net/gml");
AddText("title", "text", title);
Start("published").Value(published).End();
}
//--- Properties ---
/// <summary>
/// Entry Geo Rss Tag.
/// </summary>
public Tuple<double, double> Where {
get {
XDoc where = Root["georss:where/gml:Point/gml:pos"];
if(where.IsEmpty) {
return null;
}
string[] coords = where.Contents.Split(new char[] { ' ', ',' }, 2, StringSplitOptions.RemoveEmptyEntries);
if(coords.Length != 2) {
return null;
}
double x;
double y;
if(!double.TryParse(coords[0], out x) || !double.TryParse(coords[1], out y)) {
return null;
}
return new Tuple<double, double>(x, y);
}
set {
this["georss:where"].Remove();
if(value != null) {
Root.Start("georss:where").Start("gml:Point").Elem("gml:pos", string.Format("{0} {1}", value.Item1, value.Item2)).End().End();
}
}
}
//--- Methods ---
/// <summary>
/// Add content to the entry.
/// </summary>
/// <param name="text">Text body to add.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomEntry AddContent(string text) {
AddText("content", "text", text);
return this;
}
/// <summary>
/// Add a subdocument as content to the entry.
/// </summary>
/// <param name="mime">Mime type of the document to be added.</param>
/// <param name="xml">Document to add.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomEntry AddContent(MimeType mime, XDoc xml) {
AddText("content", mime, xml);
return this;
}
/// <summary>
/// Add content to the entry.
/// </summary>
/// <param name="mime">Mime type of the content to be added.</param>
/// <param name="data">Content as byte array.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomEntry AddContent(MimeType mime, byte[] data) {
AddText("content", mime, data);
return this;
}
/// <summary>
/// Add an entry summary.
/// </summary>
/// <param name="text">Summary text.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomEntry AddSummary(string text) {
AddText("summary", "text", text);
return this;
}
/// <summary>
/// Add an entry summary document.
/// </summary>
/// <param name="mime">Mime type of the summary document to be added.</param>
/// <param name="xml">Summary document.</param>
/// <returns>Returns the current document instance.</returns>
public XAtomEntry AddSummary(MimeType mime, XDoc xml) {
AddText("summary", mime, xml);
return this;
}
}
}
| |
// 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 Test.Utilities;
using Xunit;
namespace Desktop.Analyzers.UnitTests
{
public partial class DoNotUseInsecureXSLTScriptExecutionAnalyzerTests : DiagnosticAnalyzerTestBase
{
private readonly string _CA3076LoadInsecureConstructedMessage = DesktopAnalyzersResources.XslCompiledTransformLoadInsecureConstructedMessage;
private DiagnosticResult GetCA3076LoadInsecureConstructedCSharpResultAt(int line, int column, string name)
{
return GetCSharpResultAt(line, column, CA3076RuleId, string.Format(_CA3076LoadInsecureConstructedMessage, name));
}
private DiagnosticResult GetCA3076LoadInsecureConstructedBasicResultAt(int line, int column, string name)
{
return GetBasicResultAt(line, column, CA3076RuleId, string.Format(_CA3076LoadInsecureConstructedMessage, name));
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
var resolver = new XmlUrlResolver();
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadInsecureConstructedCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
Dim resolver = New XmlUrlResolver()
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadInsecureConstructedBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsAndNullResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
xslCompiledTransform.Load(""testStylesheet"", settings, null);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings)
Dim xslCompiledTransform As New XslCompiledTransform()
xslCompiledTransform.Load("""", settings, Nothing)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructDefaultAndNonSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.Default;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.[Default]
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsReconstructTrustedXsltAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings = XsltSettings.TrustedXslt;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings = XsltSettings.TrustedXslt
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToFalseAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInTryBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInCatchBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverInFinallyBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndSecureResolverAsyncAwaitShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlSecureResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlSecureResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}",
GetCA3076LoadCSharpResultAt(13, 13, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(10, 13, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInTryBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(11, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}",
GetCA3076LoadCSharpResultAt(15, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally {
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "TestMethod")
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(14, 17, "TestMethod")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetOneToTrueAndNonSecureResolverAsyncAwaitShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private async Task TestMethod(XsltSettings settings, XmlResolver resolver)
{
await Task.Run(() =>
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableScript = true;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
});
}
private async void TestMethod2()
{
await TestMethod(null, null);
}
}
}",
GetCA3076LoadCSharpResultAt(16, 17, "Run")
);
VerifyBasic(@"
Imports System.Threading.Tasks
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Async Function TestMethod(settings As XsltSettings, resolver As XmlResolver) As Task
Await Task.Run(Function()
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableScript = True
xslCompiledTransform.Load("""", settings, resolver)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod(Nothing, Nothing)
End Sub
End Class
End Namespace",
GetCA3076LoadBasicResultAt(12, 13, "Run")
);
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInTryBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
catch { throw; }
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Catch
Throw
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInCatchBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
finally { }
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
Finally
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverInFinallyBlockShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XsltSettings settings, XmlResolver resolver)
{
try { }
catch { throw; }
finally
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(settings As XsltSettings, resolver As XmlResolver)
Try
Catch
Throw
Finally
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Try
End Sub
End Class
End Namespace");
}
[Fact]
public void UseXslCompiledTransformLoadInputSettingsSetBothToFalseAndNonSecureResolverAsyncAwaitShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Xsl;
namespace TestNamespace
{
class TestClass
{
private async Task TestMethod(XsltSettings settings, XmlResolver resolver)
{
await Task.Run(() =>
{
XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
settings.EnableDocumentFunction = false;
settings.EnableScript = false;
xslCompiledTransform.Load(""testStylesheet"", settings, resolver);
});
}
private async void TestMethod2()
{
await TestMethod(null, null);
}
}
}"
);
VerifyBasic(@"
Imports System.Threading.Tasks
Imports System.Xml
Imports System.Xml.Xsl
Namespace TestNamespace
Class TestClass
Private Async Function TestMethod(settings As XsltSettings, resolver As XmlResolver) As Task
Await Task.Run(Function()
Dim xslCompiledTransform As New XslCompiledTransform()
settings.EnableDocumentFunction = False
settings.EnableScript = False
xslCompiledTransform.Load("""", settings, resolver)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod(Nothing, Nothing)
End Sub
End Class
End Namespace");
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
namespace RefactoringEssentials.CSharp.Diagnostics
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
[NotPortedYet]
public class ParameterCanBeDeclaredWithBaseTypeAnalyzer : DiagnosticAnalyzer
{
//bool tryResolve;
public ParameterCanBeDeclaredWithBaseTypeAnalyzer() : this(true)
{
}
public ParameterCanBeDeclaredWithBaseTypeAnalyzer(bool tryResolve)
{
//this.tryResolve = tryResolve;
}
static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
CSharpDiagnosticIDs.ParameterCanBeDeclaredWithBaseTypeAnalyzerID,
GettextCatalog.GetString("Finds parameters that can be demoted to a base class"),
GettextCatalog.GetString("Parameter can be declared with base type"),
DiagnosticAnalyzerCategories.RedundanciesInCode,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ParameterCanBeDeclaredWithBaseTypeAnalyzerID)
);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
//context.RegisterSyntaxNodeAction(
// (nodeContext) => {
// Diagnostic diagnostic;
// if (TryGetDiagnostic (nodeContext, out diagnostic)) {
// nodeContext.ReportDiagnostic(diagnostic);
// }
// },
// new SyntaxKind[] { SyntaxKind.None }
//);
}
static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
{
diagnostic = default(Diagnostic);
//var node = nodeContext.Node as ;
//diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
//return true;
return false;
}
// class GatherVisitor : GatherVisitorBase<ParameterCanBeDeclaredWithBaseTypeAnalyzer>
// {
// //bool tryResolve;
// public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
// : base (semanticModel, addDiagnostic, cancellationToken)
// {
// }
//// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
//// {
//// methodDeclaration.Attributes.AcceptVisitor(this);
//// if (HasEntryPointSignature(methodDeclaration) || methodDeclaration.HasModifier(Modifiers.Public) || methodDeclaration.HasModifier(Modifiers.Protected))
//// return;
//// var eligibleParameters = methodDeclaration.Parameters
//// .Where(p => p.ParameterModifier != ParameterModifier.Out && p.ParameterModifier != ParameterModifier.Ref)
//// .ToList();
//// if (eligibleParameters.Count == 0)
//// return;
//// var declarationResolveResult = ctx.Resolve(methodDeclaration) as MemberResolveResult;
//// if (declarationResolveResult == null)
//// return;
//// var member = declarationResolveResult.Member;
//// if (member.IsOverride || member.IsOverridable || member.ImplementedInterfaceMembers.Any())
//// return;
////
//// var collector = new TypeCriteriaCollector(ctx);
//// methodDeclaration.AcceptVisitor(collector);
////
//// foreach (var parameter in eligibleParameters) {
//// ProcessParameter(parameter, methodDeclaration.Body, collector);
//// }
//// }
////
//// bool HasEntryPointSignature(MethodDeclaration methodDeclaration)
//// {
//// if (!methodDeclaration.Modifiers.HasFlag(Modifiers.Static))
//// return false;
//// var returnType = ctx.Resolve(methodDeclaration.ReturnType).Type;
//// if (!returnType.IsKnownType(KnownTypeCode.Int32) && !returnType.IsKnownType(KnownTypeCode.Void))
//// return false;
//// var parameterCount = methodDeclaration.Parameters.Count;
//// if (parameterCount == 0)
//// return true;
//// if (parameterCount != 1)
//// return false;
//// var parameterType = ctx.Resolve(methodDeclaration.Parameters.First()).Type as ArrayType;
//// if (parameterType == null || !parameterType.ElementType.IsKnownType(KnownTypeCode.String))
//// return false;
//// return true;
//// }
////
//// bool FilterOut(IType current, IType newType)
//// {
//// // Filter out some strange framework types like _Exception
//// return newType.Namespace.StartsWith("System.", StringComparison.Ordinal) &&
//// newType.Name.StartsWith("_", StringComparison.Ordinal) ? true : false;
//// }
////
//// void ProcessParameter(ParameterDeclaration parameter, AstNode rootResolutionNode, TypeCriteriaCollector collector)
//// {
//// var localResolveResult = ctx.Resolve(parameter) as LocalResolveResult;
//// if (localResolveResult == null)
//// return;
//// var variable = localResolveResult.Variable;
//// var typeKind = variable.Type.Kind;
//// if (!(typeKind == TypeKind.Class ||
//// typeKind == TypeKind.Struct ||
//// typeKind == TypeKind.Interface ||
//// typeKind == TypeKind.Array) ||
//// parameter.Type is PrimitiveType ||
//// !collector.UsedVariables.Contains(variable)) {
//// return;
//// }
////
//// var candidateTypes = localResolveResult.Type.GetAllBaseTypes().ToList();
//// TypesChecked += candidateTypes.Count;
//// var criterion = collector.GetCriterion(variable);
////
//// var possibleTypes =
//// (from type in candidateTypes
//// where !type.Equals(localResolveResult.Type) && criterion.SatisfiedBy(type)
//// select type).ToList();
////
//// TypeResolveCount += possibleTypes.Count;
//// var validTypes =
//// (from type in possibleTypes
//// where (!tryResolve || TypeChangeResolvesCorrectly(ctx, parameter, rootResolutionNode, type)) && !FilterOut (variable.Type, type)
//// select type).ToList();
//// if (validTypes.Any()) {
// // AddDiagnosticAnalyzer(new CodeIssue(parameter.Type, ctx.TranslateString("Parameter can be declared with base type"), GetActions(parameter, validTypes)) {
//// IssueMarker = IssueMarker.DottedLine
//// });
//// MembersWithIssues++;
//// }
//// }
////
//// internal int TypeResolveCount = 0;
//// internal int TypesChecked = 0;
//// internal int MembersWithIssues = 0;
//// internal int MethodResolveCount = 0;
////
//// IEnumerable<CodeAction> GetActions(ParameterDeclaration parameter, IEnumerable<IType> possibleTypes)
//// {
//// var csResolver = ctx.Resolver.GetResolverStateBefore(parameter);
//// var astBuilder = new TypeSystemAstBuilder(csResolver);
//// foreach (var type in possibleTypes) {
//// var localType = type;
//// var message = String.Format(ctx.TranslateString("Demote parameter to '{0}'"), type.FullName);
//// yield return new CodeAction(message, script => {
//// script.Replace(parameter.Type, astBuilder.ConvertType(localType));
//// }, parameter.Type);
//// }
//// }
//// }
////
//// public static bool TypeChangeResolvesCorrectly(BaseSemanticModel ctx, ParameterDeclaration parameter, AstNode rootNode, IType type)
//// {
//// var resolver = ctx.GetResolverStateBefore(rootNode);
//// resolver = resolver.AddVariable(new DefaultParameter(type, parameter.Name));
//// var astResolver = new CSharpAstResolver(resolver, rootNode, ctx.UnresolvedFile);
//// var validator = new TypeChangeValidationNavigator();
//// astResolver.ApplyNavigator(validator, ctx.CancellationToken);
//// return !validator.FoundErrors;
//// }
////
//// class TypeChangeValidationNavigator : IResolveVisitorNavigator
//// {
//// public bool FoundErrors { get; private set; }
////
//// #region IResolveVisitorNavigator implementation
//// public ResolveVisitorNavigationMode Scan(AstNode node)
//// {
//// if (FoundErrors)
//// return ResolveVisitorNavigationMode.Skip;
//// return ResolveVisitorNavigationMode.Resolve;
//// }
////
//// public void Resolved(AstNode node, ResolveResult result)
//// {
////// bool errors = result.IsError;
//// FoundErrors |= result.IsError;
//// }
////
//// public void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
//// {
//// // no-op
//// }
//// #endregion
////
//// }
// }
//
// public interface ITypeCriterion
// {
// /// <summary>
// /// Checks if the given type satisfies the critrion.
// /// </summary>
// /// <returns>
// /// <c>true</c>, if the type satisfies the criterion, <c>false</c> otherwise.
// /// </returns>
// /// <param name='type'>
// /// The type to check.
// /// </param>
// bool SatisfiedBy(IType type);
// }
//
// public class SupportsIndexingCriterion : ITypeCriterion
// {
// IType returnType;
//
// IList<IType> argumentTypes;
//
// CSharpConversions conversions;
//
// bool isWriteAccess;
//
// public SupportsIndexingCriterion(IType returnType, IEnumerable<IType> argumentTypes, CSharpConversions conversions, bool isWriteAccess = false)
// {
// if (returnType == null)
// throw new ArgumentNullException("returnType");
// if (argumentTypes == null)
// throw new ArgumentNullException("argumentTypes");
// if (conversions == null)
// throw new ArgumentNullException("conversions");
//
// this.returnType = returnType;
// this.argumentTypes = argumentTypes.ToList();
// this.conversions = conversions;
// this.isWriteAccess = isWriteAccess;
// }
//
// #region ITypeCriterion implementation
//
// public bool SatisfiedBy(IType type)
// {
// var accessors = type.GetAccessors().ToList();
// return accessors.Any(member => {
// var parameterizedMember = member as IParameterizedMember;
// if (parameterizedMember == null)
// return false;
//
// if (isWriteAccess) {
// var parameterCount = member.Parameters.Count;
// if (member.Name != "set_Item" || parameterCount < 2)
// return false;
// var indexerElementType = parameterizedMember.Parameters.Last().Type;
// var indexerParameterTypes = parameterizedMember.Parameters.Take(parameterCount - 1).Select(p => p.Type).ToList();
// return IsSignatureMatch(indexerElementType, indexerParameterTypes);
// } else {
// if (member.Name != "get_Item" || member.Parameters.Count < 1)
// return false;
// var indexerElementType = parameterizedMember.ReturnType;
// var indexerParameterTypes = parameterizedMember.Parameters.Select(p => p.Type).ToList();
// return IsSignatureMatch(indexerElementType, indexerParameterTypes);
// }
// });
// }
//
// #endregion
//
// bool IsSignatureMatch(IType indexerElementType, IList<IType> indexerParameterTypes)
// {
// indexerElementType.GetAllBaseTypes();
// if (indexerParameterTypes.Count != argumentTypes.Count)
// return false;
// var returnConversion = conversions.ImplicitConversion(indexerElementType, returnType);
// if (!returnConversion.IsValid)
// return false;
// for (int i = 0; i < argumentTypes.Count; i++) {
// var conversion = conversions.ImplicitConversion(indexerParameterTypes[i], argumentTypes[i]);
// if (!conversion.IsValid)
// return false;
// }
// return true;
// }
// }
//
// public class TypeCriteriaCollector : DepthFirstAstVisitor
// {
// BaseSemanticModel context;
//
// public TypeCriteriaCollector(BaseSemanticModel context)
// {
// this.context = context;
// TypeCriteria = new Dictionary<IVariable, IList<ITypeCriterion>>();
// UsedVariables = new HashSet<IVariable>();
// }
//
// IDictionary<IVariable, IList<ITypeCriterion>> TypeCriteria { get; set; }
//
// public HashSet<IVariable> UsedVariables { get; private set; }
//
// public ITypeCriterion GetCriterion(IVariable variable)
// {
// if (!TypeCriteria.ContainsKey(variable))
// return new ConjunctionCriteria(new List<ITypeCriterion>());
// return new ConjunctionCriteria(TypeCriteria[variable]);
// }
//
// void AddCriterion(IVariable variable, ITypeCriterion criterion)
// {
// if (!TypeCriteria.ContainsKey(variable))
// TypeCriteria[variable] = new List<ITypeCriterion>();
// TypeCriteria[variable].Add(criterion);
// }
//
// public override void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
// {
// base.VisitMemberReferenceExpression(memberReferenceExpression);
//
// var targetResolveResult = context.Resolve(memberReferenceExpression.Target) as LocalResolveResult;
// if (targetResolveResult == null)
// return;
// var variable = targetResolveResult.Variable;
// var conversion = context.GetConversion(memberReferenceExpression);
// if (conversion.IsMethodGroupConversion) {
// AddCriterion(variable, new HasMemberCriterion(conversion.Method));
// } else {
// var resolveResult = context.Resolve(memberReferenceExpression);
// var memberResolveResult = resolveResult as MemberResolveResult;
// if (memberResolveResult != null)
// AddCriterion(variable, new HasMemberCriterion(memberResolveResult.Member));
// }
// }
//
// public override void VisitIndexerExpression(IndexerExpression indexerExpression)
// {
// base.VisitIndexerExpression(indexerExpression);
//
// var localResolveResult = context.Resolve(indexerExpression.Target) as LocalResolveResult;
// if (localResolveResult == null)
// return;
// var resolveResult = context.Resolve(indexerExpression);
// if (resolveResult == null)
// return;
// var parent = indexerExpression.Parent;
// while (parent is ParenthesizedExpression)
// parent = parent.Parent;
// if (parent is DirectionExpression) {
// // The only types which are indexable and where the indexing expression
// // results in a variable is an actual array type
// AddCriterion(localResolveResult.Variable, new IsArrayTypeCriterion());
// } else if (resolveResult is ArrayAccessResolveResult) {
// var arrayResolveResult = (ArrayAccessResolveResult)resolveResult;
// var arrayType = arrayResolveResult.Array.Type as ArrayType;
// if (arrayType != null) {
// var parameterTypes = arrayResolveResult.Indexes.Select(index => index.Type);
// var criterion = new SupportsIndexingCriterion(arrayType.ElementType, parameterTypes, CSharpConversions.Get(context.Compilation));
// AddCriterion(localResolveResult.Variable, criterion);
// }
// } else if (resolveResult is CSharpInvocationResolveResult) {
// var invocationResolveResult = (CSharpInvocationResolveResult)resolveResult;
// var parameterTypes = invocationResolveResult.Arguments.Select(arg => arg.Type);
// var criterion = new SupportsIndexingCriterion(invocationResolveResult.Member.ReturnType, parameterTypes, CSharpConversions.Get(context.Compilation));
// AddCriterion(localResolveResult.Variable, criterion);
// }
// }
//
// public override void VisitInvocationExpression(InvocationExpression invocationExpression)
// {
// base.VisitInvocationExpression(invocationExpression);
//
// var resolveResult = context.Resolve(invocationExpression);
// var invocationResolveResult = resolveResult as InvocationResolveResult;
// if (invocationResolveResult == null)
// return;
//
// // invocationExpression.Target resolves to a method group and VisitMemberReferenceExpression
// // only handles members, so handle method groups here
// var targetResolveResult = invocationResolveResult.TargetResult as LocalResolveResult;
// if (targetResolveResult != null) {
// var variable = targetResolveResult.Variable;
// AddCriterion(variable, new HasMemberCriterion(invocationResolveResult.Member));
// }
// }
//
// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
// {
// base.VisitMethodDeclaration(methodDeclaration);
//
// var lastParameter = methodDeclaration.Parameters.LastOrNullObject();
// if (lastParameter.IsNull || !lastParameter.ParameterModifier.HasFlag(ParameterModifier.Params))
// return;
// var localResolveResult = context.Resolve(lastParameter) as LocalResolveResult;
// if (localResolveResult == null)
// return;
// AddCriterion(localResolveResult.Variable, new IsArrayTypeCriterion());
// }
//
// Role[] roles = new [] {
// Roles.Expression,
// Roles.Argument,
// Roles.Condition,
// BinaryOperatorExpression.RightRole,
// BinaryOperatorExpression.LeftRole
// };
//
// public override void VisitIdentifierExpression(IdentifierExpression identifierExpression)
// {
// var resolveResult = context.Resolve(identifierExpression);
// var localResolveResult = resolveResult as LocalResolveResult;
// if (localResolveResult == null)
// return;
//
// var variable = localResolveResult.Variable;
// if (!UsedVariables.Contains(variable))
// UsedVariables.Add(variable);
//
// // Assignment expressions are checked separately, see VisitAssignmentExpression
// if (!roles.Contains(identifierExpression.Role) || identifierExpression.Parent is AssignmentExpression)
// return;
//
// CheckForCriterion(identifierExpression, variable);
// }
//
// public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
// {
// base.VisitAssignmentExpression(assignmentExpression);
//
// // Only check the right side; The left side always has the type of
// // the variable, which is not what we want to check
//
// var rightResolveResult = context.Resolve(assignmentExpression.Right) as LocalResolveResult;
// if (rightResolveResult != null) {
// CheckForCriterion(assignmentExpression.Right, rightResolveResult.Variable);
// }
// }
//
// void CheckForCriterion(Expression expression, IVariable variable)
// {
// AddCriterion(variable, new IsTypeCriterion(context.GetExpectedType(expression)));
// }
//
// class ConjunctionCriteria : ITypeCriterion
// {
// IList<ITypeCriterion> criteria;
//
// public ConjunctionCriteria(IList<ITypeCriterion> criteria)
// {
// this.criteria = criteria;
// }
//
// public bool SatisfiedBy(IType type)
// {
// foreach (var criterion in criteria) {
// if (!criterion.SatisfiedBy(type)) {
// return false;
// }
// }
// return true;
// }
// }
}
// public class IsTypeCriterion : ITypeCriterion
// {
// IType isType;
//
// public IsTypeCriterion(IType isType)
// {
// this.isType = isType;
// }
//
// #region ITypeCriterion implementation
// public bool SatisfiedBy (IType type)
// {
// return isType == type ||
// type.GetAllBaseTypes().Any(t => t == isType);
// }
// #endregion
// }
//
// public class IsArrayTypeCriterion : ITypeCriterion
// {
// #region ITypeCriterion implementation
//
// public bool SatisfiedBy(IType type)
// {
// return type is ArrayType;
// }
//
// #endregion
// }
//
// public class HasMemberCriterion : ITypeCriterion
// {
//// IMember neededMember;
// IList<IMember> acceptableMembers;
//
// public HasMemberCriterion(IMember neededMember)
// {
//// this.neededMember = neededMember;
//
// if (neededMember.ImplementedInterfaceMembers.Any()) {
// acceptableMembers = neededMember.ImplementedInterfaceMembers.ToList();
// } else if (neededMember.IsOverride) {
// acceptableMembers = new List<IMember>();
// foreach (var member in InheritanceHelper.GetBaseMembers(neededMember, true)) {
// acceptableMembers.Add(member);
// if (member.IsShadowing)
// break;
// }
// acceptableMembers.Add(neededMember);
// } else {
// acceptableMembers = new List<IMember> { neededMember };
// }
// }
//
// #region ITypeCriterion implementation
// public bool SatisfiedBy (IType type)
// {
// if (type == null)
// throw new ArgumentNullException("type");
//
// var typeMembers = type.GetMembers();
// return typeMembers.Any(member => HasCommonMemberDeclaration(acceptableMembers, member));
// }
// #endregion
//
// static bool HasCommonMemberDeclaration(IEnumerable<IMember> acceptableMembers, IMember member)
// {
// var implementedInterfaceMembers = member.MemberDefinition.ImplementedInterfaceMembers;
// if (implementedInterfaceMembers.Any()) {
// return ContainsAny(acceptableMembers, implementedInterfaceMembers);
// } else {
// return acceptableMembers.Contains(member/* .MemberDefinition*/);
// }
// }
//
// static bool ContainsAny<T>(IEnumerable<T> collection, IEnumerable<T> items)
// {
// foreach (var item in items) {
// if (collection.Contains(item))
// return true;
// }
// return false;
// }
// }
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Modules;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Metadata.Models;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.Records;
using Orchard.Contents;
using Orchard.Core.XmlRpc;
using Orchard.Core.XmlRpc.Models;
using Orchard.Lists.Indexes;
using Orchard.Lists.Models;
using Orchard.MetaWeblog;
using Orchard.Security.Permissions;
using Orchard.Security.Services;
using YesSql;
namespace Orchard.Lists.RemotePublishing
{
[Feature("Orchard.RemotePublishing")]
public class MetaWeblogHandler : IXmlRpcHandler
{
private readonly IContentManager _contentManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly IAuthorizationService _authorizationService;
private readonly HtmlEncoder _htmlEncoder;
private readonly IMembershipService _membershipService;
private readonly IEnumerable<IMetaWeblogDriver> _metaWeblogDrivers;
private readonly ISession _session;
public MetaWeblogHandler(IContentManager contentManager,
IAuthorizationService authorizationService,
IMembershipService membershipService,
ISession session,
HtmlEncoder htmlEncoder,
IContentDefinitionManager contentDefinitionManager,
IEnumerable<IMetaWeblogDriver> metaWeblogDrivers,
ILogger<MetaWeblogHandler> logger,
IStringLocalizer<MetaWeblogHandler> localizer)
{
_contentManager = contentManager;
_contentDefinitionManager = contentDefinitionManager;
_authorizationService = authorizationService;
_metaWeblogDrivers = metaWeblogDrivers;
_session = session;
_htmlEncoder = htmlEncoder;
_membershipService = membershipService;
Logger = logger;
T = localizer;
}
ILogger Logger { get; }
IStringLocalizer T { get; }
public void SetCapabilities(XElement options)
{
const string manifestUri = "http://schemas.microsoft.com/wlw/manifest/weblog";
foreach (var driver in _metaWeblogDrivers)
{
driver.SetCapabilities((name, value) => { options.SetElementValue(XName.Get(name, manifestUri), value); });
}
}
public async Task ProcessAsync(XmlRpcContext context)
{
if (context.RpcMethodCall.MethodName == "blogger.getUsersBlogs")
{
var result = await MetaWeblogGetUserBlogsAsync(context,
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value));
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.getRecentPosts")
{
var result = await MetaWeblogGetRecentPosts(
context,
Convert.ToString(context.RpcMethodCall.Params[0].Value),
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
Convert.ToInt32(context.RpcMethodCall.Params[3].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.newPost")
{
var result = await MetaWeblogNewPostAsync(
Convert.ToString(context.RpcMethodCall.Params[0].Value),
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
(XRpcStruct)context.RpcMethodCall.Params[3].Value,
Convert.ToBoolean(context.RpcMethodCall.Params[4].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.getPost")
{
var result = await MetaWeblogGetPostAsync(
context,
Convert.ToString(context.RpcMethodCall.Params[0].Value),
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "metaWeblog.editPost")
{
var result = await MetaWeblogEditPostAsync(
Convert.ToString(context.RpcMethodCall.Params[0].Value),
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
(XRpcStruct)context.RpcMethodCall.Params[3].Value,
Convert.ToBoolean(context.RpcMethodCall.Params[4].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
if (context.RpcMethodCall.MethodName == "blogger.deletePost")
{
var result = await MetaWeblogDeletePostAsync(
Convert.ToString(context.RpcMethodCall.Params[1].Value),
Convert.ToString(context.RpcMethodCall.Params[2].Value),
Convert.ToString(context.RpcMethodCall.Params[3].Value),
context.Drivers);
context.RpcMethodResponse = new XRpcMethodResponse().Add(result);
}
}
private async Task<XRpcArray> MetaWeblogGetUserBlogsAsync(XmlRpcContext context, string userName, string password)
{
var user = await ValidateUserAsync(userName, password);
XRpcArray array = new XRpcArray();
// Look for all types using ListPart
foreach(var type in _contentDefinitionManager.ListTypeDefinitions())
{
if (!type.Parts.Any(x => x.Name == nameof(ListPart)))
{
continue;
}
foreach (var list in await _session.Query<ContentItem, ContentItemIndex>(x => x.ContentType == type.Name).ListAsync())
{
// User needs to at least have permission to edit its own blog posts to access the service
if (await _authorizationService.AuthorizeAsync(user, Permissions.EditContent, list))
{
var metadata = _contentManager.PopulateAspect<ContentItemMetadata>(list);
var displayRouteValues = metadata.DisplayRouteValues;
array.Add(new XRpcStruct()
.Set("url", context.Url.Action(displayRouteValues["action"].ToString(), displayRouteValues["controller"].ToString(), displayRouteValues, context.HttpContext.Request.Scheme))
.Set("blogid", list.ContentItemId)
.Set("blogName", metadata.DisplayText));
}
}
}
return array;
}
private async Task<XRpcArray> MetaWeblogGetRecentPosts(
XmlRpcContext context,
string contentItemId,
string userName,
string password,
int numberOfPosts,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
// User needs to at least have permission to edit its own blog posts to access the service
await CheckAccessAsync(Permissions.EditContent, user, null);
var list = await _contentManager.GetAsync(contentItemId);
if (list == null)
{
throw new InvalidOperationException("Could not find content item " + contentItemId);
}
var array = new XRpcArray();
var contentItems = await _session.Query<ContentItem>()
.With<ContainedPartIndex>(x => x.ListContentItemId == contentItemId)
.With<ContentItemIndex>(x => x.Latest)
.OrderByDescending(x => x.CreatedUtc)
.Take(numberOfPosts)
.ListAsync();
foreach (var contentItem in contentItems)
{
var postStruct = CreateBlogStruct(context, contentItem);
foreach (var driver in drivers)
{
driver.Process(postStruct);
}
array.Add(postStruct);
}
return array;
}
private async Task<string> MetaWeblogNewPostAsync(
string contentItemId,
string userName,
string password,
XRpcStruct content,
bool publish,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
// User needs permission to edit or publish its own blog posts
await CheckAccessAsync(publish ? Permissions.PublishContent: Permissions.EditContent, user, null);
var list = await _contentManager.GetAsync(contentItemId);
if (list == null)
{
throw new InvalidOperationException("Could not find content item " + contentItemId);
}
var postType = GetContainedContentTypes(list).FirstOrDefault();
var contentItem = _contentManager.New(postType.Name);
contentItem.Owner = userName;
contentItem.Alter<ContainedPart>(x => x.ListContentItemId = list.ContentItemId);
foreach (var driver in _metaWeblogDrivers)
{
driver.EditPost(content, contentItem);
}
_contentManager.Create(contentItem, VersionOptions.Draft);
// try to get the UTC timezone by default
var publishedUtc = content.Optional<DateTime?>("date_created_gmt");
if (publishedUtc == null)
{
// take the local one
publishedUtc = content.Optional<DateTime?>("dateCreated");
}
else
{
// ensure it's read as a UTC time
publishedUtc = new DateTime(publishedUtc.Value.Ticks, DateTimeKind.Utc);
}
if (publish && (publishedUtc == null || publishedUtc <= DateTime.UtcNow))
{
await _contentManager.PublishAsync(contentItem);
}
if (publishedUtc != null)
{
contentItem.CreatedUtc = publishedUtc;
}
foreach (var driver in drivers)
{
driver.Process(contentItem.ContentItemId);
}
return contentItem.ContentItemId;
}
private async Task<XRpcStruct> MetaWeblogGetPostAsync(
XmlRpcContext context,
string contentItemId,
string userName,
string password,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null)
{
throw new ArgumentException();
}
await CheckAccessAsync(Permissions.EditContent, user, contentItem);
var postStruct = CreateBlogStruct(context, contentItem);
foreach(var driver in _metaWeblogDrivers)
{
driver.BuildPost(postStruct, context, contentItem);
}
foreach (var driver in drivers)
{
driver.Process(postStruct);
}
return postStruct;
}
private async Task<bool> MetaWeblogEditPostAsync(
string contentItemId,
string userName,
string password,
XRpcStruct content,
bool publish,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.DraftRequired);
if (contentItem == null)
{
throw new Exception(T["The specified Blog Post doesn't exist anymore. Please create a new Blog Post."]);
}
await CheckAccessAsync(publish ? Permissions.PublishContent: Permissions.EditContent, user, contentItem);
foreach (var driver in _metaWeblogDrivers)
{
driver.EditPost(content, contentItem);
}
// try to get the UTC timezone by default
var publishedUtc = content.Optional<DateTime?>("date_created_gmt");
if (publishedUtc == null)
{
// take the local one
publishedUtc = content.Optional<DateTime?>("dateCreated");
}
else
{
// ensure it's read as a UTC time
publishedUtc = new DateTime(publishedUtc.Value.Ticks, DateTimeKind.Utc);
}
if (publish && (publishedUtc == null || publishedUtc <= DateTime.UtcNow))
{
await _contentManager.PublishAsync(contentItem);
}
if (publishedUtc != null)
{
contentItem.CreatedUtc = publishedUtc;
}
foreach (var driver in drivers)
{
driver.Process(contentItem.Id);
}
return true;
}
private async Task<bool> MetaWeblogDeletePostAsync(
string contentItemId,
string userName,
string password,
IEnumerable<IXmlRpcDriver> drivers)
{
var user = await ValidateUserAsync(userName, password);
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null)
{
throw new ArgumentException();
}
if (!await _authorizationService.AuthorizeAsync(user, Permissions.DeleteContent, contentItem))
{
throw new InvalidOperationException(T["Not authorized to delete this content"].Value);
}
foreach (var driver in drivers)
{
driver.Process(contentItem.ContentItemId);
}
await _contentManager.RemoveAsync(contentItem);
return true;
}
private async Task<ClaimsPrincipal> ValidateUserAsync(string userName, string password)
{
if(!await _membershipService.CheckPasswordAsync(userName, password))
{
throw new InvalidOperationException(T["The username or e-mail or password provided is incorrect."].Value);
}
var storeUser = await _membershipService.GetUserAsync(userName);
if (storeUser == null)
{
return null;
}
return await _membershipService.CreateClaimsPrincipal(storeUser);
}
private XRpcStruct CreateBlogStruct(XmlRpcContext context, ContentItem contentItem)
{
var metadata = _contentManager.PopulateAspect<ContentItemMetadata>(contentItem);
var url = context.Url.Action(
metadata.DisplayRouteValues["action"].ToString(),
metadata.DisplayRouteValues["controller"].ToString(),
metadata.DisplayRouteValues,
context.HttpContext.Request.Scheme);
if (contentItem.HasDraft())
{
url = context.Url.Action("Preview", "Item", new { area = "Orchard.Contents", contentItemId = contentItem.ContentItemId });
}
var blogStruct = new XRpcStruct()
.Set("postid", contentItem.ContentItemId)
.Set("link", url)
.Set("permaLink", url);
if (contentItem.PublishedUtc != null)
{
blogStruct.Set("dateCreated", contentItem.PublishedUtc);
blogStruct.Set("date_created_gmt", contentItem.PublishedUtc);
}
foreach(var driver in _metaWeblogDrivers)
{
driver.BuildPost(blogStruct, context, contentItem);
}
return blogStruct;
}
private async Task CheckAccessAsync(Permission permission, ClaimsPrincipal user, ContentItem contentItem)
{
if (!await _authorizationService.AuthorizeAsync(user, permission, contentItem))
{
throw new InvalidOperationException(T["Not authorized to delete this content"].Value);
}
}
private IEnumerable<ContentTypeDefinition> GetContainedContentTypes(ContentItem contentItem)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "ListPart", StringComparison.Ordinal));
var settings = contentTypePartDefinition.Settings.ToObject<ListPartSettings>();
var contentTypes = settings.ContainedContentTypes ?? Enumerable.Empty<string>();
return contentTypes.Select(contentType => _contentDefinitionManager.GetTypeDefinition(contentType));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.ModelsBuilder;
using Umbraco.ModelsBuilder.Umbraco;
[assembly: PureLiveAssembly]
[assembly:ModelsBuilderAssembly(PureLive = true, SourceHash = "b87568283eac4ed9")]
[assembly:System.Reflection.AssemblyVersion("0.0.0.1")]
// FILE: models.generated.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Umbraco.ModelsBuilder v3.0.7.99
//
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Umbraco.Web.PublishedContentModels
{
// Mixin content Type 1091 with alias "contentBase"
/// <summary>Content Base</summary>
public partial interface IContentBase : IPublishedContent
{
/// <summary>Content</summary>
Newtonsoft.Json.Linq.JToken BodyText { get; }
/// <summary>Page Title</summary>
string PageTitle { get; }
}
/// <summary>Content Base</summary>
[PublishedContentModel("contentBase")]
public partial class ContentBase : PublishedContentModel, IContentBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "contentBase";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public ContentBase(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<ContentBase, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Content
///</summary>
[ImplementPropertyType("bodyText")]
public Newtonsoft.Json.Linq.JToken BodyText
{
get { return GetBodyText(this); }
}
/// <summary>Static getter for Content</summary>
public static Newtonsoft.Json.Linq.JToken GetBodyText(IContentBase that) { return that.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("bodyText"); }
///<summary>
/// Page Title: The title of the page, this is also the first text in a google search result. The ideal length is between 40 and 60 characters
///</summary>
[ImplementPropertyType("pageTitle")]
public string PageTitle
{
get { return GetPageTitle(this); }
}
/// <summary>Static getter for Page Title</summary>
public static string GetPageTitle(IContentBase that) { return that.GetPropertyValue<string>("pageTitle"); }
}
/// <summary>Feature</summary>
[PublishedContentModel("feature")]
public partial class Feature : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "feature";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Feature(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Feature, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Details
///</summary>
[ImplementPropertyType("featureDetails")]
public string FeatureDetails
{
get { return this.GetPropertyValue<string>("featureDetails"); }
}
///<summary>
/// Name
///</summary>
[ImplementPropertyType("featureName")]
public string FeatureName
{
get { return this.GetPropertyValue<string>("featureName"); }
}
}
/// <summary>Home</summary>
[PublishedContentModel("home")]
public partial class Home : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "home";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Home(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Home, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Content
///</summary>
[ImplementPropertyType("bodyText")]
public Newtonsoft.Json.Linq.JToken BodyText
{
get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("bodyText"); }
}
///<summary>
/// Color Theme: This will be a custom property editor later
///</summary>
[ImplementPropertyType("colorTheme")]
public int ColorTheme
{
get { return this.GetPropertyValue<int>("colorTheme"); }
}
///<summary>
/// Font: This will be a custom property editor later
///</summary>
[ImplementPropertyType("font")]
public int Font
{
get { return this.GetPropertyValue<int>("font"); }
}
///<summary>
/// Address
///</summary>
[ImplementPropertyType("footerAddress")]
public string FooterAddress
{
get { return this.GetPropertyValue<string>("footerAddress"); }
}
///<summary>
/// Call To Action Caption: Caption on the Call To Action Button
///</summary>
[ImplementPropertyType("footerCTACaption")]
public string FooterCtacaption
{
get { return this.GetPropertyValue<string>("footerCTACaption"); }
}
///<summary>
/// Call To Action Link
///</summary>
[ImplementPropertyType("FooterCtalink")]
public IPublishedContent FooterCtalink
{
get { return this.GetPropertyValue<IPublishedContent>("FooterCtalink"); }
}
///<summary>
/// Description
///</summary>
[ImplementPropertyType("footerDescription")]
public string FooterDescription
{
get { return this.GetPropertyValue<string>("footerDescription"); }
}
///<summary>
/// Header
///</summary>
[ImplementPropertyType("footerHeader")]
public string FooterHeader
{
get { return this.GetPropertyValue<string>("footerHeader"); }
}
///<summary>
/// Hero Background: Spice up the homepage by adding a beautiful photo that relates to your business
///</summary>
[ImplementPropertyType("HeroBackgroundImage")]
public IPublishedContent HeroBackgroundImage
{
get { return this.GetPropertyValue<IPublishedContent>("HeroBackgroundImage"); }
}
///<summary>
/// Call To Action Caption: The caption on the button
///</summary>
[ImplementPropertyType("heroCTACaption")]
public string HeroCtacaption
{
get { return this.GetPropertyValue<string>("heroCTACaption"); }
}
///<summary>
/// Call To Action Link
///</summary>
[ImplementPropertyType("HeroCtalink")]
public IPublishedContent HeroCtalink
{
get { return this.GetPropertyValue<IPublishedContent>("HeroCtalink"); }
}
///<summary>
/// Description
///</summary>
[ImplementPropertyType("heroDescription")]
public string HeroDescription
{
get { return this.GetPropertyValue<string>("heroDescription"); }
}
///<summary>
/// Header: This is the main headline for the hero area on the Homepage
///</summary>
[ImplementPropertyType("heroHeader")]
public string HeroHeader
{
get { return this.GetPropertyValue<string>("heroHeader"); }
}
///<summary>
/// Logo: Optional. If you add a logo it'll be used in the upper left corner instead of the site name. Make sure to use a transparent logo for best results
///</summary>
[ImplementPropertyType("SiteLogo")]
public IPublishedContent SiteLogo
{
get { return this.GetPropertyValue<IPublishedContent>("SiteLogo"); }
}
///<summary>
/// Sitename: Used on the homepage as well as the title and social cards
///</summary>
[ImplementPropertyType("sitename")]
public string Sitename
{
get { return this.GetPropertyValue<string>("sitename"); }
}
}
// Mixin content Type 1094 with alias "navigationBase"
/// <summary>Navigation Base</summary>
public partial interface INavigationBase : IPublishedContent
{
/// <summary>Keywords</summary>
IEnumerable<string> Keywords { get; }
/// <summary>Description</summary>
string SeoMetaDescription { get; }
/// <summary>Hide in Navigation</summary>
bool UmbracoNavihide { get; }
}
/// <summary>Navigation Base</summary>
[PublishedContentModel("navigationBase")]
public partial class NavigationBase : PublishedContentModel, INavigationBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "navigationBase";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public NavigationBase(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<NavigationBase, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Keywords: Keywords that describe the content of the page. This is consired optional since most modern search engines don't use this anymore
///</summary>
[ImplementPropertyType("keywords")]
public IEnumerable<string> Keywords
{
get { return GetKeywords(this); }
}
/// <summary>Static getter for Keywords</summary>
public static IEnumerable<string> GetKeywords(INavigationBase that) { return that.GetPropertyValue<IEnumerable<string>>("keywords"); }
///<summary>
/// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters
///</summary>
[ImplementPropertyType("seoMetaDescription")]
public string SeoMetaDescription
{
get { return GetSeoMetaDescription(this); }
}
/// <summary>Static getter for Description</summary>
public static string GetSeoMetaDescription(INavigationBase that) { return that.GetPropertyValue<string>("seoMetaDescription"); }
///<summary>
/// Hide in Navigation: If you don't want this page to appear in the navigation, check this box
///</summary>
[ImplementPropertyType("umbracoNavihide")]
public bool UmbracoNavihide
{
get { return GetUmbracoNavihide(this); }
}
/// <summary>Static getter for Hide in Navigation</summary>
public static bool GetUmbracoNavihide(INavigationBase that) { return that.GetPropertyValue<bool>("umbracoNavihide"); }
}
/// <summary>Blog</summary>
[PublishedContentModel("blog")]
public partial class Blog : PublishedContentModel, IContentBase, INavigationBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "blog";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Blog(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Blog, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Disqus Shortname: To use comments, you'll need to sign up for Disqus and enter your shortname here (more info: https://help.disqus.com/customer/portal/articles/472097-universal-embed-code)
///</summary>
[ImplementPropertyType("disqusShortname")]
public string DisqusShortname
{
get { return this.GetPropertyValue<string>("disqusShortname"); }
}
///<summary>
/// How many posts should be shown?
///</summary>
[ImplementPropertyType("howManyPostsShouldBeShown")]
public decimal HowManyPostsShouldBeShown
{
get { return this.GetPropertyValue<decimal>("howManyPostsShouldBeShown"); }
}
///<summary>
/// Content
///</summary>
[ImplementPropertyType("bodyText")]
public Newtonsoft.Json.Linq.JToken BodyText
{
get { return Umbraco.Web.PublishedContentModels.ContentBase.GetBodyText(this); }
}
///<summary>
/// Page Title: The title of the page, this is also the first text in a google search result. The ideal length is between 40 and 60 characters
///</summary>
[ImplementPropertyType("pageTitle")]
public string PageTitle
{
get { return Umbraco.Web.PublishedContentModels.ContentBase.GetPageTitle(this); }
}
///<summary>
/// Keywords: Keywords that describe the content of the page. This is consired optional since most modern search engines don't use this anymore
///</summary>
[ImplementPropertyType("keywords")]
public IEnumerable<string> Keywords
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetKeywords(this); }
}
///<summary>
/// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters
///</summary>
[ImplementPropertyType("seoMetaDescription")]
public string SeoMetaDescription
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetSeoMetaDescription(this); }
}
///<summary>
/// Hide in Navigation: If you don't want this page to appear in the navigation, check this box
///</summary>
[ImplementPropertyType("umbracoNavihide")]
public bool UmbracoNavihide
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetUmbracoNavihide(this); }
}
}
/// <summary>Blogpost</summary>
[PublishedContentModel("blogpost")]
public partial class Blogpost : PublishedContentModel, INavigationBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "blogpost";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Blogpost(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Blogpost, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Content
///</summary>
[ImplementPropertyType("bodyText")]
public Newtonsoft.Json.Linq.JToken BodyText
{
get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("bodyText"); }
}
///<summary>
/// Categories (tags)
///</summary>
[ImplementPropertyType("categories")]
public IEnumerable<string> Categories
{
get { return this.GetPropertyValue<IEnumerable<string>>("categories"); }
}
///<summary>
/// Excerpt: Introduction to your blog post. This is also used in the summaries on the front of the blog as well as the homepage
///</summary>
[ImplementPropertyType("excerpt")]
public string Excerpt
{
get { return this.GetPropertyValue<string>("excerpt"); }
}
///<summary>
/// Page Title: The title of the page, this is also the first text in a google search result. The ideal length is between 40 and 60 characters
///</summary>
[ImplementPropertyType("pageTitle")]
public string PageTitle
{
get { return this.GetPropertyValue<string>("pageTitle"); }
}
///<summary>
/// Keywords: Keywords that describe the content of the page. This is consired optional since most modern search engines don't use this anymore
///</summary>
[ImplementPropertyType("keywords")]
public IEnumerable<string> Keywords
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetKeywords(this); }
}
///<summary>
/// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters
///</summary>
[ImplementPropertyType("seoMetaDescription")]
public string SeoMetaDescription
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetSeoMetaDescription(this); }
}
///<summary>
/// Hide in Navigation: If you don't want this page to appear in the navigation, check this box
///</summary>
[ImplementPropertyType("umbracoNavihide")]
public bool UmbracoNavihide
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetUmbracoNavihide(this); }
}
}
/// <summary>Contact</summary>
[PublishedContentModel("contact")]
public partial class Contact : PublishedContentModel, INavigationBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "contact";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Contact(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Contact, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// ApiKey: To use the map you'll need your own Google API key. More information here: https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
///</summary>
[ImplementPropertyType("apiKey")]
public string ApiKey
{
get { return this.GetPropertyValue<string>("apiKey"); }
}
///<summary>
/// Pick a Contact Form: If Umbraco Forms is installed you'll be able to select a form here.
///</summary>
[ImplementPropertyType("contactForm")]
public string ContactForm
{
get { return this.GetPropertyValue<string>("contactForm"); }
}
///<summary>
/// Contact Form Header
///</summary>
[ImplementPropertyType("contactFormHeader")]
public string ContactFormHeader
{
get { return this.GetPropertyValue<string>("contactFormHeader"); }
}
///<summary>
/// Contact Intro
///</summary>
[ImplementPropertyType("contactIntro")]
public IHtmlString ContactIntro
{
get { return this.GetPropertyValue<IHtmlString>("contactIntro"); }
}
///<summary>
/// Your Address: Plot your address on the map and it'll be displayed on the contact page
///</summary>
[ImplementPropertyType("map")]
public Terratype.Models.Model Map
{
get { return this.GetPropertyValue<Terratype.Models.Model>("map"); }
}
///<summary>
/// Map Header
///</summary>
[ImplementPropertyType("mapHeader")]
public string MapHeader
{
get { return this.GetPropertyValue<string>("mapHeader"); }
}
///<summary>
/// Page Title: The title of the page, this is also the first text in a google search result. The ideal length is between 40 and 60 characters
///</summary>
[ImplementPropertyType("pageTitle")]
public string PageTitle
{
get { return this.GetPropertyValue<string>("pageTitle"); }
}
///<summary>
/// Keywords: Keywords that describe the content of the page. This is consired optional since most modern search engines don't use this anymore
///</summary>
[ImplementPropertyType("keywords")]
public IEnumerable<string> Keywords
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetKeywords(this); }
}
///<summary>
/// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters
///</summary>
[ImplementPropertyType("seoMetaDescription")]
public string SeoMetaDescription
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetSeoMetaDescription(this); }
}
///<summary>
/// Hide in Navigation: If you don't want this page to appear in the navigation, check this box
///</summary>
[ImplementPropertyType("umbracoNavihide")]
public bool UmbracoNavihide
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetUmbracoNavihide(this); }
}
}
/// <summary>Content Page</summary>
[PublishedContentModel("contentPage")]
public partial class ContentPage : PublishedContentModel, IContentBase, INavigationBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "contentPage";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public ContentPage(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<ContentPage, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Content
///</summary>
[ImplementPropertyType("bodyText")]
public Newtonsoft.Json.Linq.JToken BodyText
{
get { return Umbraco.Web.PublishedContentModels.ContentBase.GetBodyText(this); }
}
///<summary>
/// Page Title: The title of the page, this is also the first text in a google search result. The ideal length is between 40 and 60 characters
///</summary>
[ImplementPropertyType("pageTitle")]
public string PageTitle
{
get { return Umbraco.Web.PublishedContentModels.ContentBase.GetPageTitle(this); }
}
///<summary>
/// Keywords: Keywords that describe the content of the page. This is consired optional since most modern search engines don't use this anymore
///</summary>
[ImplementPropertyType("keywords")]
public IEnumerable<string> Keywords
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetKeywords(this); }
}
///<summary>
/// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters
///</summary>
[ImplementPropertyType("seoMetaDescription")]
public string SeoMetaDescription
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetSeoMetaDescription(this); }
}
///<summary>
/// Hide in Navigation: If you don't want this page to appear in the navigation, check this box
///</summary>
[ImplementPropertyType("umbracoNavihide")]
public bool UmbracoNavihide
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetUmbracoNavihide(this); }
}
}
/// <summary>People</summary>
[PublishedContentModel("people")]
public partial class People : PublishedContentModel, IContentBase, INavigationBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "people";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public People(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<People, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Featured People
///</summary>
[ImplementPropertyType("featuredPeople")]
public IEnumerable<IPublishedContent> FeaturedPeople
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("featuredPeople"); }
}
///<summary>
/// Content
///</summary>
[ImplementPropertyType("bodyText")]
public Newtonsoft.Json.Linq.JToken BodyText
{
get { return Umbraco.Web.PublishedContentModels.ContentBase.GetBodyText(this); }
}
///<summary>
/// Page Title: The title of the page, this is also the first text in a google search result. The ideal length is between 40 and 60 characters
///</summary>
[ImplementPropertyType("pageTitle")]
public string PageTitle
{
get { return Umbraco.Web.PublishedContentModels.ContentBase.GetPageTitle(this); }
}
///<summary>
/// Keywords: Keywords that describe the content of the page. This is consired optional since most modern search engines don't use this anymore
///</summary>
[ImplementPropertyType("keywords")]
public IEnumerable<string> Keywords
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetKeywords(this); }
}
///<summary>
/// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters
///</summary>
[ImplementPropertyType("seoMetaDescription")]
public string SeoMetaDescription
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetSeoMetaDescription(this); }
}
///<summary>
/// Hide in Navigation: If you don't want this page to appear in the navigation, check this box
///</summary>
[ImplementPropertyType("umbracoNavihide")]
public bool UmbracoNavihide
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetUmbracoNavihide(this); }
}
}
/// <summary>Person</summary>
[PublishedContentModel("person")]
public partial class Person : PublishedContentModel, INavigationBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "person";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Person(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Person, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Department
///</summary>
[ImplementPropertyType("department")]
public IEnumerable<string> Department
{
get { return this.GetPropertyValue<IEnumerable<string>>("department"); }
}
///<summary>
/// Email
///</summary>
[ImplementPropertyType("email")]
public string Email
{
get { return this.GetPropertyValue<string>("email"); }
}
///<summary>
/// Facebook username
///</summary>
[ImplementPropertyType("facebookUsername")]
public string FacebookUsername
{
get { return this.GetPropertyValue<string>("facebookUsername"); }
}
///<summary>
/// Instagram Username
///</summary>
[ImplementPropertyType("instagramUsername")]
public string InstagramUsername
{
get { return this.GetPropertyValue<string>("instagramUsername"); }
}
///<summary>
/// LinkedIn username
///</summary>
[ImplementPropertyType("linkedInUsername")]
public string LinkedInUsername
{
get { return this.GetPropertyValue<string>("linkedInUsername"); }
}
///<summary>
/// Photo
///</summary>
[ImplementPropertyType("photo")]
public IPublishedContent Photo
{
get { return this.GetPropertyValue<IPublishedContent>("photo"); }
}
///<summary>
/// Twitter username
///</summary>
[ImplementPropertyType("twitterUsername")]
public string TwitterUsername
{
get { return this.GetPropertyValue<string>("twitterUsername"); }
}
///<summary>
/// Keywords: Keywords that describe the content of the page. This is consired optional since most modern search engines don't use this anymore
///</summary>
[ImplementPropertyType("keywords")]
public IEnumerable<string> Keywords
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetKeywords(this); }
}
///<summary>
/// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters
///</summary>
[ImplementPropertyType("seoMetaDescription")]
public string SeoMetaDescription
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetSeoMetaDescription(this); }
}
///<summary>
/// Hide in Navigation: If you don't want this page to appear in the navigation, check this box
///</summary>
[ImplementPropertyType("umbracoNavihide")]
public bool UmbracoNavihide
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetUmbracoNavihide(this); }
}
}
/// <summary>Product</summary>
[PublishedContentModel("product")]
public partial class Product : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "product";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Product(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Product, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Content
///</summary>
[ImplementPropertyType("bodyText")]
public Newtonsoft.Json.Linq.JToken BodyText
{
get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("bodyText"); }
}
///<summary>
/// Category
///</summary>
[ImplementPropertyType("category")]
public IEnumerable<string> Category
{
get { return this.GetPropertyValue<IEnumerable<string>>("category"); }
}
///<summary>
/// Description
///</summary>
[ImplementPropertyType("description")]
public string Description
{
get { return this.GetPropertyValue<string>("description"); }
}
///<summary>
/// Features
///</summary>
[ImplementPropertyType("features")]
public IEnumerable<IPublishedContent> Features
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("features"); }
}
///<summary>
/// Photos: You can add multiple photos - the first one will be the default and used in overviews and lists
///</summary>
[ImplementPropertyType("photos")]
public IEnumerable<IPublishedContent> Photos
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("photos"); }
}
///<summary>
/// Price
///</summary>
[ImplementPropertyType("price")]
public decimal Price
{
get { return this.GetPropertyValue<decimal>("price"); }
}
///<summary>
/// Product Name
///</summary>
[ImplementPropertyType("productName")]
public string ProductName
{
get { return this.GetPropertyValue<string>("productName"); }
}
///<summary>
/// SKU
///</summary>
[ImplementPropertyType("sku")]
public string Sku
{
get { return this.GetPropertyValue<string>("sku"); }
}
}
/// <summary>Products</summary>
[PublishedContentModel("products")]
public partial class Products : PublishedContentModel, IContentBase, INavigationBase
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "products";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public Products(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Products, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Default Currency: This is just used to prefix pricing
///</summary>
[ImplementPropertyType("defaultCurrency")]
public string DefaultCurrency
{
get { return this.GetPropertyValue<string>("defaultCurrency"); }
}
///<summary>
/// Featured Products
///</summary>
[ImplementPropertyType("featuredProducts")]
public IEnumerable<IPublishedContent> FeaturedProducts
{
get { return this.GetPropertyValue<IEnumerable<IPublishedContent>>("featuredProducts"); }
}
///<summary>
/// Content
///</summary>
[ImplementPropertyType("bodyText")]
public Newtonsoft.Json.Linq.JToken BodyText
{
get { return Umbraco.Web.PublishedContentModels.ContentBase.GetBodyText(this); }
}
///<summary>
/// Page Title: The title of the page, this is also the first text in a google search result. The ideal length is between 40 and 60 characters
///</summary>
[ImplementPropertyType("pageTitle")]
public string PageTitle
{
get { return Umbraco.Web.PublishedContentModels.ContentBase.GetPageTitle(this); }
}
///<summary>
/// Keywords: Keywords that describe the content of the page. This is consired optional since most modern search engines don't use this anymore
///</summary>
[ImplementPropertyType("keywords")]
public IEnumerable<string> Keywords
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetKeywords(this); }
}
///<summary>
/// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters
///</summary>
[ImplementPropertyType("seoMetaDescription")]
public string SeoMetaDescription
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetSeoMetaDescription(this); }
}
///<summary>
/// Hide in Navigation: If you don't want this page to appear in the navigation, check this box
///</summary>
[ImplementPropertyType("umbracoNavihide")]
public bool UmbracoNavihide
{
get { return Umbraco.Web.PublishedContentModels.NavigationBase.GetUmbracoNavihide(this); }
}
}
/// <summary>Folder</summary>
[PublishedContentModel("Folder")]
public partial class Folder : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Folder";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public Folder(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Folder, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Contents:
///</summary>
[ImplementPropertyType("contents")]
public object Contents
{
get { return this.GetPropertyValue("contents"); }
}
}
/// <summary>Image</summary>
[PublishedContentModel("Image")]
public partial class Image : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Image";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public Image(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Image, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Size
///</summary>
[ImplementPropertyType("umbracoBytes")]
public string UmbracoBytes
{
get { return this.GetPropertyValue<string>("umbracoBytes"); }
}
///<summary>
/// Type
///</summary>
[ImplementPropertyType("umbracoExtension")]
public string UmbracoExtension
{
get { return this.GetPropertyValue<string>("umbracoExtension"); }
}
///<summary>
/// Upload image
///</summary>
[ImplementPropertyType("umbracoFile")]
public Umbraco.Web.Models.ImageCropDataSet UmbracoFile
{
get { return this.GetPropertyValue<Umbraco.Web.Models.ImageCropDataSet>("umbracoFile"); }
}
///<summary>
/// Height
///</summary>
[ImplementPropertyType("umbracoHeight")]
public string UmbracoHeight
{
get { return this.GetPropertyValue<string>("umbracoHeight"); }
}
///<summary>
/// Width
///</summary>
[ImplementPropertyType("umbracoWidth")]
public string UmbracoWidth
{
get { return this.GetPropertyValue<string>("umbracoWidth"); }
}
}
/// <summary>File</summary>
[PublishedContentModel("File")]
public partial class File : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "File";
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
#pragma warning restore 0109
public File(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<File, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Size
///</summary>
[ImplementPropertyType("umbracoBytes")]
public string UmbracoBytes
{
get { return this.GetPropertyValue<string>("umbracoBytes"); }
}
///<summary>
/// Type
///</summary>
[ImplementPropertyType("umbracoExtension")]
public string UmbracoExtension
{
get { return this.GetPropertyValue<string>("umbracoExtension"); }
}
///<summary>
/// Upload file
///</summary>
[ImplementPropertyType("umbracoFile")]
public string UmbracoFile
{
get { return this.GetPropertyValue<string>("umbracoFile"); }
}
}
/// <summary>Member</summary>
[PublishedContentModel("Member")]
public partial class Member : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "Member";
public new const PublishedItemType ModelItemType = PublishedItemType.Member;
#pragma warning restore 0109
public Member(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Member, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Is Approved
///</summary>
[ImplementPropertyType("umbracoMemberApproved")]
public bool UmbracoMemberApproved
{
get { return this.GetPropertyValue<bool>("umbracoMemberApproved"); }
}
///<summary>
/// Comments
///</summary>
[ImplementPropertyType("umbracoMemberComments")]
public string UmbracoMemberComments
{
get { return this.GetPropertyValue<string>("umbracoMemberComments"); }
}
///<summary>
/// Failed Password Attempts
///</summary>
[ImplementPropertyType("umbracoMemberFailedPasswordAttempts")]
public string UmbracoMemberFailedPasswordAttempts
{
get { return this.GetPropertyValue<string>("umbracoMemberFailedPasswordAttempts"); }
}
///<summary>
/// Last Lockout Date
///</summary>
[ImplementPropertyType("umbracoMemberLastLockoutDate")]
public string UmbracoMemberLastLockoutDate
{
get { return this.GetPropertyValue<string>("umbracoMemberLastLockoutDate"); }
}
///<summary>
/// Last Login Date
///</summary>
[ImplementPropertyType("umbracoMemberLastLogin")]
public string UmbracoMemberLastLogin
{
get { return this.GetPropertyValue<string>("umbracoMemberLastLogin"); }
}
///<summary>
/// Last Password Change Date
///</summary>
[ImplementPropertyType("umbracoMemberLastPasswordChangeDate")]
public string UmbracoMemberLastPasswordChangeDate
{
get { return this.GetPropertyValue<string>("umbracoMemberLastPasswordChangeDate"); }
}
///<summary>
/// Is Locked Out
///</summary>
[ImplementPropertyType("umbracoMemberLockedOut")]
public bool UmbracoMemberLockedOut
{
get { return this.GetPropertyValue<bool>("umbracoMemberLockedOut"); }
}
///<summary>
/// Password Answer
///</summary>
[ImplementPropertyType("umbracoMemberPasswordRetrievalAnswer")]
public string UmbracoMemberPasswordRetrievalAnswer
{
get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalAnswer"); }
}
///<summary>
/// Password Question
///</summary>
[ImplementPropertyType("umbracoMemberPasswordRetrievalQuestion")]
public string UmbracoMemberPasswordRetrievalQuestion
{
get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalQuestion"); }
}
}
}
// EOF
| |
using Foundation;
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using UIKit;
using Hvz.Api;
using Hvz.Api.Game;
using Hvz.Api.Response;
namespace Hvz
{
partial class PlayersViewController : UITableViewController
{
private PlayersTableViewSource source = null;
private bool loading = false;
protected int currentPage = 0;
protected bool lastPage = false;
protected string sortBy = "team";
protected string currentSearch = "";
public PlayersViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
source = new PlayersTableViewSource {Controller = this};
TableView.Source = source;
sortBy = "team";
var button = ToolbarItems[0];
button.Title = "Team";
RefreshList();
NavigationController.SetToolbarHidden(false, true);
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
source = null;
loading = false;
}
protected void RefreshList()
{
if (loading || source == null)
return;
source.Players.Clear();
currentPage = 0;
lastPage = false;
LoadPage(0);
}
protected void LoadPage(int page)
{
if (loading || source == null || (page >= currentPage && lastPage == true))
return;
loading = true;
HvzClient.Instance.GetPlayerList(page, (response) =>
{
InvokeOnMainThread(() =>
{
if (source == null || !this.IsViewLoaded || View.Window == null)
{
loading = false;
return;
}
switch (response.Status)
{
case ApiResponse.ResponseStatus.Ok:
source.Players.AddRange(response.Players);
if (!response.HasMorePages)
lastPage = true;
if (page > currentPage)
currentPage = page;
TableView.ReloadData();
break;
case ApiResponse.ResponseStatus.Error:
var av = new UIAlertView("Error", "There was a problem retrieving the player list", null,
"OK", null);
av.Show();
break;
}
loading = false;
});
}, 10, sortBy);
}
private void ChangeSortMethod(string newMethod)
{
string method = newMethod.ToLower();
if (method == sortBy)
return;
sortBy = method;
RefreshList();
}
partial void OnSearchButtonPressed(UIBarButtonItem sender)
{
var av = new UIAlertView("Search", "Enter your search terms.", null, "Cancel", "Search");
av.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
av.GetTextField(0).Text = currentSearch;
av.Clicked += (o, args) =>
{
if(args.ButtonIndex == 1)
SearchList(av.GetTextField(0).Text);
};
av.Show();
}
private void SearchList(string term)
{
if (loading || source == null)
return;
currentSearch = term;
if (term.Length < 3)
{
var av = new UIAlertView("Error", "Searches have a minimum of three characters", null, "OK", null);
av.Show();
return;
}
currentPage = 0;
lastPage = false;
loading = true;
sortBy = "search";
source.Players.Clear();
TableView.ReloadData();
HvzClient.Instance.SearchPlayerList(term, (response) =>
{
InvokeOnMainThread(() =>
{
if (source == null || !this.IsViewLoaded || View.Window == null)
{
loading = false;
return;
}
switch (response.Status)
{
case ApiResponse.ResponseStatus.Ok:
source.Players.AddRange(response.Players);
TableView.ReloadData();
break;
case ApiResponse.ResponseStatus.Error:
var av = new UIAlertView("Error", "There was a problem searching the player list.", null, "OK",
null);
av.Show();
break;
}
loading = false;
});
});
}
partial void OnSortButtonPressed(UIBarButtonItem sender)
{
var av = new UIAlertView("Sort By", "Select how you would like to sort players", null, "Cancel", "Team", "Clan",
"Mods");
av.Clicked += (o, args) =>
{
var button = ToolbarItems[0];
switch (args.ButtonIndex)
{
case 1:
button.Title = "Team";
ChangeSortMethod(GameUtils.SortByTeam);
break;
case 2:
button.Title = "Clan";
ChangeSortMethod(GameUtils.SortByClan);
break;
case 3:
button.Title = "Mods";
ChangeSortMethod(GameUtils.SortByMods);
break;
}
};
av.Show();
}
private class PlayersTableViewSource : UITableViewSource
{
private const string cellIdentifier = "playerCell";
public List<Player> Players { get; set; }
public PlayersViewController Controller { get; set; }
public PlayersTableViewSource()
{
Players = new List<Player>();
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell(cellIdentifier) ??
new UITableViewCell(UITableViewCellStyle.Subtitle, cellIdentifier);
Player player = Players[indexPath.Row];
cell.TextLabel.Text = player.FullName;
cell.DetailTextLabel.Text = "Tags: " + player.HumansTagged + ", Clan: " + (string.IsNullOrWhiteSpace(player.Clan) ? "none" : player.Clan);
cell.BackgroundColor = player.Team == GameUtils.Team.Human
? UIColor.FromRGB(255, 117, 25)
: UIColor.FromRGB(49, 230, 54);
if (!string.IsNullOrWhiteSpace(player.Avatar))
{
try
{
using (var url = new NSUrl(ApiConfiguration.BaseUrl + "/" + player.Avatar))
using (var data = NSData.FromUrl(url))
cell.ImageView.Image = UIImage.LoadFromData(data);
}
catch (Exception e)
{
// horrible way to do this, but idk what kind of exceptions the code can throw, and it really
// doesn't matter since we would want to just display an empty image anyway.
}
}
else
{
cell.ImageView.Image = null;
}
if(indexPath.Row == Players.Count - 1)
Controller.LoadPage(Controller.currentPage + 1);
return cell;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return Players.Count;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableSortedSetTest : ImmutableSetTest
{
private enum Operation
{
Add,
Union,
Remove,
Except,
Last,
}
protected override bool IncludesGetHashCodeDerivative
{
get { return false; }
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedSet<int>();
var actual = ImmutableSortedSet<int>.Empty;
int seed = (int)DateTime.Now.Ticks;
Console.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Console.WriteLine("Adding \"{0}\" to the set.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.Union:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Console.WriteLine("Adding {0} elements to the set.", inputLength);
expected.UnionWith(values);
actual = actual.Union(values);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
int element = expected.Skip(position).First();
Console.WriteLine("Removing element \"{0}\" from the set.", element);
Assert.True(expected.Remove(element));
actual = actual.Remove(element);
}
break;
case Operation.Except:
var elements = expected.Where(el => random.Next(2) == 0).ToArray();
Console.WriteLine("Removing {0} elements from the set.", elements.Length);
expected.ExceptWith(elements);
actual = actual.Except(elements);
break;
}
Assert.Equal<int>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void EmptyTest()
{
this.EmptyTestHelper(Empty<int>(), 5, null);
this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal),
true,
new[] { "apple", "APPLE" },
new[] { "APPLE", "apple" });
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
true,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeSortComparer()
{
var ordinalSet = ImmutableSortedSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToUnorderedTest()
{
var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet();
Assert.True(result.Contains(3));
}
[Fact]
public void ToImmutableSortedSetTest()
{
var set = new[] { 1, 2, 2 }.ToImmutableSortedSet();
Assert.Same(Comparer<int>.Default, set.KeyComparer);
Assert.Equal(2, set.Count);
}
[Fact]
public void IndexOfTest()
{
var set = ImmutableSortedSet<int>.Empty;
Assert.Equal(~0, set.IndexOf(5));
set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
Assert.Equal(0, set.IndexOf(10));
Assert.Equal(1, set.IndexOf(20));
Assert.Equal(4, set.IndexOf(50));
Assert.Equal(8, set.IndexOf(90));
Assert.Equal(9, set.IndexOf(100));
Assert.Equal(~0, set.IndexOf(5));
Assert.Equal(~1, set.IndexOf(15));
Assert.Equal(~2, set.IndexOf(25));
Assert.Equal(~5, set.IndexOf(55));
Assert.Equal(~9, set.IndexOf(95));
Assert.Equal(~10, set.IndexOf(105));
}
[Fact]
public void IndexGetTest()
{
var set = ImmutableSortedSet<int>.Empty
.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
int i = 0;
foreach (var item in set)
{
AssertAreSame(item, set[i++]);
}
Assert.Throws<ArgumentOutOfRangeException>(() => set[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => set[set.Count]);
}
[Fact]
public void ReverseTest()
{
var range = Enumerable.Range(1, 10);
var set = ImmutableSortedSet<int>.Empty.Union(range);
var expected = range.Reverse().ToList();
var actual = set.Reverse().ToList();
Assert.Equal<int>(expected, actual);
}
[Fact]
public void MaxTest()
{
Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max);
}
[Fact]
public void MinTest()
{
Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min);
}
[Fact]
public void InitialBulkAdd()
{
Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count);
Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count);
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> set = ImmutableSortedSet.Create<string>();
Assert.Throws<NotSupportedException>(() => set.Add("a"));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove("a"));
Assert.True(set.IsReadOnly);
}
[Fact]
public void IListOfTMethods()
{
IList<string> set = ImmutableSortedSet.Create<string>("b");
Assert.Throws<NotSupportedException>(() => set.Insert(0, "a"));
Assert.Throws<NotSupportedException>(() => set.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => set[0] = "a");
Assert.Equal("b", set[0]);
Assert.True(set.IsReadOnly);
}
[Fact]
public void UnionOptimizationsTest()
{
var set = ImmutableSortedSet.Create(1, 2, 3);
var builder = set.ToBuilder();
Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder));
Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>()));
var smallSet = ImmutableSortedSet.Create(1);
var unionSet = smallSet.Union(set);
Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableSortedSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
}
[Fact]
public void IListMethods()
{
IList list = ImmutableSortedSet.Create("a", "b");
Assert.True(list.Contains("a"));
Assert.Equal("a", list[0]);
Assert.Equal("b", list[1]);
Assert.Equal(0, list.IndexOf("a"));
Assert.Equal(1, list.IndexOf("b"));
Assert.Throws<NotSupportedException>(() => list.Add("b"));
Assert.Throws<NotSupportedException>(() => list[3] = "c");
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, "b"));
Assert.Throws<NotSupportedException>(() => list.Remove("a"));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.True(list.IsFixedSize);
Assert.True(list.IsReadOnly);
}
[Fact]
public void TryGetValueTest()
{
this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedSet.Create<int>();
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected ImmutableSortedSet<T> EmptyTyped<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new SortedSet<T>();
}
internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
{
return ((ImmutableSortedSet<T>)set).Root;
}
/// <summary>
/// Tests various aspects of a sorted set.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
/// <param name="value">A value that could be placed in the set.</param>
/// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer)
{
Contract.Requires(emptySet != null);
this.EmptyTestHelper(emptySet);
Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer));
Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer);
var reemptied = emptySet.Add(value).Clear();
Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// 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 Event Store LLP 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.Diagnostics;
using System.Linq;
using EventStore.Common.Log;
using EventStore.Core.Bus;
using EventStore.Projections.Core.Messages;
namespace EventStore.Projections.Core.Services.Processing
{
public class EventProcessingProjectionProcessingPhase : EventSubscriptionBasedProjectionProcessingPhase,
IHandle<EventReaderSubscriptionMessage.CommittedEventReceived>,
IHandle<EventReaderSubscriptionMessage.PartitionEofReached>,
IHandle<EventReaderSubscriptionMessage.PartitionDeleted>,
IHandle<EventReaderSubscriptionMessage.PartitionMeasured>,
IEventProcessingProjectionPhase
{
private readonly IProjectionStateHandler _projectionStateHandler;
private readonly bool _definesStateTransform;
private readonly StatePartitionSelector _statePartitionSelector;
private readonly bool _isBiState;
private string _handlerPartition;
//private bool _sharedStateSet;
private readonly Stopwatch _stopwatch;
public EventProcessingProjectionProcessingPhase(
CoreProjection coreProjection, Guid projectionCorrelationId, IPublisher publisher,
ProjectionConfig projectionConfig, Action updateStatistics, IProjectionStateHandler projectionStateHandler,
PartitionStateCache partitionStateCache, bool definesStateTransform, string projectionName, ILogger logger,
CheckpointTag zeroCheckpointTag, ICoreProjectionCheckpointManager coreProjectionCheckpointManager,
StatePartitionSelector statePartitionSelector, ReaderSubscriptionDispatcher subscriptionDispatcher,
IReaderStrategy readerStrategy, IResultWriter resultWriter, bool useCheckpoints, bool stopOnEof,
bool isBiState, bool orderedPartitionProcessing)
: base(
publisher, coreProjection, projectionCorrelationId, coreProjectionCheckpointManager, projectionConfig,
projectionName, logger, zeroCheckpointTag, partitionStateCache, resultWriter, updateStatistics,
subscriptionDispatcher, readerStrategy, useCheckpoints, stopOnEof, orderedPartitionProcessing, isBiState)
{
_projectionStateHandler = projectionStateHandler;
_definesStateTransform = definesStateTransform;
_statePartitionSelector = statePartitionSelector;
_isBiState = isBiState;
_stopwatch = new Stopwatch();
}
public void Handle(EventReaderSubscriptionMessage.CommittedEventReceived message)
{
//TODO: make sure this is no longer required : if (_state != State.StateLoaded)
if (IsOutOfOrderSubscriptionMessage(message))
return;
RegisterSubscriptionMessage(message);
try
{
CheckpointTag eventTag = message.CheckpointTag;
var committedEventWorkItem = new CommittedEventWorkItem(this, message, _statePartitionSelector);
_processingQueue.EnqueueTask(committedEventWorkItem, eventTag);
if (_state == PhaseState.Running) // prevent processing mostly one projection
EnsureTickPending();
}
catch (Exception ex)
{
_coreProjection.SetFaulted(ex);
}
}
public void Handle(EventReaderSubscriptionMessage.PartitionDeleted message)
{
//TODO: make sure this is no longer required : if (_state != State.StateLoaded)
if (IsOutOfOrderSubscriptionMessage(message))
return;
RegisterSubscriptionMessage(message);
try
{
if (_statePartitionSelector.EventReaderBasePartitionDeletedIsSupported())
{
var partitionDeletedWorkItem = new PartitionDeletedWorkItem(this, message);
_processingQueue.EnqueueOutOfOrderTask(partitionDeletedWorkItem);
if (_state == PhaseState.Running) // prevent processing mostly one projection
EnsureTickPending();
}
}
catch (Exception ex)
{
_coreProjection.SetFaulted(ex);
}
}
public void Handle(EventReaderSubscriptionMessage.PartitionEofReached message)
{
if (IsOutOfOrderSubscriptionMessage(message))
return;
RegisterSubscriptionMessage(message);
try
{
var partitionCompletedWorkItem = new PartitionCompletedWorkItem(
this, _checkpointManager, message.Partition, message.CheckpointTag);
_processingQueue.EnqueueTask(
partitionCompletedWorkItem, message.CheckpointTag, allowCurrentPosition: true);
ProcessEvent();
}
catch (Exception ex)
{
_coreProjection.SetFaulted(ex);
}
}
public string TransformCatalogEvent(EventReaderSubscriptionMessage.CommittedEventReceived message)
{
switch (_state)
{
case PhaseState.Running:
var result = InternalTransformCatalogEvent(message);
return result;
case PhaseState.Stopped:
_logger.Error("Ignoring committed catalog event in stopped state");
return null;
default:
throw new NotSupportedException();
}
}
public EventProcessedResult ProcessCommittedEvent(
EventReaderSubscriptionMessage.CommittedEventReceived message, string partition)
{
switch (_state)
{
case PhaseState.Running:
var result = InternalProcessCommittedEvent(partition, message);
return result;
case PhaseState.Stopped:
_logger.Error("Ignoring committed event in stopped state");
return null;
default:
throw new NotSupportedException();
}
}
public EventProcessedResult ProcessPartitionDeleted(string partition, CheckpointTag deletedPosition)
{
switch (_state)
{
case PhaseState.Running:
var result = InternalProcessPartitionDeleted(partition, deletedPosition);
return result;
case PhaseState.Stopped:
_logger.Error("Ignoring committed event in stopped state");
return null;
default:
throw new NotSupportedException();
}
}
private EventProcessedResult InternalProcessCommittedEvent(
string partition, EventReaderSubscriptionMessage.CommittedEventReceived message)
{
string newState;
string projectionResult;
EmittedEventEnvelope[] emittedEvents;
//TODO: support shared state
string newSharedState;
var hasBeenProcessed = SafeProcessEventByHandler(
partition, message, out newState, out newSharedState, out projectionResult, out emittedEvents);
if (hasBeenProcessed)
{
var newPartitionState = new PartitionState(newState, projectionResult, message.CheckpointTag);
var newSharedPartitionState = newSharedState != null
? new PartitionState(newSharedState, null, message.CheckpointTag)
: null;
return InternalCommittedEventProcessed(
partition, message, emittedEvents, newPartitionState, newSharedPartitionState);
}
return null;
}
private EventProcessedResult InternalProcessPartitionDeleted(
string partition, CheckpointTag deletedPosition)
{
string newState;
string projectionResult;
var hasBeenProcessed = SafeProcessPartitionDeletedByHandler(
partition, deletedPosition, out newState, out projectionResult);
if (hasBeenProcessed)
{
var newPartitionState = new PartitionState(newState, projectionResult, deletedPosition);
return InternalPartitionDeletedProcessed(partition, deletedPosition, newPartitionState);
}
return null;
}
private string InternalTransformCatalogEvent(
EventReaderSubscriptionMessage.CommittedEventReceived message)
{
var result = SafeTransformCatalogEventByHandler(message);
return result;
}
private bool SafeProcessEventByHandler(
string partition, EventReaderSubscriptionMessage.CommittedEventReceived message, out string newState,
out string newSharedState, out string projectionResult, out EmittedEventEnvelope[] emittedEvents)
{
projectionResult = null;
//TODO: not emitting (optimized) projection handlers can skip serializing state on each processed event
bool hasBeenProcessed;
try
{
hasBeenProcessed = ProcessEventByHandler(
partition, message, out newState, out newSharedState, out projectionResult, out emittedEvents);
}
catch (Exception ex)
{
// update progress to reflect exact fault position
_checkpointManager.Progress(message.Progress);
SetFaulting(
String.Format(
"The {0} projection failed to process an event.\r\nHandler: {1}\r\nEvent Position: {2}\r\n\r\nMessage:\r\n\r\n{3}",
_projectionName, GetHandlerTypeName(), message.CheckpointTag, ex.Message), ex);
newState = null;
newSharedState = null;
emittedEvents = null;
hasBeenProcessed = false;
}
newState = newState ?? "";
return hasBeenProcessed;
}
private bool SafeProcessPartitionDeletedByHandler(
string partition, CheckpointTag deletedPosition, out string newState,
out string projectionResult)
{
projectionResult = null;
//TODO: not emitting (optimized) projection handlers can skip serializing state on each processed event
bool hasBeenProcessed;
try
{
hasBeenProcessed = ProcessPartitionDeletedByHandler(
partition, deletedPosition, out newState, out projectionResult);
}
catch (Exception ex)
{
SetFaulting(
String.Format(
"The {0} projection failed to process a delete partition notification.\r\nHandler: {1}\r\nEvent Position: {2}\r\n\r\nMessage:\r\n\r\n{3}",
_projectionName, GetHandlerTypeName(), deletedPosition, ex.Message), ex);
newState = null;
hasBeenProcessed = false;
}
newState = newState ?? "";
return hasBeenProcessed;
}
private string SafeTransformCatalogEventByHandler(EventReaderSubscriptionMessage.CommittedEventReceived message)
{
string result;
try
{
result = TransformCatalogEventByHandler(message);
}
catch (Exception ex)
{
// update progress to reflect exact fault position
_checkpointManager.Progress(message.Progress);
SetFaulting(
String.Format(
"The {0} projection failed to transform a catalog event.\r\nHandler: {1}\r\nEvent Position: {2}\r\n\r\nMessage:\r\n\r\n{3}",
_projectionName, GetHandlerTypeName(), message.CheckpointTag, ex.Message), ex);
result = null;
}
return result;
}
private string GetHandlerTypeName()
{
return _projectionStateHandler.GetType().Namespace + "." + _projectionStateHandler.GetType().Name;
}
private bool ProcessEventByHandler(
string partition, EventReaderSubscriptionMessage.CommittedEventReceived message, out string newState,
out string newSharedState, out string projectionResult, out EmittedEventEnvelope[] emittedEvents)
{
projectionResult = null;
var newPatitionInitialized = InitOrLoadHandlerState(partition);
_stopwatch.Start();
EmittedEventEnvelope[] eventsEmittedOnInitialization = null;
if (newPatitionInitialized)
{
_projectionStateHandler.ProcessPartitionCreated(
partition, message.CheckpointTag, message.Data, out eventsEmittedOnInitialization);
}
var result = _projectionStateHandler.ProcessEvent(
partition, message.CheckpointTag, message.EventCategory, message.Data, out newState, out newSharedState,
out emittedEvents);
if (result)
{
var oldState = _partitionStateCache.GetLockedPartitionState(partition);
//TODO: depending on query processing final state to result transformation should happen either here (if EOF) on while writing results
if ( /*_producesRunningResults && */oldState.State != newState)
{
if (_definesStateTransform)
{
projectionResult = _projectionStateHandler.TransformStateToResult();
}
else
{
projectionResult = newState;
}
}
else
{
projectionResult = oldState.Result;
}
}
_stopwatch.Stop();
if (eventsEmittedOnInitialization != null)
{
if (emittedEvents == null || emittedEvents.Length == 0)
emittedEvents = eventsEmittedOnInitialization;
else
emittedEvents = eventsEmittedOnInitialization.Concat(emittedEvents).ToArray();
}
return result;
}
private bool ProcessPartitionDeletedByHandler(
string partition, CheckpointTag deletePosition, out string newState,
out string projectionResult)
{
projectionResult = null;
InitOrLoadHandlerState(partition);
_stopwatch.Start();
var result = _projectionStateHandler.ProcessPartitionDeleted(
partition, deletePosition, out newState);
if (result)
{
var oldState = _partitionStateCache.GetLockedPartitionState(partition);
//TODO: depending on query processing final state to result transformation should happen either here (if EOF) on while writing results
if ( /*_producesRunningResults && */oldState.State != newState)
{
if (_definesStateTransform)
{
projectionResult = _projectionStateHandler.TransformStateToResult();
}
else
{
projectionResult = newState;
}
}
else
{
projectionResult = oldState.Result;
}
}
_stopwatch.Stop();
return result;
}
private string TransformCatalogEventByHandler(EventReaderSubscriptionMessage.CommittedEventReceived message)
{
_stopwatch.Start();
var result = _projectionStateHandler.TransformCatalogEvent(message.CheckpointTag, message.Data);
_stopwatch.Stop();
return result;
}
/// <summary>
/// initializes or loads existing partition state
/// </summary>
/// <param name="partition"></param>
/// <returns>true - if new partition state was initialized</returns>
private bool InitOrLoadHandlerState(string partition)
{
if (_handlerPartition == partition)
return false;
var newState = _partitionStateCache.GetLockedPartitionState(partition);
_handlerPartition = partition;
var initialized = false;
if (newState != null && !String.IsNullOrEmpty(newState.State))
_projectionStateHandler.Load(newState.State);
else
{
initialized = true;
_projectionStateHandler.Initialize();
}
//if (!_sharedStateSet && _isBiState)
if (_isBiState)
{
var newSharedState = _partitionStateCache.GetLockedPartitionState("");
if (newSharedState != null && !String.IsNullOrEmpty(newSharedState.State))
_projectionStateHandler.LoadShared(newSharedState.State);
else
_projectionStateHandler.InitializeShared();
}
return initialized;
}
public override void NewCheckpointStarted(CheckpointTag at)
{
if (!(_state == PhaseState.Running || _state == PhaseState.Starting))
{
Console.WriteLine("Starting a checkpoint in non-runnable state");
return;
}
var checkpointHandler = _projectionStateHandler as IProjectionCheckpointHandler;
if (checkpointHandler != null)
{
EmittedEventEnvelope[] emittedEvents;
try
{
checkpointHandler.ProcessNewCheckpoint(at, out emittedEvents);
}
catch (Exception ex)
{
var faultedReason =
String.Format(
"The {0} projection failed to process a checkpoint start.\r\nHandler: {1}\r\nEvent Position: {2}\r\n\r\nMessage:\r\n\r\n{3}",
_projectionName, GetHandlerTypeName(), at, ex.Message);
SetFaulting(faultedReason, ex);
emittedEvents = null;
}
if (emittedEvents != null && emittedEvents.Length > 0)
{
if (!ValidateEmittedEvents(emittedEvents))
return;
if (_state == PhaseState.Running || _state == PhaseState.Starting)
_resultWriter.EventsEmitted(
emittedEvents, Guid.Empty, correlationId: null);
}
}
}
public override void GetStatistics(ProjectionStatistics info)
{
base.GetStatistics(info);
info.CoreProcessingTime = _stopwatch.ElapsedMilliseconds;
}
public override void Dispose()
{
if (_projectionStateHandler != null)
_projectionStateHandler.Dispose();
}
public void Handle(EventReaderSubscriptionMessage.PartitionMeasured message)
{
if (IsOutOfOrderSubscriptionMessage(message))
return;
RegisterSubscriptionMessage(message);
try
{
_resultWriter.WritePartitionMeasured(message.SubscriptionId, message.Partition, message.Size);
}
catch (Exception ex)
{
_coreProjection.SetFaulted(ex);
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Filters;
using NLog.Internal;
using NLog.Targets;
/// <summary>
/// Implementation of logging engine.
/// </summary>
internal static class LoggerImpl
{
private const int StackTraceSkipMethods = 0;
private static readonly Assembly nlogAssembly = typeof(LoggerImpl).Assembly;
private static readonly Assembly mscorlibAssembly = typeof(string).Assembly;
private static readonly Assembly systemAssembly = typeof(Debug).Assembly;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using 'NLog' in message.")]
internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
{
if (targets == null)
{
return;
}
#if !NET_CF
StackTraceUsage stu = targets.GetStackTraceUsage();
if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
{
StackTrace stackTrace;
#if !SILVERLIGHT
stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
stackTrace = new StackTrace();
#endif
int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);
logEvent.SetStackTrace(stackTrace, firstUserFrame);
}
#endif
int originalThreadId = Thread.CurrentThread.ManagedThreadId;
AsyncContinuation exceptionHandler = ex =>
{
if (ex != null)
{
if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId)
{
throw new NLogRuntimeException("Exception occurred in NLog", ex);
}
}
};
for (var t = targets; t != null; t = t.NextInChain)
{
if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
{
break;
}
}
}
#if !NET_CF
private static int FindCallingMethodOnStackTrace(StackTrace stackTrace, Type loggerType)
{
int firstUserFrame = 0;
for (int i = 0; i < stackTrace.FrameCount; ++i)
{
StackFrame frame = stackTrace.GetFrame(i);
MethodBase mb = frame.GetMethod();
Assembly methodAssembly = null;
if (mb.DeclaringType != null)
{
methodAssembly = mb.DeclaringType.Assembly;
}
if ((loggerType == null && SkipAssembly(methodAssembly)) || mb.DeclaringType == loggerType)
{
firstUserFrame = i + 1;
}
else
{
if (firstUserFrame != 0)
{
break;
}
}
}
return firstUserFrame;
}
private static bool SkipAssembly(Assembly assembly)
{
if (assembly == nlogAssembly)
{
return true;
}
if (assembly == mscorlibAssembly)
{
return true;
}
if (assembly == systemAssembly)
{
return true;
}
return false;
}
#endif
private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
{
Target target = targetListHead.Target;
FilterResult result = GetFilterResult(targetListHead.FilterChain, logEvent);
if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal))
{
if (InternalLogger.IsDebugEnabled)
{
InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level);
}
if (result == FilterResult.IgnoreFinal)
{
return false;
}
return true;
}
target.WriteAsyncLogEvent(logEvent.WithContinuation(onException));
if (result == FilterResult.LogFinal)
{
return false;
}
return true;
}
/// <summary>
/// Gets the filter result.
/// </summary>
/// <param name="filterChain">The filter chain.</param>
/// <param name="logEvent">The log event.</param>
/// <returns>The result of the filter.</returns>
private static FilterResult GetFilterResult(IEnumerable<Filter> filterChain, LogEventInfo logEvent)
{
FilterResult result = FilterResult.Neutral;
try
{
foreach (Filter f in filterChain)
{
result = f.GetFilterResult(logEvent);
if (result != FilterResult.Neutral)
{
break;
}
}
return result;
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Exception during filter evaluation: {0}", exception);
return FilterResult.Ignore;
}
}
}
}
| |
// 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 AlignRightInt640()
{
var test = new ImmBinaryOpTest__AlignRightInt640();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ImmBinaryOpTest__AlignRightInt640
{
private struct TestStruct
{
public Vector256<Int64> _fld1;
public Vector256<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__AlignRightInt640 testClass)
{
var result = Avx2.AlignRight(_fld1, _fld2, 0);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector256<Int64> _clsVar1;
private static Vector256<Int64> _clsVar2;
private Vector256<Int64> _fld1;
private Vector256<Int64> _fld2;
private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable;
static ImmBinaryOpTest__AlignRightInt640()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
}
public ImmBinaryOpTest__AlignRightInt640()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.AlignRight(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr),
0
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.AlignRight(
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)),
0
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.AlignRight(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)),
0
);
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(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.AlignRight(
_clsVar1,
_clsVar2,
0
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
var result = Avx2.AlignRight(left, right, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx2.AlignRight(left, right, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx2.AlignRight(left, right, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__AlignRightInt640();
var result = Avx2.AlignRight(test._fld1, test._fld2, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.AlignRight(_fld1, _fld2, 0);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.AlignRight(test._fld1, test._fld2, 0);
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 RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != right[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<Int64>(Vector256<Int64>.0, Vector256<Int64>): {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;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Environment = System.Environment;
using StreamWriter = System.IO.StreamWriter;
namespace Unity.IL2CPP
{
public static class Shell
{
private static readonly object FileLocker = new object();
private static readonly object PipeLocker = new object();
public class ExecuteArgs
{
public string Executable { get; set; }
public string Arguments { get; set; }
public Dictionary<string, string> EnvVars { get; set; }
public string WorkingDirectory { get; set; }
}
public class ExecuteResult
{
public string StdOut { get; set; }
public string StdErr { get; set; }
public int ExitCode { get; set; }
public TimeSpan Duration { get; set; }
}
public interface IExecuteController
{
void OnStdoutReceived(string data);
void OnStderrReceived(string data);
void AboutToCleanup(string tempOutputFile, string tempErrorFile);
}
private class LiveOutput : IExecuteController
{
public static readonly IExecuteController Instance = new LiveOutput();
public void OnStdoutReceived(string data)
{
Console.WriteLine(data);
}
public void OnStderrReceived(string data)
{
Console.WriteLine(data);
}
public void AboutToCleanup(string tempOutputFile, string tempErrorFile)
{
}
}
public static string ExecuteAndCaptureOutput(NiceIO.NPath filename, string arguments, Dictionary<string, string> envVars = null)
{
return ExecuteAndCaptureOutput(filename.ToString(), arguments, envVars);
}
public static string ExecuteAndCaptureOutput(string filename, string arguments, Dictionary<string, string> envVars = null)
{
ExecuteArgs executeArgs = new ExecuteArgs { Executable = filename, Arguments = arguments, EnvVars = envVars};
return ExecuteAndCaptureOutput(executeArgs);
}
public static string ExecuteAndCaptureOutput(string filename, string arguments, string workingDirectory, Dictionary<string, string> envVars = null)
{
ExecuteArgs executeArgs = new ExecuteArgs { Executable = filename, Arguments = arguments, WorkingDirectory = workingDirectory, EnvVars = envVars };
return ExecuteAndCaptureOutput(executeArgs);
}
public static string ExecuteAndCaptureOutput(ExecuteArgs executeArgs)
{
var result = Execute(executeArgs);
var allConsoleOutput = result.StdErr.Trim() + result.StdOut.Trim();
if (0 != result.ExitCode)
{
throw new Exception(string.Format(
"Process {0} ended with exitcode {1}" + Environment.NewLine +
"{2}" + Environment.NewLine,
executeArgs.Executable,
result.ExitCode,
allConsoleOutput));
}
return allConsoleOutput;
}
public static ExecuteResult ExecuteWithLiveOutput(ExecuteArgs executeArgs)
{
return Execute(executeArgs, LiveOutput.Instance);
}
public static ExecuteResult Execute(ExecuteArgs executeArgs, IExecuteController controller = null)
{
using (var p = NewProcess(executeArgs))
{
FileStream fOut, fError;
string tempOutputFile, tempErrorFile;
lock (FileLocker)
{
tempOutputFile = Path.GetTempFileName();
tempErrorFile = Path.GetTempFileName();
fOut = File.Create(tempOutputFile);
fError = File.Create(tempErrorFile);
}
var stopWatch = new Stopwatch();
stopWatch.Start();
using (
StreamWriter outputWriter = new StreamWriter(fOut, Encoding.UTF8),
errorWriter = new StreamWriter(fError, Encoding.UTF8))
{
p.OutputDataReceived += (sender, args) =>
{
outputWriter.WriteLine(args.Data);
if (controller != null)
controller.OnStdoutReceived(args.Data);
};
p.ErrorDataReceived += (sender, args) =>
{
errorWriter.WriteLine(args.Data);
if (controller != null)
controller.OnStderrReceived(args.Data);
};
lock (PipeLocker)
{
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
p.WaitForExit();
p.CancelErrorRead();
p.CancelOutputRead();
}
string output;
string error;
lock (FileLocker)
{
if (controller != null)
controller.AboutToCleanup(tempOutputFile, tempErrorFile);
output = File.ReadAllText(tempOutputFile, Encoding.UTF8);
File.Delete(tempOutputFile);
error = File.ReadAllText(tempErrorFile, Encoding.UTF8);
File.Delete(tempErrorFile);
}
stopWatch.Stop();
var result = new ExecuteResult()
{
ExitCode = p.ExitCode,
StdOut = output,
StdErr = error,
Duration = TimeSpan.FromMilliseconds(stopWatch.ElapsedMilliseconds)
};
return result;
}
}
public static Process StartProcess(string filename, string arguments)
{
var p = NewProcess(new ExecuteArgs { Executable = filename, Arguments = arguments});
p.Start();
return p;
}
static Process NewProcess(ExecuteArgs executeArgs)
{
var p = new Process
{
StartInfo =
{
Arguments = executeArgs.Arguments,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
FileName = executeArgs.Executable,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
WorkingDirectory = executeArgs.WorkingDirectory,
}
};
if (executeArgs.EnvVars != null)
foreach (var envVar in executeArgs.EnvVars)
p.StartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
return p;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Xunit;
using Prism.Events;
namespace Prism.Tests.Events
{
public class PubSubEventFixture
{
[Fact]
public void CanSubscribeAndRaiseEvent()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
bool published = false;
pubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, true, delegate { return true; });
pubSubEvent.Publish(null);
Assert.True(published);
}
[Fact]
public void CanSubscribeAndRaiseCustomEvent()
{
var customEvent = new TestablePubSubEvent<Payload>();
Payload payload = new Payload();
var action = new ActionHelper();
customEvent.Subscribe(action.Action);
customEvent.Publish(payload);
Assert.Same(action.ActionArg<Payload>(), payload);
}
[Fact]
public void CanHaveMultipleSubscribersAndRaiseCustomEvent()
{
var customEvent = new TestablePubSubEvent<Payload>();
Payload payload = new Payload();
var action1 = new ActionHelper();
var action2 = new ActionHelper();
customEvent.Subscribe(action1.Action);
customEvent.Subscribe(action2.Action);
customEvent.Publish(payload);
Assert.Same(action1.ActionArg<Payload>(), payload);
Assert.Same(action2.ActionArg<Payload>(), payload);
}
[Fact]
public void SubscribeTakesExecuteDelegateThreadOptionAndFilter()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
var action = new ActionHelper();
pubSubEvent.Subscribe(action.Action);
pubSubEvent.Publish("test");
Assert.Equal("test", action.ActionArg<string>());
}
[Fact]
public void FilterEnablesActionTarget()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
var goodFilter = new MockFilter { FilterReturnValue = true };
var actionGoodFilter = new ActionHelper();
var badFilter = new MockFilter { FilterReturnValue = false };
var actionBadFilter = new ActionHelper();
pubSubEvent.Subscribe(actionGoodFilter.Action, ThreadOption.PublisherThread, true, goodFilter.FilterString);
pubSubEvent.Subscribe(actionBadFilter.Action, ThreadOption.PublisherThread, true, badFilter.FilterString);
pubSubEvent.Publish("test");
Assert.True(actionGoodFilter.ActionCalled);
Assert.False(actionBadFilter.ActionCalled);
}
[Fact]
public void SubscribeDefaultsThreadOptionAndNoFilter()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
SynchronizationContext calledSyncContext = null;
var myAction = new ActionHelper()
{
ActionToExecute =
() => calledSyncContext = SynchronizationContext.Current
};
pubSubEvent.Subscribe(myAction.Action);
pubSubEvent.Publish("test");
Assert.Equal(SynchronizationContext.Current, calledSyncContext);
}
[Fact]
public void ShouldUnsubscribeFromPublisherThread()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var actionEvent = new ActionHelper();
PubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.PublisherThread);
Assert.True(PubSubEvent.Contains(actionEvent.Action));
PubSubEvent.Unsubscribe(actionEvent.Action);
Assert.False(PubSubEvent.Contains(actionEvent.Action));
}
[Fact]
public void UnsubscribeShouldNotFailWithNonSubscriber()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
Action<string> subscriber = delegate { };
pubSubEvent.Unsubscribe(subscriber);
}
[Fact]
public void ShouldUnsubscribeFromBackgroundThread()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var actionEvent = new ActionHelper();
PubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.BackgroundThread);
Assert.True(PubSubEvent.Contains(actionEvent.Action));
PubSubEvent.Unsubscribe(actionEvent.Action);
Assert.False(PubSubEvent.Contains(actionEvent.Action));
}
[Fact]
public void ShouldUnsubscribeFromUIThread()
{
var PubSubEvent = new TestablePubSubEvent<string>();
PubSubEvent.SynchronizationContext = new SynchronizationContext();
var actionEvent = new ActionHelper();
PubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.UIThread);
Assert.True(PubSubEvent.Contains(actionEvent.Action));
PubSubEvent.Unsubscribe(actionEvent.Action);
Assert.False(PubSubEvent.Contains(actionEvent.Action));
}
[Fact]
public void ShouldUnsubscribeASingleDelegate()
{
var PubSubEvent = new TestablePubSubEvent<string>();
int callCount = 0;
var actionEvent = new ActionHelper() { ActionToExecute = () => callCount++ };
PubSubEvent.Subscribe(actionEvent.Action);
PubSubEvent.Subscribe(actionEvent.Action);
PubSubEvent.Publish(null);
Assert.Equal<int>(2, callCount);
callCount = 0;
PubSubEvent.Unsubscribe(actionEvent.Action);
PubSubEvent.Publish(null);
Assert.Equal<int>(1, callCount);
}
[Fact]
public void ShouldNotExecuteOnGarbageCollectedDelegateReferenceWhenNotKeepAlive()
{
var PubSubEvent = new TestablePubSubEvent<string>();
ExternalAction externalAction = new ExternalAction();
PubSubEvent.Subscribe(externalAction.ExecuteAction);
PubSubEvent.Publish("testPayload");
Assert.Equal("testPayload", externalAction.PassedValue);
WeakReference actionEventReference = new WeakReference(externalAction);
externalAction = null;
GC.Collect();
Assert.False(actionEventReference.IsAlive);
PubSubEvent.Publish("testPayload");
}
[Fact]
public void ShouldNotExecuteOnGarbageCollectedFilterReferenceWhenNotKeepAlive()
{
var PubSubEvent = new TestablePubSubEvent<string>();
bool wasCalled = false;
var actionEvent = new ActionHelper() { ActionToExecute = () => wasCalled = true };
ExternalFilter filter = new ExternalFilter();
PubSubEvent.Subscribe(actionEvent.Action, ThreadOption.PublisherThread, false, filter.AlwaysTrueFilter);
PubSubEvent.Publish("testPayload");
Assert.True(wasCalled);
wasCalled = false;
WeakReference filterReference = new WeakReference(filter);
filter = null;
GC.Collect();
Assert.False(filterReference.IsAlive);
PubSubEvent.Publish("testPayload");
Assert.False(wasCalled);
}
[Fact]
public void CanAddSubscriptionWhileEventIsFiring()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var subscriptionAction = new ActionHelper
{
ActionToExecute = (() =>
PubSubEvent.Subscribe(
emptyAction.Action))
};
PubSubEvent.Subscribe(subscriptionAction.Action);
Assert.False(PubSubEvent.Contains(emptyAction.Action));
PubSubEvent.Publish(null);
Assert.True((PubSubEvent.Contains(emptyAction.Action)));
}
[Fact]
public void InlineDelegateDeclarationsDoesNotGetCollectedIncorrectlyWithWeakReferences()
{
var PubSubEvent = new TestablePubSubEvent<string>();
bool published = false;
PubSubEvent.Subscribe(delegate { published = true; }, ThreadOption.PublisherThread, false, delegate { return true; });
GC.Collect();
PubSubEvent.Publish(null);
Assert.True(published);
}
[Fact]
public void ShouldNotGarbageCollectDelegateReferenceWhenUsingKeepAlive()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var externalAction = new ExternalAction();
PubSubEvent.Subscribe(externalAction.ExecuteAction, ThreadOption.PublisherThread, true);
WeakReference actionEventReference = new WeakReference(externalAction);
externalAction = null;
GC.Collect();
GC.Collect();
Assert.True(actionEventReference.IsAlive);
PubSubEvent.Publish("testPayload");
Assert.Equal("testPayload", ((ExternalAction)actionEventReference.Target).PassedValue);
}
[Fact]
public void RegisterReturnsTokenThatCanBeUsedToUnsubscribe()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var token = PubSubEvent.Subscribe(emptyAction.Action);
PubSubEvent.Unsubscribe(token);
Assert.False(PubSubEvent.Contains(emptyAction.Action));
}
[Fact]
public void ContainsShouldSearchByToken()
{
var PubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var token = PubSubEvent.Subscribe(emptyAction.Action);
Assert.True(PubSubEvent.Contains(token));
PubSubEvent.Unsubscribe(emptyAction.Action);
Assert.False(PubSubEvent.Contains(token));
}
[Fact]
public void SubscribeDefaultsToPublisherThread()
{
var PubSubEvent = new TestablePubSubEvent<string>();
Action<string> action = delegate { };
var token = PubSubEvent.Subscribe(action, true);
Assert.Equal(1, PubSubEvent.BaseSubscriptions.Count);
Assert.Equal(typeof(EventSubscription<string>), PubSubEvent.BaseSubscriptions.ElementAt(0).GetType());
}
public class ExternalFilter
{
public bool AlwaysTrueFilter(string value)
{
return true;
}
}
public class ExternalAction
{
public string PassedValue;
public void ExecuteAction(string value)
{
PassedValue = value;
}
}
class TestablePubSubEvent<TPayload> : PubSubEvent<TPayload>
{
public ICollection<IEventSubscription> BaseSubscriptions
{
get { return base.Subscriptions; }
}
}
public class Payload { }
}
public class ActionHelper
{
public bool ActionCalled;
public Action ActionToExecute = null;
private object actionArg;
public T ActionArg<T>()
{
return (T)actionArg;
}
public void Action(PubSubEventFixture.Payload arg)
{
Action((object)arg);
}
public void Action(string arg)
{
Action((object)arg);
}
public void Action(object arg)
{
actionArg = arg;
ActionCalled = true;
if (ActionToExecute != null)
{
ActionToExecute.Invoke();
}
}
}
public class MockFilter
{
public bool FilterReturnValue;
public bool FilterString(string arg)
{
return FilterReturnValue;
}
}
}
| |
using System;
using Xamarin.Forms;
namespace NReact
{
public partial class NProperties
{
public NProperty AnchorX { get { return _anchorX ?? (_anchorX = NPropFactories.CreateAnchorX()); } }
NProperty _anchorX;
public NProperty AnchorY { get { return _anchorY ?? (_anchorY = NPropFactories.CreateAnchorY()); } }
NProperty _anchorY;
public NProperty Appearing { get { return _appearing ?? (_appearing = NPropFactories.CreateAppearing()); } }
NProperty _appearing;
public NProperty Aspect { get { return _aspect ?? (_aspect = NPropFactories.CreateAspect()); } }
NProperty _aspect;
public NProperty BackgroundColor { get { return _backgroundColor ?? (_backgroundColor = NPropFactories.CreateBackgroundColor()); } }
NProperty _backgroundColor;
public NProperty BackgroundImage { get { return _backgroundImage ?? (_backgroundImage = NPropFactories.CreateBackgroundImage()); } }
NProperty _backgroundImage;
public NProperty BarBackgroundColor { get { return _barBackgroundColor ?? (_barBackgroundColor = NPropFactories.CreateBarBackgroundColor()); } }
NProperty _barBackgroundColor;
public NProperty BarTextColor { get { return _barTextColor ?? (_barTextColor = NPropFactories.CreateBarTextColor()); } }
NProperty _barTextColor;
public NProperty BorderColor { get { return _borderColor ?? (_borderColor = NPropFactories.CreateBorderColor()); } }
NProperty _borderColor;
public NProperty BorderRadius { get { return _borderRadius ?? (_borderRadius = NPropFactories.CreateBorderRadius()); } }
NProperty _borderRadius;
public NProperty BorderWidth { get { return _borderWidth ?? (_borderWidth = NPropFactories.CreateBorderWidth()); } }
NProperty _borderWidth;
public NProperty CancelButtonColor { get { return _cancelButtonColor ?? (_cancelButtonColor = NPropFactories.CreateCancelButtonColor()); } }
NProperty _cancelButtonColor;
public NProperty Child { get { return _child ?? (_child = NPropFactories.CreateChild()); } }
NProperty _child;
public NProperty Children { get { return _children ?? (_children = NPropFactories.CreateChildren()); } }
NProperty _children;
public NProperty ChildrenReordered { get { return _childrenReordered ?? (_childrenReordered = NPropFactories.CreateChildrenReordered()); } }
NProperty _childrenReordered;
public NProperty Clicked { get { return _clicked ?? (_clicked = NPropFactories.CreateClicked()); } }
NProperty _clicked;
public NProperty Color { get { return _color ?? (_color = NPropFactories.CreateColor()); } }
NProperty _color;
public NProperty Command { get { return _command ?? (_command = NPropFactories.CreateCommand()); } }
NProperty _command;
public NProperty CommandParameter { get { return _commandParameter ?? (_commandParameter = NPropFactories.CreateCommandParameter()); } }
NProperty _commandParameter;
public NProperty Completed { get { return _completed ?? (_completed = NPropFactories.CreateCompleted()); } }
NProperty _completed;
public NProperty Content { get { return _content ?? (_content = NPropFactories.CreateContent()); } }
NProperty _content;
public NProperty ControlTemplate { get { return _controlTemplate ?? (_controlTemplate = NPropFactories.CreateControlTemplate()); } }
NProperty _controlTemplate;
public NProperty Date { get { return _date ?? (_date = NPropFactories.CreateDate()); } }
NProperty _date;
public NProperty DateSelected { get { return _dateSelected ?? (_dateSelected = NPropFactories.CreateDateSelected()); } }
NProperty _dateSelected;
public NProperty Disappearing { get { return _disappearing ?? (_disappearing = NPropFactories.CreateDisappearing()); } }
NProperty _disappearing;
public NProperty Focused { get { return _focused ?? (_focused = NPropFactories.CreateFocused()); } }
NProperty _focused;
public NProperty Font { get { return _font ?? (_font = NPropFactories.CreateFont()); } }
NProperty _font;
public NProperty FontAttributes { get { return _fontAttributes ?? (_fontAttributes = NPropFactories.CreateFontAttributes()); } }
NProperty _fontAttributes;
public NProperty FontFamily { get { return _fontFamily ?? (_fontFamily = NPropFactories.CreateFontFamily()); } }
NProperty _fontFamily;
public NProperty FontSize { get { return _fontSize ?? (_fontSize = NPropFactories.CreateFontSize()); } }
NProperty _fontSize;
public NProperty Format { get { return _format ?? (_format = NPropFactories.CreateFormat()); } }
NProperty _format;
public NProperty FormattedText { get { return _formattedText ?? (_formattedText = NPropFactories.CreateFormattedText()); } }
NProperty _formattedText;
public NProperty HasRenderLoop { get { return _hasRenderLoop ?? (_hasRenderLoop = NPropFactories.CreateHasRenderLoop()); } }
NProperty _hasRenderLoop;
public NProperty HasShadow { get { return _hasShadow ?? (_hasShadow = NPropFactories.CreateHasShadow()); } }
NProperty _hasShadow;
public NProperty HasUnevenRows { get { return _hasUnevenRows ?? (_hasUnevenRows = NPropFactories.CreateHasUnevenRows()); } }
NProperty _hasUnevenRows;
public NProperty HeightRequest { get { return _heightRequest ?? (_heightRequest = NPropFactories.CreateHeightRequest()); } }
NProperty _heightRequest;
public NProperty HorizontalOptions { get { return _horizontalOptions ?? (_horizontalOptions = NPropFactories.CreateHorizontalOptions()); } }
NProperty _horizontalOptions;
public NProperty HorizontalTextAlignment { get { return _horizontalTextAlignment ?? (_horizontalTextAlignment = NPropFactories.CreateHorizontalTextAlignment()); } }
NProperty _horizontalTextAlignment;
public NProperty Icon { get { return _icon ?? (_icon = NPropFactories.CreateIcon()); } }
NProperty _icon;
public NProperty Image { get { return _image ?? (_image = NPropFactories.CreateImage()); } }
NProperty _image;
public NProperty Increment { get { return _increment ?? (_increment = NPropFactories.CreateIncrement()); } }
NProperty _increment;
public NProperty InputTransparent { get { return _inputTransparent ?? (_inputTransparent = NPropFactories.CreateInputTransparent()); } }
NProperty _inputTransparent;
public NProperty Intent { get { return _intent ?? (_intent = NPropFactories.CreateIntent()); } }
NProperty _intent;
public NProperty IsBusy { get { return _isBusy ?? (_isBusy = NPropFactories.CreateIsBusy()); } }
NProperty _isBusy;
public NProperty IsClippedToBounds { get { return _isClippedToBounds ?? (_isClippedToBounds = NPropFactories.CreateIsClippedToBounds()); } }
NProperty _isClippedToBounds;
public NProperty IsEnabled { get { return _isEnabled ?? (_isEnabled = NPropFactories.CreateIsEnabled()); } }
NProperty _isEnabled;
public NProperty IsGestureEnabled { get { return _isGestureEnabled ?? (_isGestureEnabled = NPropFactories.CreateIsGestureEnabled()); } }
NProperty _isGestureEnabled;
public NProperty IsOpaque { get { return _isOpaque ?? (_isOpaque = NPropFactories.CreateIsOpaque()); } }
NProperty _isOpaque;
public NProperty IsPassword { get { return _isPassword ?? (_isPassword = NPropFactories.CreateIsPassword()); } }
NProperty _isPassword;
public NProperty IsPresented { get { return _isPresented ?? (_isPresented = NPropFactories.CreateIsPresented()); } }
NProperty _isPresented;
public NProperty IsPresentedChanged { get { return _isPresentedChanged ?? (_isPresentedChanged = NPropFactories.CreateIsPresentedChanged()); } }
NProperty _isPresentedChanged;
public NProperty IsRunning { get { return _isRunning ?? (_isRunning = NPropFactories.CreateIsRunning()); } }
NProperty _isRunning;
public NProperty IsToggled { get { return _isToggled ?? (_isToggled = NPropFactories.CreateIsToggled()); } }
NProperty _isToggled;
public NProperty IsVisible { get { return _isVisible ?? (_isVisible = NPropFactories.CreateIsVisible()); } }
NProperty _isVisible;
public NProperty Keyboard { get { return _keyboard ?? (_keyboard = NPropFactories.CreateKeyboard()); } }
NProperty _keyboard;
public NProperty LayoutChanged { get { return _layoutChanged ?? (_layoutChanged = NPropFactories.CreateLayoutChanged()); } }
NProperty _layoutChanged;
public NProperty LineBreakMode { get { return _lineBreakMode ?? (_lineBreakMode = NPropFactories.CreateLineBreakMode()); } }
NProperty _lineBreakMode;
public NProperty MasterBehavior { get { return _masterBehavior ?? (_masterBehavior = NPropFactories.CreateMasterBehavior()); } }
NProperty _masterBehavior;
public NProperty Maximum { get { return _maximum ?? (_maximum = NPropFactories.CreateMaximum()); } }
NProperty _maximum;
public NProperty MaximumDate { get { return _maximumDate ?? (_maximumDate = NPropFactories.CreateMaximumDate()); } }
NProperty _maximumDate;
public NProperty MeasureInvalidated { get { return _measureInvalidated ?? (_measureInvalidated = NPropFactories.CreateMeasureInvalidated()); } }
NProperty _measureInvalidated;
public NProperty Minimum { get { return _minimum ?? (_minimum = NPropFactories.CreateMinimum()); } }
NProperty _minimum;
public NProperty MinimumDate { get { return _minimumDate ?? (_minimumDate = NPropFactories.CreateMinimumDate()); } }
NProperty _minimumDate;
public NProperty MinimumHeightRequest { get { return _minimumHeightRequest ?? (_minimumHeightRequest = NPropFactories.CreateMinimumHeightRequest()); } }
NProperty _minimumHeightRequest;
public NProperty MinimumWidthRequest { get { return _minimumWidthRequest ?? (_minimumWidthRequest = NPropFactories.CreateMinimumWidthRequest()); } }
NProperty _minimumWidthRequest;
public NProperty Navigated { get { return _navigated ?? (_navigated = NPropFactories.CreateNavigated()); } }
NProperty _navigated;
public NProperty Navigating { get { return _navigating ?? (_navigating = NPropFactories.CreateNavigating()); } }
NProperty _navigating;
public NProperty NavigationPageBackButtonTitle { get { return _navigationPageBackButtonTitle ?? (_navigationPageBackButtonTitle = NPropFactories.CreateNavigationPageBackButtonTitle()); } }
NProperty _navigationPageBackButtonTitle;
public NProperty NavigationPageHasBackButton { get { return _navigationPageHasBackButton ?? (_navigationPageHasBackButton = NPropFactories.CreateNavigationPageHasBackButton()); } }
NProperty _navigationPageHasBackButton;
public NProperty NavigationPageHasNavigationBar { get { return _navigationPageHasNavigationBar ?? (_navigationPageHasNavigationBar = NPropFactories.CreateNavigationPageHasNavigationBar()); } }
NProperty _navigationPageHasNavigationBar;
public NProperty NavigationPageTitleIcon { get { return _navigationPageTitleIcon ?? (_navigationPageTitleIcon = NPropFactories.CreateNavigationPageTitleIcon()); } }
NProperty _navigationPageTitleIcon;
public NProperty Opacity { get { return _opacity ?? (_opacity = NPropFactories.CreateOpacity()); } }
NProperty _opacity;
public NProperty Orientation { get { return _orientation ?? (_orientation = NPropFactories.CreateOrientation()); } }
NProperty _orientation;
public NProperty OutlineColor { get { return _outlineColor ?? (_outlineColor = NPropFactories.CreateOutlineColor()); } }
NProperty _outlineColor;
public NProperty Padding { get { return _padding ?? (_padding = NPropFactories.CreatePadding()); } }
NProperty _padding;
public NProperty Placeholder { get { return _placeholder ?? (_placeholder = NPropFactories.CreatePlaceholder()); } }
NProperty _placeholder;
public NProperty PlaceholderColor { get { return _placeholderColor ?? (_placeholderColor = NPropFactories.CreatePlaceholderColor()); } }
NProperty _placeholderColor;
public NProperty Popped { get { return _popped ?? (_popped = NPropFactories.CreatePopped()); } }
NProperty _popped;
public NProperty PoppedToRoot { get { return _poppedToRoot ?? (_poppedToRoot = NPropFactories.CreatePoppedToRoot()); } }
NProperty _poppedToRoot;
public NProperty Progress { get { return _progress ?? (_progress = NPropFactories.CreateProgress()); } }
NProperty _progress;
public NProperty Pushed { get { return _pushed ?? (_pushed = NPropFactories.CreatePushed()); } }
NProperty _pushed;
public NProperty Root { get { return _root ?? (_root = NPropFactories.CreateRoot()); } }
NProperty _root;
public NProperty Rotation { get { return _rotation ?? (_rotation = NPropFactories.CreateRotation()); } }
NProperty _rotation;
public NProperty RotationX { get { return _rotationX ?? (_rotationX = NPropFactories.CreateRotationX()); } }
NProperty _rotationX;
public NProperty RotationY { get { return _rotationY ?? (_rotationY = NPropFactories.CreateRotationY()); } }
NProperty _rotationY;
public NProperty RowHeight { get { return _rowHeight ?? (_rowHeight = NPropFactories.CreateRowHeight()); } }
NProperty _rowHeight;
public NProperty Scale { get { return _scale ?? (_scale = NPropFactories.CreateScale()); } }
NProperty _scale;
public NProperty Scrolled { get { return _scrolled ?? (_scrolled = NPropFactories.CreateScrolled()); } }
NProperty _scrolled;
public NProperty SearchButtonPressed { get { return _searchButtonPressed ?? (_searchButtonPressed = NPropFactories.CreateSearchButtonPressed()); } }
NProperty _searchButtonPressed;
public NProperty SearchCommand { get { return _searchCommand ?? (_searchCommand = NPropFactories.CreateSearchCommand()); } }
NProperty _searchCommand;
public NProperty SearchCommandParameter { get { return _searchCommandParameter ?? (_searchCommandParameter = NPropFactories.CreateSearchCommandParameter()); } }
NProperty _searchCommandParameter;
public NProperty SelectedIndex { get { return _selectedIndex ?? (_selectedIndex = NPropFactories.CreateSelectedIndex()); } }
NProperty _selectedIndex;
public NProperty SelectedIndexChanged { get { return _selectedIndexChanged ?? (_selectedIndexChanged = NPropFactories.CreateSelectedIndexChanged()); } }
NProperty _selectedIndexChanged;
public NProperty SizeChanged { get { return _sizeChanged ?? (_sizeChanged = NPropFactories.CreateSizeChanged()); } }
NProperty _sizeChanged;
public NProperty Source { get { return _source ?? (_source = NPropFactories.CreateSource()); } }
NProperty _source;
public NProperty Style { get { return _style ?? (_style = NPropFactories.CreateStyle()); } }
NProperty _style;
public NProperty Text { get { return _text ?? (_text = NPropFactories.CreateText()); } }
NProperty _text;
public NProperty TextChanged { get { return _textChanged ?? (_textChanged = NPropFactories.CreateTextChanged()); } }
NProperty _textChanged;
public NProperty TextColor { get { return _textColor ?? (_textColor = NPropFactories.CreateTextColor()); } }
NProperty _textColor;
public NProperty Time { get { return _time ?? (_time = NPropFactories.CreateTime()); } }
NProperty _time;
public NProperty Tint { get { return _tint ?? (_tint = NPropFactories.CreateTint()); } }
NProperty _tint;
public NProperty Title { get { return _title ?? (_title = NPropFactories.CreateTitle()); } }
NProperty _title;
public NProperty Toggled { get { return _toggled ?? (_toggled = NPropFactories.CreateToggled()); } }
NProperty _toggled;
public NProperty TranslationX { get { return _translationX ?? (_translationX = NPropFactories.CreateTranslationX()); } }
NProperty _translationX;
public NProperty TranslationY { get { return _translationY ?? (_translationY = NPropFactories.CreateTranslationY()); } }
NProperty _translationY;
public NProperty Unfocused { get { return _unfocused ?? (_unfocused = NPropFactories.CreateUnfocused()); } }
NProperty _unfocused;
public NProperty Value { get { return _value ?? (_value = NPropFactories.CreateValue()); } }
NProperty _value;
public NProperty ValueChanged { get { return _valueChanged ?? (_valueChanged = NPropFactories.CreateValueChanged()); } }
NProperty _valueChanged;
public NProperty VerticalOptions { get { return _verticalOptions ?? (_verticalOptions = NPropFactories.CreateVerticalOptions()); } }
NProperty _verticalOptions;
public NProperty VerticalTextAlignment { get { return _verticalTextAlignment ?? (_verticalTextAlignment = NPropFactories.CreateVerticalTextAlignment()); } }
NProperty _verticalTextAlignment;
public NProperty WidthRequest { get { return _widthRequest ?? (_widthRequest = NPropFactories.CreateWidthRequest()); } }
NProperty _widthRequest;
public NProperty XAlign { get { return _xAlign ?? (_xAlign = NPropFactories.CreateXAlign()); } }
NProperty _xAlign;
public NProperty YAlign { get { return _yAlign ?? (_yAlign = NPropFactories.CreateYAlign()); } }
NProperty _yAlign;
}
static partial class NPropFactories
{
public static NProperty CreateAnchorX() => new NProperty(nameof(NProperties.AnchorX)).
Property<VisualElement>(VisualElement.AnchorXProperty, NConverters.ToDouble);
public static NProperty CreateAnchorY() => new NProperty(nameof(NProperties.AnchorY)).
Property<VisualElement>(VisualElement.AnchorYProperty, NConverters.ToDouble);
public static NProperty CreateAppearing() => new NProperty(nameof(NProperties.Appearing)).
Event<Page>((s, a) => s.Appearing += a.EventHandler);
public static NProperty CreateAspect() => new NProperty(nameof(NProperties.Aspect)).
Property<Image>(Image.AspectProperty, NConverters.ToEnum<Aspect>);
public static NProperty CreateBackgroundColor() => new NProperty(nameof(NProperties.BackgroundColor)).
Property<VisualElement>(VisualElement.BackgroundColorProperty);
public static NProperty CreateBackgroundImage() => new NProperty(nameof(NProperties.BackgroundImage)).
Property<Page>(Page.BackgroundImageProperty, NConverters.ToString);
public static NProperty CreateBarBackgroundColor() => new NProperty(nameof(NProperties.BarBackgroundColor)).
Property<NavigationPage>(NavigationPage.BarBackgroundColorProperty);
public static NProperty CreateBarTextColor() => new NProperty(nameof(NProperties.BarTextColor)).
Property<NavigationPage>(NavigationPage.BarTextColorProperty);
public static NProperty CreateBorderColor() => new NProperty(nameof(NProperties.BorderColor)).
Property<Button>(Button.BorderColorProperty);
public static NProperty CreateBorderRadius() => new NProperty(nameof(NProperties.BorderRadius)).
Property<Button>(Button.BorderRadiusProperty, NConverters.ToInt32);
public static NProperty CreateBorderWidth() => new NProperty(nameof(NProperties.BorderWidth)).
Property<Button>(Button.BorderWidthProperty, NConverters.ToDouble);
public static NProperty CreateCancelButtonColor() => new NProperty(nameof(NProperties.CancelButtonColor)).
Property<SearchBar>(SearchBar.CancelButtonColorProperty);
public static NProperty CreateChild() => new NProperty(nameof(NProperties.Child));
public static NProperty CreateChildren() => new NProperty(nameof(NProperties.Children));
public static NProperty CreateChildrenReordered() => new NProperty(nameof(NProperties.ChildrenReordered)).
Event<VisualElement>((s, a) => s.ChildrenReordered += a.EventHandler);
public static NProperty CreateClicked() => new NProperty(nameof(NProperties.Clicked)).
Event<Button>((s, a) => s.Clicked += a.EventHandler);
public static NProperty CreateColor() => new NProperty(nameof(NProperties.Color)).
Property<ActivityIndicator>(ActivityIndicator.ColorProperty).
Property<BoxView>(BoxView.ColorProperty);
public static NProperty CreateCommand() => new NProperty(nameof(NProperties.Command)).
Property<Button>(Button.CommandProperty);
public static NProperty CreateCommandParameter() => new NProperty(nameof(NProperties.CommandParameter)).
Property<Button>(Button.CommandParameterProperty);
public static NProperty CreateCompleted() => new NProperty(nameof(NProperties.Completed)).
Event<Editor>((s, a) => s.Completed += a.EventHandler).
Event<Entry>((s, a) => s.Completed += a.EventHandler);
public static NProperty CreateContent() => new NProperty(nameof(NProperties.Content)).
Property<ContentPresenter>(ContentPresenter.ContentProperty).
Property<ContentView>(ContentView.ContentProperty).
Property<ContentPage>(ContentPage.ContentProperty);
public static NProperty CreateControlTemplate() => new NProperty(nameof(NProperties.ControlTemplate)).
Property<TemplatedView>(TemplatedView.ControlTemplateProperty).
Property<TemplatedPage>(TemplatedPage.ControlTemplateProperty);
public static NProperty CreateDate() => new NProperty(nameof(NProperties.Date)).
Property<DatePicker>(DatePicker.DateProperty);
public static NProperty CreateDateSelected() => new NProperty(nameof(NProperties.DateSelected)).
Event<DatePicker>((s, a) => s.DateSelected += a.EventHandler);
public static NProperty CreateDisappearing() => new NProperty(nameof(NProperties.Disappearing)).
Event<Page>((s, a) => s.Disappearing += a.EventHandler);
public static NProperty CreateFocused() => new NProperty(nameof(NProperties.Focused)).
Event<VisualElement>((s, a) => s.Focused += a.EventHandler);
public static NProperty CreateFont() => new NProperty(nameof(NProperties.Font)).
Property<Button>(Button.FontProperty).
Property<Label>(Label.FontProperty);
public static NProperty CreateFontAttributes() => new NProperty(nameof(NProperties.FontAttributes)).
Property<Button>(Button.FontAttributesProperty, NConverters.ToEnum<FontAttributes>).
Property<Editor>(Editor.FontAttributesProperty, NConverters.ToEnum<FontAttributes>).
Property<Entry>(Entry.FontAttributesProperty, NConverters.ToEnum<FontAttributes>).
Property<Label>(Label.FontAttributesProperty, NConverters.ToEnum<FontAttributes>).
Property<SearchBar>(SearchBar.FontAttributesProperty, NConverters.ToEnum<FontAttributes>);
public static NProperty CreateFontFamily() => new NProperty(nameof(NProperties.FontFamily)).
Property<Button>(Button.FontFamilyProperty, NConverters.ToString).
Property<Editor>(Editor.FontFamilyProperty, NConverters.ToString).
Property<Entry>(Entry.FontFamilyProperty, NConverters.ToString).
Property<Label>(Label.FontFamilyProperty, NConverters.ToString).
Property<SearchBar>(SearchBar.FontFamilyProperty, NConverters.ToString);
public static NProperty CreateFontSize() => new NProperty(nameof(NProperties.FontSize)).
Property<Button>(Button.FontSizeProperty, NConverters.ToDouble).
Property<Editor>(Editor.FontSizeProperty, NConverters.ToDouble).
Property<Entry>(Entry.FontSizeProperty, NConverters.ToDouble).
Property<Label>(Label.FontSizeProperty, NConverters.ToDouble).
Property<SearchBar>(SearchBar.FontSizeProperty, NConverters.ToDouble);
public static NProperty CreateFormat() => new NProperty(nameof(NProperties.Format)).
Property<DatePicker>(DatePicker.FormatProperty, NConverters.ToString).
Property<TimePicker>(TimePicker.FormatProperty, NConverters.ToString);
public static NProperty CreateFormattedText() => new NProperty(nameof(NProperties.FormattedText)).
Property<Label>(Label.FormattedTextProperty);
public static NProperty CreateHasRenderLoop() => new NProperty(nameof(NProperties.HasRenderLoop)).
Property<OpenGLView>(OpenGLView.HasRenderLoopProperty, NConverters.ToBool);
public static NProperty CreateHasShadow() => new NProperty(nameof(NProperties.HasShadow)).
Property<Frame>(Frame.HasShadowProperty, NConverters.ToBool);
public static NProperty CreateHasUnevenRows() => new NProperty(nameof(NProperties.HasUnevenRows)).
Property<TableView>(TableView.HasUnevenRowsProperty, NConverters.ToBool);
public static NProperty CreateHeightRequest() => new NProperty(nameof(NProperties.HeightRequest)).
Property<VisualElement>(VisualElement.HeightRequestProperty, NConverters.ToDouble);
public static NProperty CreateHorizontalOptions() => new NProperty(nameof(NProperties.HorizontalOptions)).
Property<View>(View.HorizontalOptionsProperty);
public static NProperty CreateHorizontalTextAlignment() => new NProperty(nameof(NProperties.HorizontalTextAlignment)).
Property<Entry>(Entry.HorizontalTextAlignmentProperty, NConverters.ToEnum<TextAlignment>).
Property<Label>(Label.HorizontalTextAlignmentProperty, NConverters.ToEnum<TextAlignment>).
Property<SearchBar>(SearchBar.HorizontalTextAlignmentProperty, NConverters.ToEnum<TextAlignment>);
public static NProperty CreateIcon() => new NProperty(nameof(NProperties.Icon)).
Property<Page>(Page.IconProperty);
public static NProperty CreateImage() => new NProperty(nameof(NProperties.Image)).
Property<Button>(Button.ImageProperty);
public static NProperty CreateIncrement() => new NProperty(nameof(NProperties.Increment)).
Property<Stepper>(Stepper.IncrementProperty, NConverters.ToDouble);
public static NProperty CreateInputTransparent() => new NProperty(nameof(NProperties.InputTransparent)).
Property<VisualElement>(VisualElement.InputTransparentProperty, NConverters.ToBool);
public static NProperty CreateIntent() => new NProperty(nameof(NProperties.Intent)).
Property<TableView>((t, v) => t.Intent = NConverters.ToEnumT<TableIntent>(v));
public static NProperty CreateIsBusy() => new NProperty(nameof(NProperties.IsBusy)).
Property<Page>(Page.IsBusyProperty, NConverters.ToBool);
public static NProperty CreateIsClippedToBounds() => new NProperty(nameof(NProperties.IsClippedToBounds)).
Property<Layout>(Layout.IsClippedToBoundsProperty, NConverters.ToBool);
public static NProperty CreateIsEnabled() => new NProperty(nameof(NProperties.IsEnabled)).
Property<VisualElement>(VisualElement.IsEnabledProperty, NConverters.ToBool);
public static NProperty CreateIsGestureEnabled() => new NProperty(nameof(NProperties.IsGestureEnabled)).
Property<MasterDetailPage>(MasterDetailPage.IsGestureEnabledProperty, NConverters.ToBool);
public static NProperty CreateIsOpaque() => new NProperty(nameof(NProperties.IsOpaque)).
Property<Image>(Image.IsOpaqueProperty, NConverters.ToBool);
public static NProperty CreateIsPassword() => new NProperty(nameof(NProperties.IsPassword)).
Property<Entry>(Entry.IsPasswordProperty, NConverters.ToBool);
public static NProperty CreateIsPresented() => new NProperty(nameof(NProperties.IsPresented)).
Property<MasterDetailPage>(MasterDetailPage.IsPresentedProperty, NConverters.ToBool);
public static NProperty CreateIsPresentedChanged() => new NProperty(nameof(NProperties.IsPresentedChanged)).
Event<MasterDetailPage>((s, a) => s.IsPresentedChanged += a.EventHandler);
public static NProperty CreateIsRunning() => new NProperty(nameof(NProperties.IsRunning)).
Property<ActivityIndicator>(ActivityIndicator.IsRunningProperty, NConverters.ToBool);
public static NProperty CreateIsToggled() => new NProperty(nameof(NProperties.IsToggled)).
Property<Switch>(Switch.IsToggledProperty, NConverters.ToBool);
public static NProperty CreateIsVisible() => new NProperty(nameof(NProperties.IsVisible)).
Property<VisualElement>(VisualElement.IsVisibleProperty, NConverters.ToBool);
public static NProperty CreateKeyboard() => new NProperty(nameof(NProperties.Keyboard)).
Property<InputView>(InputView.KeyboardProperty);
public static NProperty CreateLayoutChanged() => new NProperty(nameof(NProperties.LayoutChanged)).
Event<Layout>((s, a) => s.LayoutChanged += a.EventHandler).
Event<Page>((s, a) => s.LayoutChanged += a.EventHandler);
public static NProperty CreateLineBreakMode() => new NProperty(nameof(NProperties.LineBreakMode)).
Property<Label>(Label.LineBreakModeProperty, NConverters.ToEnum<LineBreakMode>);
public static NProperty CreateMasterBehavior() => new NProperty(nameof(NProperties.MasterBehavior)).
Property<MasterDetailPage>(MasterDetailPage.MasterBehaviorProperty, NConverters.ToEnum<MasterBehavior>);
public static NProperty CreateMaximum() => new NProperty(nameof(NProperties.Maximum)).
Property<Slider>(Slider.MaximumProperty, NConverters.ToDouble).
Property<Stepper>(Stepper.MaximumProperty, NConverters.ToDouble);
public static NProperty CreateMaximumDate() => new NProperty(nameof(NProperties.MaximumDate)).
Property<DatePicker>(DatePicker.MaximumDateProperty);
public static NProperty CreateMeasureInvalidated() => new NProperty(nameof(NProperties.MeasureInvalidated)).
Event<VisualElement>((s, a) => s.MeasureInvalidated += a.EventHandler);
public static NProperty CreateMinimum() => new NProperty(nameof(NProperties.Minimum)).
Property<Slider>(Slider.MinimumProperty, NConverters.ToDouble).
Property<Stepper>(Stepper.MinimumProperty, NConverters.ToDouble);
public static NProperty CreateMinimumDate() => new NProperty(nameof(NProperties.MinimumDate)).
Property<DatePicker>(DatePicker.MinimumDateProperty);
public static NProperty CreateMinimumHeightRequest() => new NProperty(nameof(NProperties.MinimumHeightRequest)).
Property<VisualElement>(VisualElement.MinimumHeightRequestProperty, NConverters.ToDouble);
public static NProperty CreateMinimumWidthRequest() => new NProperty(nameof(NProperties.MinimumWidthRequest)).
Property<VisualElement>(VisualElement.MinimumWidthRequestProperty, NConverters.ToDouble);
public static NProperty CreateNavigated() => new NProperty(nameof(NProperties.Navigated)).
Event<WebView>((s, a) => s.Navigated += a.EventHandler);
public static NProperty CreateNavigating() => new NProperty(nameof(NProperties.Navigating)).
Event<WebView>((s, a) => s.Navigating += a.EventHandler);
public static NProperty CreateNavigationPageBackButtonTitle() => new NProperty(nameof(NProperties.NavigationPageBackButtonTitle)).
Property<BindableObject>(NavigationPage.BackButtonTitleProperty, NConverters.ToString);
public static NProperty CreateNavigationPageHasBackButton() => new NProperty(nameof(NProperties.NavigationPageHasBackButton)).
Property<Page>(NavigationPage.HasBackButtonProperty, NConverters.ToBool);
public static NProperty CreateNavigationPageHasNavigationBar() => new NProperty(nameof(NProperties.NavigationPageHasNavigationBar)).
Property<BindableObject>(NavigationPage.HasNavigationBarProperty, NConverters.ToBool);
public static NProperty CreateNavigationPageTitleIcon() => new NProperty(nameof(NProperties.NavigationPageTitleIcon)).
Property<BindableObject>(NavigationPage.TitleIconProperty);
public static NProperty CreateOpacity() => new NProperty(nameof(NProperties.Opacity)).
Property<VisualElement>(VisualElement.OpacityProperty, NConverters.ToDouble);
public static NProperty CreateOrientation() => new NProperty(nameof(NProperties.Orientation)).
Property<ScrollView>(ScrollView.OrientationProperty, NConverters.ToEnum<ScrollOrientation>);
public static NProperty CreateOutlineColor() => new NProperty(nameof(NProperties.OutlineColor)).
Property<Frame>(Frame.OutlineColorProperty);
public static NProperty CreatePadding() => new NProperty(nameof(NProperties.Padding)).
Property<Layout>(Layout.PaddingProperty).
Property<Page>(Page.PaddingProperty);
public static NProperty CreatePlaceholder() => new NProperty(nameof(NProperties.Placeholder)).
Property<Entry>(Entry.PlaceholderProperty, NConverters.ToString).
Property<SearchBar>(SearchBar.PlaceholderProperty, NConverters.ToString);
public static NProperty CreatePlaceholderColor() => new NProperty(nameof(NProperties.PlaceholderColor)).
Property<Entry>(Entry.PlaceholderColorProperty).
Property<SearchBar>(SearchBar.PlaceholderColorProperty);
public static NProperty CreatePopped() => new NProperty(nameof(NProperties.Popped)).
Event<NavigationPage>((s, a) => s.Popped += a.EventHandler);
public static NProperty CreatePoppedToRoot() => new NProperty(nameof(NProperties.PoppedToRoot)).
Event<NavigationPage>((s, a) => s.PoppedToRoot += a.EventHandler);
public static NProperty CreateProgress() => new NProperty(nameof(NProperties.Progress)).
Property<ProgressBar>(ProgressBar.ProgressProperty, NConverters.ToDouble);
public static NProperty CreatePushed() => new NProperty(nameof(NProperties.Pushed)).
Event<NavigationPage>((s, a) => s.Pushed += a.EventHandler);
public static NProperty CreateRoot() => new NProperty(nameof(NProperties.Root)).
Property<TableView>((t, v) => NPatch.AssignListT(t.Root, v));
public static NProperty CreateRotation() => new NProperty(nameof(NProperties.Rotation)).
Property<VisualElement>(VisualElement.RotationProperty, NConverters.ToDouble);
public static NProperty CreateRotationX() => new NProperty(nameof(NProperties.RotationX)).
Property<VisualElement>(VisualElement.RotationXProperty, NConverters.ToDouble);
public static NProperty CreateRotationY() => new NProperty(nameof(NProperties.RotationY)).
Property<VisualElement>(VisualElement.RotationYProperty, NConverters.ToDouble);
public static NProperty CreateRowHeight() => new NProperty(nameof(NProperties.RowHeight)).
Property<TableView>(TableView.RowHeightProperty, NConverters.ToInt32);
public static NProperty CreateScale() => new NProperty(nameof(NProperties.Scale)).
Property<VisualElement>(VisualElement.ScaleProperty, NConverters.ToDouble);
public static NProperty CreateScrolled() => new NProperty(nameof(NProperties.Scrolled)).
Event<ScrollView>((s, a) => s.Scrolled += a.EventHandler);
public static NProperty CreateSearchButtonPressed() => new NProperty(nameof(NProperties.SearchButtonPressed)).
Event<SearchBar>((s, a) => s.SearchButtonPressed += a.EventHandler);
public static NProperty CreateSearchCommand() => new NProperty(nameof(NProperties.SearchCommand)).
Property<SearchBar>(SearchBar.SearchCommandProperty);
public static NProperty CreateSearchCommandParameter() => new NProperty(nameof(NProperties.SearchCommandParameter)).
Property<SearchBar>(SearchBar.SearchCommandParameterProperty);
public static NProperty CreateSelectedIndex() => new NProperty(nameof(NProperties.SelectedIndex)).
Property<Picker>(Picker.SelectedIndexProperty, NConverters.ToInt32);
public static NProperty CreateSelectedIndexChanged() => new NProperty(nameof(NProperties.SelectedIndexChanged)).
Event<Picker>((s, a) => s.SelectedIndexChanged += a.EventHandler);
public static NProperty CreateSizeChanged() => new NProperty(nameof(NProperties.SizeChanged)).
Event<VisualElement>((s, a) => s.SizeChanged += a.EventHandler);
public static NProperty CreateSource() => new NProperty(nameof(NProperties.Source)).
Property<Image>(Image.SourceProperty).
Property<WebView>(WebView.SourceProperty);
public static NProperty CreateStyle() => new NProperty(nameof(NProperties.Style)).
Property<VisualElement>(VisualElement.StyleProperty);
public static NProperty CreateText() => new NProperty(nameof(NProperties.Text)).
Property<Button>(Button.TextProperty, NConverters.ToString).
Property<Editor>(Editor.TextProperty, NConverters.ToString).
Property<Entry>(Entry.TextProperty, NConverters.ToString).
Property<Label>(Label.TextProperty, NConverters.ToString).
Property<SearchBar>(SearchBar.TextProperty, NConverters.ToString);
public static NProperty CreateTextChanged() => new NProperty(nameof(NProperties.TextChanged)).
Event<Editor>((s, a) => s.TextChanged += a.EventHandler).
Event<Entry>((s, a) => s.TextChanged += a.EventHandler).
Event<SearchBar>((s, a) => s.TextChanged += a.EventHandler);
public static NProperty CreateTextColor() => new NProperty(nameof(NProperties.TextColor)).
Property<Button>(Button.TextColorProperty).
Property<Editor>(Editor.TextColorProperty).
Property<Entry>(Entry.TextColorProperty).
Property<Label>(Label.TextColorProperty).
Property<SearchBar>(SearchBar.TextColorProperty);
public static NProperty CreateTime() => new NProperty(nameof(NProperties.Time)).
Property<TimePicker>(TimePicker.TimeProperty, NConverters.ToTimeSpan);
public static NProperty CreateTint() => new NProperty(nameof(NProperties.Tint)).
Property<NavigationPage>(NavigationPage.TintProperty);
public static NProperty CreateTitle() => new NProperty(nameof(NProperties.Title)).
Property<Picker>(Picker.TitleProperty, NConverters.ToString).
Property<Page>(Page.TitleProperty, NConverters.ToString);
public static NProperty CreateToggled() => new NProperty(nameof(NProperties.Toggled)).
Event<Switch>((s, a) => s.Toggled += a.EventHandler);
public static NProperty CreateTranslationX() => new NProperty(nameof(NProperties.TranslationX)).
Property<VisualElement>(VisualElement.TranslationXProperty, NConverters.ToDouble);
public static NProperty CreateTranslationY() => new NProperty(nameof(NProperties.TranslationY)).
Property<VisualElement>(VisualElement.TranslationYProperty, NConverters.ToDouble);
public static NProperty CreateUnfocused() => new NProperty(nameof(NProperties.Unfocused)).
Event<VisualElement>((s, a) => s.Unfocused += a.EventHandler);
public static NProperty CreateValue() => new NProperty(nameof(NProperties.Value)).
Property<Slider>(Slider.ValueProperty, NConverters.ToDouble).
Property<Stepper>(Stepper.ValueProperty, NConverters.ToDouble);
public static NProperty CreateValueChanged() => new NProperty(nameof(NProperties.ValueChanged)).
Event<Slider>((s, a) => s.ValueChanged += a.EventHandler).
Event<Stepper>((s, a) => s.ValueChanged += a.EventHandler);
public static NProperty CreateVerticalOptions() => new NProperty(nameof(NProperties.VerticalOptions)).
Property<View>(View.VerticalOptionsProperty);
public static NProperty CreateVerticalTextAlignment() => new NProperty(nameof(NProperties.VerticalTextAlignment)).
Property<Label>(Label.VerticalTextAlignmentProperty, NConverters.ToEnum<TextAlignment>);
public static NProperty CreateWidthRequest() => new NProperty(nameof(NProperties.WidthRequest)).
Property<VisualElement>(VisualElement.WidthRequestProperty, NConverters.ToDouble);
public static NProperty CreateXAlign() => new NProperty(nameof(NProperties.XAlign)).
Property<Label>(Label.XAlignProperty, NConverters.ToEnum<TextAlignment>);
public static NProperty CreateYAlign() => new NProperty(nameof(NProperties.YAlign)).
Property<Label>(Label.YAlignProperty, NConverters.ToEnum<TextAlignment>);
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.IpMessaging.V2.Service
{
/// <summary>
/// FetchUserOptions
/// </summary>
public class FetchUserOptions : IOptions<UserResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchUserOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
public FetchUserOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// DeleteUserOptions
/// </summary>
public class DeleteUserOptions : IOptions<UserResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteUserOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
public DeleteUserOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// CreateUserOptions
/// </summary>
public class CreateUserOptions : IOptions<UserResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The identity
/// </summary>
public string Identity { get; }
/// <summary>
/// The role_sid
/// </summary>
public string RoleSid { get; set; }
/// <summary>
/// The attributes
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The friendly_name
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public UserResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new CreateUserOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="identity"> The identity </param>
public CreateUserOptions(string pathServiceSid, string identity)
{
PathServiceSid = pathServiceSid;
Identity = identity;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Identity != null)
{
p.Add(new KeyValuePair<string, string>("Identity", Identity));
}
if (RoleSid != null)
{
p.Add(new KeyValuePair<string, string>("RoleSid", RoleSid.ToString()));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// ReadUserOptions
/// </summary>
public class ReadUserOptions : ReadOptions<UserResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// Construct a new ReadUserOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
public ReadUserOptions(string pathServiceSid)
{
PathServiceSid = pathServiceSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// UpdateUserOptions
/// </summary>
public class UpdateUserOptions : IOptions<UserResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// The role_sid
/// </summary>
public string RoleSid { get; set; }
/// <summary>
/// The attributes
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The friendly_name
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public UserResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new UpdateUserOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
public UpdateUserOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (RoleSid != null)
{
p.Add(new KeyValuePair<string, string>("RoleSid", RoleSid.ToString()));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime
{
internal abstract class AsynchQueueAgent<T> : AsynchAgent, IDisposable where T : IOutgoingMessage
{
private readonly IMessagingConfiguration config;
private RuntimeQueue<T> requestQueue;
private QueueTrackingStatistic queueTracking;
protected AsynchQueueAgent(string nameSuffix, IMessagingConfiguration cfg)
: base(nameSuffix)
{
config = cfg;
requestQueue = new RuntimeQueue<T>();
if (StatisticsCollector.CollectQueueStats)
{
queueTracking = new QueueTrackingStatistic(base.Name);
}
}
public void QueueRequest(T request)
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnEnQueueRequest(1, requestQueue.Count, request);
}
#endif
requestQueue.Add(request);
}
protected abstract void Process(T request);
protected abstract void ProcessBatch(List<T> requests);
protected override void Run()
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStartExecution();
queueTracking.OnStartExecution();
}
#endif
try
{
if (config.UseMessageBatching)
{
RunBatching();
}
else
{
RunNonBatching();
}
}
finally
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStopExecution();
queueTracking.OnStopExecution();
}
#endif
}
}
protected void RunNonBatching()
{
while (true)
{
if (Cts.IsCancellationRequested)
{
return;
}
T request;
try
{
request = requestQueue.Take();
}
catch (InvalidOperationException)
{
Log.Info(ErrorCode.Runtime_Error_100312, "Stop request processed");
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnDeQueueRequest(request);
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStartProcessing();
}
#endif
Process(request);
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStopProcessing();
threadTracking.IncrementNumberOfProcessed();
}
#endif
}
}
protected void RunBatching()
{
int maxBatchingSize = config.MaxMessageBatchingSize;
while (true)
{
if (Cts.IsCancellationRequested)
{
return;
}
var mlist = new List<T>();
try
{
T firstRequest = requestQueue.Take();
mlist.Add(firstRequest);
while (requestQueue.Count != 0 && mlist.Count < maxBatchingSize &&
requestQueue.First().IsSameDestination(firstRequest))
{
mlist.Add(requestQueue.Take());
}
}
catch (InvalidOperationException)
{
Log.Info(ErrorCode.Runtime_Error_100312, "Stop request processed");
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
foreach (var request in mlist)
{
queueTracking.OnDeQueueRequest(request);
}
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStartProcessing();
}
#endif
ProcessBatch(mlist);
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStopProcessing();
threadTracking.IncrementNumberOfProcessed(mlist.Count);
}
#endif
}
}
public override void Stop()
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStopExecution();
}
#endif
requestQueue.CompleteAdding();
base.Stop();
}
public virtual int Count
{
get
{
return requestQueue.Count;
}
}
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (!disposing) return;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStopExecution();
}
#endif
base.Dispose(disposing);
if (requestQueue != null)
{
requestQueue.Dispose();
requestQueue = null;
}
}
#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 SearchCTC.WebAPI.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;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
namespace Zeltex.Voxels
{
/* Rooms to have floors
Doors
Chairs
Tables
Lanterns on walls
Bookshelves
Beds
Chains on walls in some places
Prison Cells
Windows
A level of difficulty . they will spawn enemies
A number of floors, as some will be battle towers with big boss at top
*/
/*[System.Serializable]
public class DungeonData {
}*/
// need a gui for this
// right click on maze item - edit maze properties
// use AStar to check the paths between rooms
//[ExecuteInEditMode]
public class Maze : WorldEditor
{
public List<Vector3> DebugPositions = new List<Vector3>();
public List<int> DebugDirections = new List<int> ();
[Header("Actions")]
public bool IsGenerateMaze = false;
// Dungeon Data
[Header("Block Types")]
public int PathBlockType;
public int MazeWallType;
public int MazeRoofType;
[Header("Maze Options")]
public bool IsPaths = true;
static int MaxIterations = 10000;
public Vector3 StartLocation; // start of maze building
public Vector3 SpawnPosition; // spawn point for player
public float Sparceness;
public float Linearity;
public Vector3 PathSizeMinimum;
public Vector3 PathSizeMaximum;
[Header("Maze Additional Options")]
public bool IsMazeRoof;
public bool IsRandomizeStartPosition = false;
public bool IsMiddleStartLocation = false;
public bool bIsGenerateBiome;
public bool IsVoidAxisX;
public bool IsVoidAxisY;
public bool IsVoidAxisZ;
public int MaxSpawnPoints;
public int SpawnBlockType;
public int FloorsMax = 1;
public float MazeWallHeight;
public bool bIsEdge;
public bool bIsRemoveSinglePillars;
public bool bIsMoveToSize;
public bool bIsPathways = true;
public bool bIsWrap;
// Generated maze Data
List<Vector3> SpawnLocations = new List<Vector3>(); // where to spawn bots when level is loaded
private Vector3 Position;
private Vector3 PathSize;
private int Iterations;
private int PathDirection = 0;
private float MaxSparce;
private float SparcePercentage;
private bool IsSparceEnough = false;
[Header("Texture Creation")]
//public GameObject MazeTextureObject;
//public Texture2D MazeTexture;
public int MaxMipMapLevel;
//public RawImage MyRawImage;
public List<Color32> BlockColors = new List<Color32> ();
// getters and setters
public float GetSparcePercent() {return SparcePercentage;}
public void CheckStartLocationInBounds() {
if (FloorsMax < 1)
FloorsMax = 1;
StartLocation = new Vector3 (Mathf.Clamp (StartLocation.x, 0, GetSize().x - 1),
Mathf.Clamp (StartLocation.y, 0, GetSize().y - 1),
Mathf.Clamp (StartLocation.z, 0, GetSize().z - 1));
}
void GenerateDungeon() {
if (IsMiddleStartLocation) {
StartLocation.x = GetSize().x/2f;
StartLocation.z = GetSize().z/2f;
}
CurrentSparce = 0;
if (bIsGenerateBiome) {
GenerateBiomeMap(GetSize());
}
else {
Debug.Log ("Generating ");
//GenerateWallsOnEdge(MyBlocks, Size, MazeWallType);
if (IsPaths && Sparceness > 0)
{
for (int i = 0; i < FloorsMax; i++) {
GeneratePaths(GetSize(),
new Vector3(StartLocation.x, StartLocation.y, StartLocation.z + (MazeWallHeight + 1)*i),
PathBlockType,
Sparceness,
Linearity);
}
}
if (IsMazeRoof)
GeneratePathWalls(PathBlockType,
MazeWallHeight,
MazeWallType,
MazeRoofType);
//RemoveSinglePillars(MyBlocks, Size, PathBlockType);
//GenerateSpawnLocations(MyBlocks, Size);
/*if (IsFillEmpty) {
FillEmptyPath(Size, PathBlockType, MazeWallType);
}*/
}
if (IsRandomizeStartPosition)
FindStartPosition (GetSize());
}
public void FindStartPosition(Int3 Size)
{
for (int i = 0; i < 1000; i++) {
Vector3 CheckPosition = new Vector3(Random.Range (0, Size.x), Random.Range (0, Size.x), Random.Range (0, Size.x));
if (IsVoidAxisX)
CheckPosition.x = StartLocation.x;
if (IsVoidAxisY)
CheckPosition.y = StartLocation.y;
if (IsVoidAxisZ)
CheckPosition.z = StartLocation.z;
if (GetBlockType(CheckPosition.ToInt3()) == PathBlockType
&& GetBlockType(CheckPosition.ToInt3() + new Int3(0,1,0)) == 0)
{
SpawnPosition = CheckPosition + new Vector3(0,1.5f,0);
Debug.Log("Found new position for spawning: " + SpawnPosition.ToString());
break;
}
}
}
void GenerateSpawnLocations(Vector3 Size) {
//MyBlocks.UpdateBlock(StartLocation, SpawnBlockType);
int MaxBotSpawnBlocks = MaxSpawnPoints;
int BotSpawnBlocksCount = 0;
bool bIsBotSpawns = true;
if (bIsBotSpawns) {
while (BotSpawnBlocksCount <= MaxBotSpawnBlocks) {
int i = Mathf.RoundToInt(Random.Range(0f, Size.x-1f));
int j = Mathf.RoundToInt(Random.Range(0f, Size.y-1f));
int k = Mathf.RoundToInt(Random.Range(0f, Size.z-1f));
if (IsVoidAxisZ)
k = (int)StartLocation.z;
if (IsVoidAxisY)
j = (int)StartLocation.y;
if (IsVoidAxisX)
i = (int)StartLocation.x;
if (GetBlockType(new Int3(i, j, k)) == PathBlockType)
{
SpawnLocations.Add (new Vector3(i,j,k));
//MyBlocks.UpdateBlock(new Vector3(i, j, k), SpawnBlockType);
BotSpawnBlocksCount++;
}
}
}
}
public void GenerateWallsOnEdge(int MazeWallType)
{
for (int i = 0; i < GetSize().x; i++)
{
for (int k = 0; k < GetSize().z; k++)
{
if (IsOnEdge(new Vector3(i, StartLocation.y, k), GetSize()) && GetBlockType(new Int3(i, StartLocation.y, k)) == 0)
{
for (int z = 0; z < MazeWallHeight + 1; z++)
{
UpdateBlock(new Int3(i, 0 + z, k), MazeWallType);
}
}
}
}
//for (int j = 0; j < Size.y; j++)
}
public void FillEmptyPath(Vector3 Size, int PathBlockType, int FillBlockType)
{
int j = Mathf.RoundToInt (StartLocation.y);
for (int i = 0; i < Size.x; i++)
{
for (int k = 0; k < Size.z; k++)
{
if (GetBlockType(new Int3(i, j, k)) == 0)
{
for (int z = 0; z < MazeWallHeight + 1; z++)
{
UpdateBlock(new Int3(i, j + z, k), FillBlockType);
}
}
}
}
}
bool IsOnEdge(Vector3 Position, Int3 Size)
{
if (Position.x == Size.x - 1 || Position.x == 0
// ||Position.y == Size.y - 1 || Position.y == 0
|| Position.z == Size.z - 1 || Position.z == 0
)
return true;
return false;
}
// Runs the maze like algorithm, from starting points of biomes, until a biome type covers the whole surface
// render it to texture to see
// generate paths from multiple positionsh
void GenerateBiomeMap(Int3 Size)
{
/*Vector3 MinimumDistanceToOthers;
Vector3 MaximumDistanceToOthers;
List<Vector3> StartingLocations;
int MinimumBiomes = 2;
int MaximumBiomes = 5;
int NumberOfBiomes = 3;
for (int i = 0; i < NumberOfBiomes; i++) {
if (IsLockedAxis)
StartingLocations.Add(new Vector3(Random.Range(0, Size.x), Random.Range(0, Size.y), StartLocation.z));
else
StartingLocations.Add(new Vector3(Random.Range(0, Size.x), Random.Range(0, Size.y), Random.Range(0, Size.z)));
}
CurrentSparce = 0;
for (int i = 0; i < StartingLocations.Count; i++) {
GeneratePaths(MyBlocks, Size, Dungeon, StartingLocations[i], PathBlockType + i, (Sparceness)*(i + 1), Linearity);
}
*/
}
int CheckedBlocks = 0;
bool HasFoundNewPosition = false;
void CheckForNewPosition()
{
}
// Need a way that gives a maximum amount of up/down blocks at once
// maybe it should remember the last few directions
// no it shou ld create a direction map lol.
void GeneratePaths(Int3 Size, Vector3 StartLocation, int PathBlockType, float Sparceness, float Linearity)
{
// set defaults
//if (bIsEdge && IsPositionOutsideBounds(StartLocation, Size, bIsEdge)) {
// if (StartLocation.y == 0) StartLocation.y = 1;
//}
Debug.Log ("Generating paths!");
DebugDirections.Clear();
Iterations = 0;
IsSparceEnough = false;
CurrentSparce = 0;
MaxSparce = 1;
if (!IsVoidAxisX)
MaxSparce *= Size.x;
if (!IsVoidAxisY)
MaxSparce *= Size.y;
if (!IsVoidAxisZ)
MaxSparce *= Size.z;
//MaxSparce = Size.x*Size.z;
//PathSizeMinimum = PathSizeMinimum;
if (PathSizeMinimum.x < 1) PathSizeMinimum.x = 1;
if (PathSizeMinimum.y < 1) PathSizeMinimum.y = 1;
if (PathSizeMinimum.z < 1) PathSizeMinimum.z = 1;
if (PathSizeMaximum.x < 1) PathSizeMaximum.x = 1;
if (PathSizeMaximum.y < 1) PathSizeMaximum.y = 1;
if (PathSizeMaximum.z < 1) PathSizeMaximum.z = 1;
PathSize = new Vector3 (Random.Range (PathSizeMinimum.x, PathSizeMaximum.x), 1, Random.Range (PathSizeMinimum.z, PathSizeMaximum.z));
DebugPositions.Clear ();
Position = StartLocation;
PathDirection = 0;
// starting block
UpdateBlock(Position.ToInt3(), PathBlockType);
CheckSparce(PathBlockType);
while (!IsSparceEnough)
{
IteratePath(Size, StartLocation, PathBlockType, Sparceness, Linearity);
}
}
public bool IsTypeDungeonBlock(int Type)
{
return (Type != 0 && Type != MazeWallType);
}
private void IteratePath(Int3 Size, Vector3 StartLocation, int PathBlockType, float Sparceness, float Linearity)
{
List<Vector3> Positions = new List<Vector3>();
// Check for Sparce Percentage
int TurnChance = Mathf.RoundToInt(Random.Range(1f, 100f));
if (PathDirection <= 0 || TurnChance >= Linearity) {
// Randomly Make a new direction
if (PathDirection == 0) {
HasFoundNewPosition = false;
CheckedBlocks = 0;
//int FindPositionBlock = 200;
int MaximumChecksForNewPosition = 0;
while (!HasFoundNewPosition || CheckedBlocks == MaxSparce || MaximumChecksForNewPosition >= 250)
{
MaximumChecksForNewPosition++;
Position.x = Mathf.RoundToInt(Random.Range(1, Size.x-2));
Position.z = Mathf.RoundToInt(Random.Range(1, Size.z-2));
if (IsTypeDungeonBlock(GetBlockType(Position.ToInt3())))
{
HasFoundNewPosition = true;
}
else
{
/*if (MyBlocks.GetBlockType(Position) != FindPositionBlock) {
CheckedBlocks++;
MyBlocks.UpdateBlock(Position, FindPositionBlock);
}*/
}
}
if (MaximumChecksForNewPosition >= 250)
{
Debug.LogError("Wow exceded maximum checks..");
Position = StartLocation;
}
/*for (int i = 0; i < Size.x; i++)
for (int j = 0; j < Size.z; j++)
{
Vector3 NewPosition = new Vector3(i, Position.y, j);
if (MyBlocks.GetBlockType(NewPosition) == FindPositionBlock)
MyBlocks.UpdateBlock(Position, 0);
}*/
}
// Search for a new place in the maze, where the path already is, and start digging again
List<int> PossiblePathDirection = new List<int>();
if (!IsVoidAxisX)
{
PossiblePathDirection.Add (1);
PossiblePathDirection.Add (2);
}
if (!IsVoidAxisY)
{
PossiblePathDirection.Add (3);
PossiblePathDirection.Add (4);
}
if (!IsVoidAxisZ)
{
PossiblePathDirection.Add (5);
PossiblePathDirection.Add (6);
}
if (PossiblePathDirection.Count > 0)
{
int PathDirectionIndex = Mathf.RoundToInt(Random.Range(0f, PossiblePathDirection.Count-1f));
PathDirection = PossiblePathDirection[PathDirectionIndex];
}
//PathDirection = (int)(Random.Range(1,4));
//Debug.Log ("PathDirection: " + PathDirection + " : Iteration: " + Iterations);
DebugDirections.Add (PathDirection);
}
if (PathDirection == 1)
{ // going right
Position.x++;
if (bIsMoveToSize)
Position.x += PathSize.x;
}
else if (PathDirection == 2)
{ // going left
Position.x--;
if (bIsMoveToSize)
Position.x -= PathSize.x;
}
else if (PathDirection == 3)
{ // going up
Position.y++;
if (bIsMoveToSize)
Position.y += PathSize.y;
}
else if (PathDirection == 4)
{ // going down
Position.y--;
if (bIsMoveToSize)
Position.y -= PathSize.y;
}
else if (PathDirection == 5)
{ // going forward
Position.z++;
if (bIsMoveToSize)
Position.z += PathSize.z;
}
else if (PathDirection == 6)
{ // going back
Position.z--;
if (bIsMoveToSize)
Position.z -= PathSize.z;
}
Positions.Clear();
for (float i = -PathSize.x; i < PathSize.x + 1; i++)
for (float j = -PathSize.y; j < PathSize.y + 1; j++)
for (float k = -PathSize.z; k < PathSize.z + 1; k++)
{
Positions.Add(new Vector3(Position.x + i, Position.y + j, Position.z + k));
//DebugPositions.Add (new Vector3(Position.x + i, Position.y + j, Position.z + k));
}
//DebugDirections.Add (PathDirection);
// Checks to Stop Growing of Dungeon!
// now here if Moving position, do checks on blocks etc for pathways
// if blocks on left and right are not taken, then build path, else don't build path
if (bIsPathways)
{
// this is now up down
//Vector3 BackPosition = new Vector3(Position.x, Position.y - 1 - PathSize.y, Position.z);
//Vector3 ForwardPosition = new Vector3(Position.x, Position.y + 1 + PathSize.y, Position.z);
if (PathDirection == 3 || PathDirection == 4)
{
//if (IsStopPath(MyBlocks.GetBlockType(BackPosition)) || MyBlocks.GetBlockType(ForwardPosition) == PathBlockType) {
//PathDirection = 0;
//}
}
Vector3 LeftPosition = new Vector3(Position.x - 1 - PathSize.x, Position.y, Position.z);
Vector3 RightPosition = new Vector3(Position.x + 1 + PathSize.x, Position.y, Position.z);
if (PathDirection == 5 || PathDirection == 6) {
if (IsStopMaze(GetBlockType(LeftPosition.ToInt3())) || IsStopMaze(GetBlockType(RightPosition.ToInt3())))
{
PathDirection = 0;
}
}
// forward, back
Vector3 BottomPosition = new Vector3(Position.x, Position.y, Position.z - 1 - PathSize.z);
//Vector3 TopPosition = new Vector3(Position.x, Position.y, Position.z + 1 + PathSize.z);
if (PathDirection == 1 || PathDirection == 2)
{
if (IsStopMaze(GetBlockType(BottomPosition.ToInt3())) || IsStopMaze(GetBlockType(BottomPosition.ToInt3())))
{
PathDirection = 0;
}
}
}
// Now do checks for positions intersecting with path
if (IsPositionOutsideBounds(Position, Size, bIsEdge))
{
if (!bIsWrap)
{
//PathDirection = -1; // Maybe I should just force the direction to turn rather then just end it like this
PathDirection = 0; // Maybe I should just force the direction to turn rather then just end it like this
if (Position.x > Size.x - 1) Position.x = Size.x - 1;
if (Position.x < 0) Position.x = 0;
if (Position.y > Size.y - 1) Position.y = Size.y - 1;
if (Position.y < 0) Position.y = 0;
if (Position.z > Size.z - 1) Position.z = Size.z - 1;
if (Position.z < 0) Position.z = 0;
}
else {
PathDirection = 0; // Maybe I should just force the direction to turn rather then just end it like this
if (Position.x > Size.x - 1) Position.x = 0;
if (Position.x < 0) Position.x = Size.x - 1;
if (Position.y > Size.y - 1) Position.y = 0;
if (Position.y < 0) Position.y = Size.y - 1;
if (Position.z > Size.z - 1) Position.z = 0;
if (Position.z < 0) Position.z = Size.z - 1;
}
}
DebugDirections.Add (PathDirection);
if (PathDirection > 0)
{
for (int z = 0; z < Positions.Count; z++)
{
if (GetBlockType(Positions[z].ToInt3()) == 0)
{
//MyBlocks.UpdateBlock(Positions[z], PathBlockType);
UpdateBlock(Positions[z].ToInt3(), Size, PathBlockType);
}
}
}
//Debug.Log (Iterations + " : PositionsCount: " + Positions.Count);
Iterations++;
if (Iterations >= MaxIterations)
{
IsSparceEnough = true;
}
SparcePercentage = (CurrentSparce / MaxSparce);
if (100f * SparcePercentage > Sparceness)
{
IsSparceEnough = true;
Debug.Log ("Is Sparce Enough: " + 100f * SparcePercentage + " Percent.");
}
}
bool IsPositionOutsideBounds(Vector3 BoundsPosition, Int3 Size, bool IsEdge)
{
bool IsOutOfBounds = false;
if (!IsVoidAxisX)
if (BoundsPosition.x >= Size.x - PathSize.x -1 || BoundsPosition.x <= PathSize.x+1)
IsOutOfBounds = true;
if (!IsVoidAxisY)
if (BoundsPosition.y >= Size.y - PathSize.y - 1 || BoundsPosition.y <= PathSize.y + 1)
IsOutOfBounds = true;
if (!IsVoidAxisZ)
if (BoundsPosition.z >= Size.z - PathSize.z - 1 || BoundsPosition.z <= PathSize.z + 1)
IsOutOfBounds = true;
/*if (!IsEdge)
return (BoundsPosition.x > Size.x - 1 || BoundsPosition.x < 0 ||
BoundsPosition.y > Size.y - 1 || BoundsPosition.y < 0 ||
BoundsPosition.z > Size.z - 1 || BoundsPosition.z < 0);
else
return (BoundsPosition.x > Size.x - 2 || BoundsPosition.x < 1 ||
BoundsPosition.y > Size.y - 2 || BoundsPosition.y < 1 ||
BoundsPosition.z > Size.z - 2 || BoundsPosition.z < 1);*/
return IsOutOfBounds;
}
public bool IsPathOverride = false; // if override, then only stop path on path blocks, else stop on any other block type thats solid
public bool IsStopMaze(int BlockType) {
if (BlockType == 0) {
return false;
} else if (!IsPathOverride)
return true;
else if (IsPathOverride && !IsTypeDungeonBlock(BlockType)) // stops for anything but itself
return true;
else
return false;
}
// Searches the Blocks for a empty block, that is surrounded by 4 path blocks, then it removes it or filles it with a special pillar looking block
void RemoveSinglePillars(Vector3 Size, int PathBlockType) {
if (bIsRemoveSinglePillars)
for (int i = 0; i < Size.x; i++)
for (int j = 0; j < Size.y; j++)
for (int k = 0; k < Size.z; k++)
{
if (GetBlockType(new Int3(i, j, k)) == 0)
{
if (GetBlockType(new Int3(i + 1, j, k)) == PathBlockType && GetBlockType(new Int3(i - 1, j, k)) == PathBlockType &&
GetBlockType(new Int3(i, j + 1, k)) == PathBlockType && GetBlockType(new Int3(i, j - 1, k)) == PathBlockType)
{
UpdateBlock(new Int3(i, j, k + MazeWallHeight), PathBlockType);
}
}
}
}
public void SetDefaultColors() {
BlockColors.Clear ();
BlockColors.Add (new Color32(125,165,165,255));
BlockColors.Add (new Color32(200,200,200,255)); // cobblestone
BlockColors.Add (new Color32(55,255,255,255)); // grass
BlockColors.Add (new Color32(66,66,66,255)); // brick - 3
BlockColors.Add (new Color32(255,0,0,255)); // red brick - 4
BlockColors.Add (new Color32(55,155,55,255)); // Hexgon brick - 4
BlockColors.Add (new Color32(255,255,55,255)); // 1,0 brick - 4
BlockColors.Add (new Color32(155,155,55,255)); // 1,0 brick - 4
for (int i = BlockColors.Count; i < 64; i++) {
BlockColors.Add (new Color32((byte)(i*25),(byte)(i*15),(byte)(i*5),255));
}
}
/*public Texture2D GetMazeTexture() {
SetDefaultColors ();
Debug.Log ("Generating Texture.");
//MeshRenderer MyRenderer = MazeTextureObject.GetComponent<MeshRenderer> ();
// duplicate the original texture and assign to the material
Texture2D MyTexture2D = new Texture2D (Mathf.FloorToInt(MyBlocks.Size.x),
Mathf.FloorToInt(MyBlocks.Size.z)); //MyRenderer.material.mainTexture);
//MyRenderer.materials[0].SetTexture(0, MyTexture2D);
//MyRawImage.texture = (MyTexture2D);
MaxMipMapLevel = MyTexture2D.mipmapCount;
MyTexture2D.filterMode = FilterMode.Point;
int MipMapLevel = 0;
//for (int z = MaxMipMapLevel; MaxMipMapLevel < MaxMipMapLevel; MaxMipMapLevel++) {
MyTexture2D.Resize (Mathf.RoundToInt (MyBlocks.Size.x), Mathf.RoundToInt (MyBlocks.Size.z));
//Texture2D MyTexture2D = MyTexture;
Color32[] NewColors = MyTexture2D.GetPixels32 (MipMapLevel);
for (int i = 0; i < MyBlocks.Size.x; i++)
for (int k = 0; k < MyBlocks.Size.z; k++) {
int PixelIndex = Mathf.RoundToInt (i * MyBlocks.Size.x + k);
NewColors[PixelIndex] = BlockColors[MyBlocks.GetBlockType (new Vector3 (i, StartLocation.y, k))];
}
MyTexture2D.SetPixels32 (NewColors, MipMapLevel);
MyTexture2D.Apply( true );
Debug.Log ("Applied Texture.");
return MyTexture2D;
}*/
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using NUnit.Framework.Api;
#if true
#endif
namespace NUnit.Framework.Internal
{
/// <summary>
/// A PropertyBag represents a collection of name value pairs
/// that allows duplicate entries with the same key. Methods
/// are provided for adding a new pair as well as for setting
/// a key to a single value. All keys are strings but values
/// may be of any type. Null values are not permitted, since
/// a null entry represents the absence of the key.
/// </summary>
public class PropertyBag : IPropertyBag
{
#if true
private Dictionary<string, IList> inner = new Dictionary<string, IList>();
private bool TryGetValue(string key, out IList list)
{
return inner.TryGetValue(key, out list);
}
#else
private Hashtable inner = new Hashtable();
private bool TryGetValue(string key, out IList list)
{
list = inner.ContainsKey(key)
? (IList)inner[key]
: null;
return list != null;
}
#endif
/// <summary>
/// Adds a key/value pair to the property set
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
public void Add(string key, object value)
{
IList list;
if (!TryGetValue(key, out list))
{
list = new ObjectList();
inner.Add(key, list);
}
list.Add(value);
}
/// <summary>
/// Sets the value for a key, removing any other
/// values that are already in the property set.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Set(string key, object value)
{
IList list = new ObjectList();
list.Add(value);
inner[key] = list;
}
/// <summary>
/// Gets a single value for a key, using the first
/// one if multiple values are present and returning
/// null if the value is not found.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public object Get(string key)
{
IList list;
return TryGetValue(key, out list) && list.Count > 0
? list[0]
: null;
}
/// <summary>
/// Gets a single boolean value for a key, using the first
/// one if multiple values are present and returning the
/// default value if no entry is found.
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public bool GetSetting(string key, bool defaultValue)
{
object value = Get(key);
return value == null
? defaultValue
: (bool)value;
}
/// <summary>
/// Gets a single string value for a key, using the first
/// one if multiple values are present and returning the
/// default value if no entry is found.
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public string GetSetting(string key, string defaultValue)
{
object value = Get(key);
return value == null
? defaultValue
: (string)value;
}
/// <summary>
/// Gets a single int value for a key, using the first
/// one if multiple values are present and returning the
/// default value if no entry is found.
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public int GetSetting(string key, int defaultValue)
{
object value = Get(key);
return value == null
? defaultValue
: (int)value;
}
/// <summary>
/// Gets a single Enum value for a key, using the first
/// one if multiple values are present and returning the
/// default value if no entry is found.
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public Enum GetSetting(string key, Enum defaultValue)
{
object value = Get(key);
return value == null
? defaultValue
: (Enum)value;
}
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear()
{
inner.Clear();
}
/// <summary>
/// Removes all entries for a key from the property set
/// </summary>
/// <param name="key">The key for which the entries are to be removed</param>
public void Remove(string key)
{
inner.Remove(key);
}
/// <summary>
/// Removes a single entry if present. If not found,
/// no error occurs.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Remove(string key, object value)
{
IList list;
if (TryGetValue(key, out list))
list.Remove(value);
}
/// <summary>
/// Removes a specific PropertyEntry. If the entry is not
/// found, no errr occurs.
/// </summary>
/// <param name="entry">The property entry to remove</param>
public void Remove(PropertyEntry entry)
{
Remove(entry.Name, entry.Value);
}
/// <summary>
/// Get the number of key/value pairs in the property set
/// </summary>
/// <value></value>
public int Count
{
get
{
int count = 0;
foreach (string key in inner.Keys)
count += ((IList)inner[key]).Count;
return count;
}
}
/// <summary>
/// Gets a flag indicating whether the specified key has
/// any entries in the property set.
/// </summary>
/// <param name="key">The key to be checked</param>
/// <returns>
/// True if their are values present, otherwise false
/// </returns>
public bool ContainsKey(string key)
{
return inner.ContainsKey(key);
}
/// <summary>
/// Gets a flag indicating whether the specified key and
/// value are present in the property set.
/// </summary>
/// <param name="key">The key to be checked</param>
/// <param name="value">The value to be checked</param>
/// <returns>
/// True if the key and value are present, otherwise false
/// </returns>
public bool Contains(string key, object value)
{
IList list;
return TryGetValue(key, out list) && list.Contains(value);
}
/// <summary>
/// Gets a flag indicating whether the specified key and
/// value are present in the property set.
/// </summary>
/// <param name="entry">The property entry to be checked</param>
/// <returns>
/// True if the entry is present, otherwise false
/// </returns>
public bool Contains(PropertyEntry entry)
{
return Contains(entry.Name, entry.Value);
}
/// <summary>
/// Gets a collection containing all the keys in the property set
/// </summary>
/// <value></value>
#if true
public ICollection<string> Keys
#else
public ICollection Keys
#endif
{
get { return inner.Keys; }
}
/// <summary>
/// Gets an enumerator for all properties in the property bag
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return new PropertyBagEnumerator(this);
}
/// <summary>
/// Gets or sets the list of values for a particular key
/// </summary>
public IList this[string key]
{
get
{
IList list;
if (!TryGetValue(key, out list))
{
list = new ObjectList();
inner.Add(key, list);
}
return list;
}
set
{
inner[key] = value;
}
}
#region IXmlNodeBuilder Members
/// <summary>
/// Returns an XmlNode representating the current PropertyBag.
/// </summary>
/// <param name="recursive">Not used</param>
/// <returns>An XmlNode representing the PropertyBag</returns>
public System.Xml.XmlNode ToXml(bool recursive)
{
XmlNode topNode = XmlHelper.CreateTopLevelElement("dummy");
XmlNode thisNode = AddToXml(topNode, recursive);
return thisNode;
}
/// <summary>
/// Returns an XmlNode representing the PropertyBag after
/// adding it as a child of the supplied parent node.
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="recursive">Not used</param>
/// <returns></returns>
public System.Xml.XmlNode AddToXml(System.Xml.XmlNode parentNode, bool recursive)
{
XmlNode properties = XmlHelper.AddElement(parentNode, "properties");
foreach (string key in Keys)
{
foreach (object value in this[key])
{
XmlNode prop = XmlHelper.AddElement(properties, "property");
// TODO: Format as string
XmlHelper.AddAttribute(prop, "name", key.ToString());
XmlHelper.AddAttribute(prop, "value", value.ToString());
}
}
return properties;
}
#endregion
#region Nested PropertyBagEnumerator Class
/// <summary>
/// TODO: Documentation needed for class
/// </summary>
#if true
public class PropertyBagEnumerator : IEnumerator<PropertyEntry>
{
private IEnumerator<KeyValuePair<string, IList>> innerEnum;
#else
public class PropertyBagEnumerator : IEnumerator
{
private IEnumerator innerEnum;
#endif
private PropertyBag bag;
private IEnumerator valueEnum;
/// <summary>
///
/// </summary>
/// <param name="bag"></param>
public PropertyBagEnumerator(PropertyBag bag)
{
this.bag = bag;
Initialize();
}
private void Initialize()
{
innerEnum = bag.inner.GetEnumerator();
valueEnum = null;
if (innerEnum.MoveNext())
{
#if true
valueEnum = innerEnum.Current.Value.GetEnumerator();
#else
DictionaryEntry entry = (DictionaryEntry)innerEnum.Current;
valueEnum = ((IList)entry.Value).GetEnumerator();
#endif
}
}
private PropertyEntry GetCurrentEntry()
{
if (valueEnum == null)
throw new InvalidOperationException();
#if true
string key = innerEnum.Current.Key;
#else
DictionaryEntry entry = (DictionaryEntry)innerEnum.Current;
string key = (string)entry.Key;
#endif
object value = valueEnum.Current;
return new PropertyEntry(key, value);
}
#region IEnumerator<PropertyEntry> Members
#if true
PropertyEntry IEnumerator<PropertyEntry>.Current
{
get
{
return GetCurrentEntry();
}
}
#endif
#endregion
#region IDisposable Members
#if true
void IDisposable.Dispose()
{
}
#endif
#endregion
#region IEnumerator Members
object IEnumerator.Current
{
get
{
return GetCurrentEntry();
}
}
bool IEnumerator.MoveNext()
{
if (valueEnum == null)
return false;
while (!valueEnum.MoveNext())
{
if (!innerEnum.MoveNext())
{
valueEnum = null;
return false;
}
#if true
valueEnum = innerEnum.Current.Value.GetEnumerator();
#else
DictionaryEntry entry = (DictionaryEntry)innerEnum.Current;
valueEnum = ((IList)entry.Value).GetEnumerator();
#endif
}
return true;
}
void IEnumerator.Reset()
{
Initialize();
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Text;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
[TestFixture]
public class EaxTest
: SimpleTest
{
private static readonly byte[] K1 = Hex.Decode("233952DEE4D5ED5F9B9C6D6FF80FF478");
private static readonly byte[] N1 = Hex.Decode("62EC67F9C3A4A407FCB2A8C49031A8B3");
private static readonly byte[] A1 = Hex.Decode("6BFB914FD07EAE6B");
private static readonly byte[] P1 = Hex.Decode("");
private static readonly byte[] C1 = Hex.Decode("E037830E8389F27B025A2D6527E79D01");
private static readonly byte[] T1 = Hex.Decode("E037830E8389F27B025A2D6527E79D01");
private static readonly byte[] K2 = Hex.Decode("91945D3F4DCBEE0BF45EF52255F095A4");
private static readonly byte[] N2 = Hex.Decode("BECAF043B0A23D843194BA972C66DEBD");
private static readonly byte[] A2 = Hex.Decode("FA3BFD4806EB53FA");
private static readonly byte[] P2 = Hex.Decode("F7FB");
private static readonly byte[] C2 = Hex.Decode("19DD5C4C9331049D0BDAB0277408F67967E5");
private static readonly byte[] T2 = Hex.Decode("5C4C9331049D0BDAB0277408F67967E5");
private static readonly byte[] K3 = Hex.Decode("01F74AD64077F2E704C0F60ADA3DD523");
private static readonly byte[] N3 = Hex.Decode("70C3DB4F0D26368400A10ED05D2BFF5E");
private static readonly byte[] A3 = Hex.Decode("234A3463C1264AC6");
private static readonly byte[] P3 = Hex.Decode("1A47CB4933");
private static readonly byte[] C3 = Hex.Decode("D851D5BAE03A59F238A23E39199DC9266626C40F80");
private static readonly byte[] T3 = Hex.Decode("3A59F238A23E39199DC9266626C40F80");
private static readonly byte[] K4 = Hex.Decode("D07CF6CBB7F313BDDE66B727AFD3C5E8");
private static readonly byte[] N4 = Hex.Decode("8408DFFF3C1A2B1292DC199E46B7D617");
private static readonly byte[] A4 = Hex.Decode("33CCE2EABFF5A79D");
private static readonly byte[] P4 = Hex.Decode("481C9E39B1");
private static readonly byte[] C4 = Hex.Decode("632A9D131AD4C168A4225D8E1FF755939974A7BEDE");
private static readonly byte[] T4 = Hex.Decode("D4C168A4225D8E1FF755939974A7BEDE");
private static readonly byte[] K5 = Hex.Decode("35B6D0580005BBC12B0587124557D2C2");
private static readonly byte[] N5 = Hex.Decode("FDB6B06676EEDC5C61D74276E1F8E816");
private static readonly byte[] A5 = Hex.Decode("AEB96EAEBE2970E9");
private static readonly byte[] P5 = Hex.Decode("40D0C07DA5E4");
private static readonly byte[] C5 = Hex.Decode("071DFE16C675CB0677E536F73AFE6A14B74EE49844DD");
private static readonly byte[] T5 = Hex.Decode("CB0677E536F73AFE6A14B74EE49844DD");
private static readonly byte[] K6 = Hex.Decode("BD8E6E11475E60B268784C38C62FEB22");
private static readonly byte[] N6 = Hex.Decode("6EAC5C93072D8E8513F750935E46DA1B");
private static readonly byte[] A6 = Hex.Decode("D4482D1CA78DCE0F");
private static readonly byte[] P6 = Hex.Decode("4DE3B35C3FC039245BD1FB7D");
private static readonly byte[] C6 = Hex.Decode("835BB4F15D743E350E728414ABB8644FD6CCB86947C5E10590210A4F");
private static readonly byte[] T6 = Hex.Decode("ABB8644FD6CCB86947C5E10590210A4F");
private static readonly byte[] K7 = Hex.Decode("7C77D6E813BED5AC98BAA417477A2E7D");
private static readonly byte[] N7 = Hex.Decode("1A8C98DCD73D38393B2BF1569DEEFC19");
private static readonly byte[] A7 = Hex.Decode("65D2017990D62528");
private static readonly byte[] P7 = Hex.Decode("8B0A79306C9CE7ED99DAE4F87F8DD61636");
private static readonly byte[] C7 = Hex.Decode("02083E3979DA014812F59F11D52630DA30137327D10649B0AA6E1C181DB617D7F2");
private static readonly byte[] T7 = Hex.Decode("137327D10649B0AA6E1C181DB617D7F2");
private static readonly byte[] K8 = Hex.Decode("5FFF20CAFAB119CA2FC73549E20F5B0D");
private static readonly byte[] N8 = Hex.Decode("DDE59B97D722156D4D9AFF2BC7559826");
private static readonly byte[] A8 = Hex.Decode("54B9F04E6A09189A");
private static readonly byte[] P8 = Hex.Decode("1BDA122BCE8A8DBAF1877D962B8592DD2D56");
private static readonly byte[] C8 = Hex.Decode("2EC47B2C4954A489AFC7BA4897EDCDAE8CC33B60450599BD02C96382902AEF7F832A");
private static readonly byte[] T8 = Hex.Decode("3B60450599BD02C96382902AEF7F832A");
private static readonly byte[] K9 = Hex.Decode("A4A4782BCFFD3EC5E7EF6D8C34A56123");
private static readonly byte[] N9 = Hex.Decode("B781FCF2F75FA5A8DE97A9CA48E522EC");
private static readonly byte[] A9 = Hex.Decode("899A175897561D7E");
private static readonly byte[] P9 = Hex.Decode("6CF36720872B8513F6EAB1A8A44438D5EF11");
private static readonly byte[] C9 = Hex.Decode("0DE18FD0FDD91E7AF19F1D8EE8733938B1E8E7F6D2231618102FDB7FE55FF1991700");
private static readonly byte[] T9 = Hex.Decode("E7F6D2231618102FDB7FE55FF1991700");
private static readonly byte[] K10 = Hex.Decode("8395FCF1E95BEBD697BD010BC766AAC3");
private static readonly byte[] N10 = Hex.Decode("22E7ADD93CFC6393C57EC0B3C17D6B44");
private static readonly byte[] A10 = Hex.Decode("126735FCC320D25A");
private static readonly byte[] P10 = Hex.Decode("CA40D7446E545FFAED3BD12A740A659FFBBB3CEAB7");
private static readonly byte[] C10 = Hex.Decode("CB8920F87A6C75CFF39627B56E3ED197C552D295A7CFC46AFC253B4652B1AF3795B124AB6E");
private static readonly byte[] T10 = Hex.Decode("CFC46AFC253B4652B1AF3795B124AB6E");
private static readonly byte[] K11 = Hex.Decode("8395FCF1E95BEBD697BD010BC766AAC3");
private static readonly byte[] N11 = Hex.Decode("22E7ADD93CFC6393C57EC0B3C17D6B44");
private static readonly byte[] A11 = Hex.Decode("126735FCC320D25A");
private static readonly byte[] P11 = Hex.Decode("CA40D7446E545FFAED3BD12A740A659FFBBB3CEAB7");
private static readonly byte[] C11 = Hex.Decode("CB8920F87A6C75CFF39627B56E3ED197C552D295A7CFC46AFC");
private static readonly byte[] T11 = Hex.Decode("CFC46AFC");
private const int NONCE_LEN = 8;
private const int MAC_LEN = 8;
private const int AUTHEN_LEN = 20;
public override string Name
{
get { return "EAX"; }
}
public override void PerformTest()
{
checkVectors(1, K1, 128, N1, A1, P1, T1, C1);
checkVectors(2, K2, 128, N2, A2, P2, T2, C2);
checkVectors(3, K3, 128, N3, A3, P3, T3, C3);
checkVectors(4, K4, 128, N4, A4, P4, T4, C4);
checkVectors(5, K5, 128, N5, A5, P5, T5, C5);
checkVectors(6, K6, 128, N6, A6, P6, T6, C6);
checkVectors(7, K7, 128, N7, A7, P7, T7, C7);
checkVectors(8, K8, 128, N8, A8, P8, T8, C8);
checkVectors(9, K9, 128, N9, A9, P9, T9, C9);
checkVectors(10, K10, 128, N10, A10, P10, T10, C10);
checkVectors(11, K11, 32, N11, A11, P11, T11, C11);
EaxBlockCipher eax = new EaxBlockCipher(new AesEngine());
ivParamTest(1, eax, K1, N1);
//
// exception tests
//
try
{
eax.Init(false, new CcmParameters(new KeyParameter(K1), 32, N2, A2));
byte[] enc = new byte[C2.Length];
int len = eax.ProcessBytes(C2, 0, C2.Length, enc, 0);
len += eax.DoFinal(enc, len);
Fail("invalid cipher text not picked up");
}
catch (InvalidCipherTextException)
{
// expected
}
try
{
eax.Init(false, new KeyParameter(K1));
Fail("illegal argument not picked up");
}
catch (ArgumentException)
{
// expected
}
randomTests();
}
private void checkVectors(
int count,
byte[] k,
int macSize,
byte[] n,
byte[] a,
byte[] p,
byte[] t,
byte[] c)
{
EaxBlockCipher encEax = new EaxBlockCipher(new AesFastEngine());
EaxBlockCipher decEax = new EaxBlockCipher(new AesFastEngine());
AeadParameters parameters = new AeadParameters(new KeyParameter(k), macSize, n, a);
encEax.Init(true, parameters);
decEax.Init(false, parameters);
runCheckVectors(count, encEax, decEax, p, t, c);
runCheckVectors(count, encEax, decEax, p, t, c);
}
private void runCheckVectors(
int count,
EaxBlockCipher encEax,
EaxBlockCipher decEax,
byte[] p,
byte[] t,
byte[] c)
{
byte[] enc = new byte[c.Length];
int len = encEax.ProcessBytes(p, 0, p.Length, enc, 0);
len += encEax.DoFinal(enc, len);
if (!AreEqual(c, enc))
{
Fail("encrypted stream fails to match in test " + count);
}
byte[] tmp = new byte[enc.Length];
len = decEax.ProcessBytes(enc, 0, enc.Length, tmp, 0);
len += decEax.DoFinal(tmp, len);
byte[] dec = new byte[len];
Array.Copy(tmp, 0, dec, 0, len);
if (!AreEqual(p, dec))
{
Fail("decrypted stream fails to match in test " + count);
}
if (!AreEqual(t, decEax.GetMac()))
{
Fail("MAC fails to match in test " + count);
}
}
private void ivParamTest(
int count,
IAeadBlockCipher eax,
byte[] k,
byte[] n)
{
byte[] p = Encoding.ASCII.GetBytes("hello world!!");
eax.Init(true, new ParametersWithIV(new KeyParameter(k), n));
byte[] enc = new byte[p.Length + 8];
int len = eax.ProcessBytes(p, 0, p.Length, enc, 0);
len += eax.DoFinal(enc, len);
eax.Init(false, new ParametersWithIV(new KeyParameter(k), n));
byte[] tmp = new byte[enc.Length];
len = eax.ProcessBytes(enc, 0, enc.Length, tmp, 0);
len += eax.DoFinal(tmp, len);
byte[] dec = new byte[len];
Array.Copy(tmp, 0, dec, 0, len);
if (!AreEqual(p, dec))
{
Fail("decrypted stream fails to match in test " + count);
}
}
private void randomTests()
{
SecureRandom srng = new SecureRandom();
for (int i = 0; i < 10; ++i)
{
randomTest(srng);
}
}
private void randomTest(
SecureRandom srng)
{
int DAT_LEN = srng.Next(1024);
byte[] nonce = new byte[NONCE_LEN];
byte[] authen = new byte[AUTHEN_LEN];
byte[] datIn = new byte[DAT_LEN];
byte[] key = new byte[16];
srng.NextBytes(nonce);
srng.NextBytes(authen);
srng.NextBytes(datIn);
srng.NextBytes(key);
AesFastEngine engine = new AesFastEngine();
KeyParameter sessKey = new KeyParameter(key);
EaxBlockCipher eaxCipher = new EaxBlockCipher(engine);
AeadParameters parameters = new AeadParameters(sessKey, MAC_LEN * 8, nonce, authen);
eaxCipher.Init(true, parameters);
byte[] intrDat = new byte[eaxCipher.GetOutputSize(datIn.Length)];
int outOff = eaxCipher.ProcessBytes(datIn, 0, DAT_LEN, intrDat, 0);
outOff += eaxCipher.DoFinal(intrDat, outOff);
eaxCipher.Init(false, parameters);
byte[] datOut = new byte[eaxCipher.GetOutputSize(outOff)];
int resultLen = eaxCipher.ProcessBytes(intrDat, 0, outOff, datOut, 0);
eaxCipher.DoFinal(datOut, resultLen);
if (!AreEqual(datIn, datOut))
{
Fail("EAX roundtrip failed to match");
}
}
public static void Main(
string[] args)
{
RunTest(new EaxTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="StateMachine.cs" company="Appccelerate">
// Copyright (c) 2008-2015
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Machine
{
using System;
using System.Collections.Generic;
using System.Linq;
using Appccelerate.StateMachine.Machine.Events;
using Appccelerate.StateMachine.Persistence;
using Appccelerate.StateMachine.Syntax;
/// <summary>
/// Base implementation of a state machine.
/// </summary>
/// <typeparam name="TState">The type of the state.</typeparam>
/// <typeparam name="TEvent">The type of the event.</typeparam>
public class StateMachine<TState, TEvent> :
INotifier<TState, TEvent>,
IStateMachineInformation<TState, TEvent>,
IExtensionHost<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
private readonly IStateDictionary<TState, TEvent> states;
private readonly IFactory<TState, TEvent> factory;
private readonly Initializable<TState> initialStateId;
private readonly string name;
private readonly List<IExtension<TState, TEvent>> extensions;
private IState<TState, TEvent> currentState;
/// <summary>
/// Initializes a new instance of the <see cref="StateMachine{TState,TEvent}"/> class.
/// </summary>
public StateMachine()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StateMachine{TState,TEvent}"/> class.
/// </summary>
/// <param name="name">The name of this state machine used in log messages.</param>
public StateMachine(string name)
: this(name, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StateMachine{TState,TEvent}"/> class.
/// </summary>
/// <param name="name">The name of this state machine used in log messages.</param>
/// <param name="factory">The factory used to create internal instances.</param>
public StateMachine(string name, IFactory<TState, TEvent> factory)
{
this.name = name;
this.factory = factory ?? new StandardFactory<TState, TEvent>(this, this);
this.states = new StateDictionary<TState, TEvent>(this.factory);
this.extensions = new List<IExtension<TState, TEvent>>();
this.initialStateId = new Initializable<TState>();
}
/// <summary>
/// Occurs when no transition could be executed.
/// </summary>
public event EventHandler<TransitionEventArgs<TState, TEvent>> TransitionDeclined;
/// <summary>
/// Occurs when an exception was thrown inside a transition of the state machine.
/// </summary>
public event EventHandler<TransitionExceptionEventArgs<TState, TEvent>> TransitionExceptionThrown;
/// <summary>
/// Occurs when a transition begins.
/// </summary>
public event EventHandler<TransitionEventArgs<TState, TEvent>> TransitionBegin;
/// <summary>
/// Occurs when a transition completed.
/// </summary>
public event EventHandler<TransitionCompletedEventArgs<TState, TEvent>> TransitionCompleted;
/// <summary>
/// Gets the name of this instance.
/// </summary>
/// <value>The name of this instance.</value>
public string Name
{
get { return this.name; }
}
/// <summary>
/// Gets the id of the current state.
/// </summary>
/// <value>The id of the current state.</value>
public TState CurrentStateId
{
get { return this.CurrentState.Id; }
}
/// <summary>
/// Gets or sets the state of the current.
/// </summary>
/// <value>The state of the current.</value>
private IState<TState, TEvent> CurrentState
{
get
{
this.CheckThatStateMachineIsInitialized();
this.CheckThatStateMachineHasEnteredInitialState();
return this.currentState;
}
set
{
IState<TState, TEvent> oldState = this.currentState;
this.currentState = value;
this.extensions.ForEach(extension => extension.SwitchedState(this, oldState, this.currentState));
}
}
/// <summary>
/// Adds the <paramref name="extension"/>.
/// </summary>
/// <param name="extension">The extension.</param>
public void AddExtension(IExtension<TState, TEvent> extension)
{
this.extensions.Add(extension);
}
/// <summary>
/// Clears all extensions.
/// </summary>
public void ClearExtensions()
{
this.extensions.Clear();
}
/// <summary>
/// Executes the specified <paramref name="action"/> for all extensions.
/// </summary>
/// <param name="action">The action to execute.</param>
public void ForEach(Action<IExtension<TState, TEvent>> action)
{
this.extensions.ForEach(action);
}
/// <summary>
/// Define the behavior of a state.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>Syntax to build state behavior.</returns>
public IEntryActionSyntax<TState, TEvent> In(TState state)
{
IState<TState, TEvent> newState = this.states[state];
return new StateBuilder<TState, TEvent>(newState, this.states, this.factory);
}
/// <summary>
/// Initializes the state machine by setting the specified initial state.
/// </summary>
/// <param name="initialState">The initial state of the state machine.</param>
public void Initialize(TState initialState)
{
this.extensions.ForEach(extension => extension.InitializingStateMachine(this, ref initialState));
this.Initialize(this.states[initialState]);
this.extensions.ForEach(extension => extension.InitializedStateMachine(this, initialState));
}
/// <summary>
/// Enters the initial state that was previously set with <see cref="Initialize(TState)"/>.
/// </summary>
public void EnterInitialState()
{
this.CheckThatStateMachineIsInitialized();
this.extensions.ForEach(extension => extension.EnteringInitialState(this, this.initialStateId.Value));
var context = this.factory.CreateTransitionContext(null, new Missable<TEvent>(), Missing.Value, this);
this.EnterInitialState(this.states[this.initialStateId.Value], context);
this.extensions.ForEach(extension => extension.EnteredInitialState(this, this.initialStateId.Value, context));
}
/// <summary>
/// Fires the specified event.
/// </summary>
/// <param name="eventId">The event.</param>
public void Fire(TEvent eventId)
{
this.Fire(eventId, Missing.Value);
}
/// <summary>
/// Fires the specified event.
/// </summary>
/// <param name="eventId">The event.</param>
/// <param name="eventArgument">The event argument.</param>
public void Fire(TEvent eventId, object eventArgument)
{
this.CheckThatStateMachineIsInitialized();
this.CheckThatStateMachineHasEnteredInitialState();
this.extensions.ForEach(extension => extension.FiringEvent(this, ref eventId, ref eventArgument));
ITransitionContext<TState, TEvent> context = this.factory.CreateTransitionContext(this.CurrentState, new Missable<TEvent>(eventId), eventArgument, this);
ITransitionResult<TState, TEvent> result = this.CurrentState.Fire(context);
if (!result.Fired)
{
this.OnTransitionDeclined(context);
return;
}
this.CurrentState = result.NewState;
this.extensions.ForEach(extension => extension.FiredEvent(this, context));
this.OnTransitionCompleted(context);
}
/// <summary>
/// Defines the hierarchy on.
/// </summary>
/// <param name="superStateId">The super state id.</param>
/// <returns>Syntax to build a state hierarchy.</returns>
public IHierarchySyntax<TState> DefineHierarchyOn(TState superStateId)
{
return new HierarchyBuilder<TState, TEvent>(this.states, superStateId);
}
public void OnExceptionThrown(ITransitionContext<TState, TEvent> context, Exception exception)
{
RethrowExceptionIfNoHandlerRegistered(exception, this.TransitionExceptionThrown);
this.RaiseEvent(this.TransitionExceptionThrown, new TransitionExceptionEventArgs<TState, TEvent>(context, exception), context, false);
}
/// <summary>
/// Fires the <see cref="TransitionBegin"/> event.
/// </summary>
/// <param name="transitionContext">The transition context.</param>
public void OnTransitionBegin(ITransitionContext<TState, TEvent> transitionContext)
{
this.RaiseEvent(this.TransitionBegin, new TransitionEventArgs<TState, TEvent>(transitionContext), transitionContext, true);
}
/// <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()
{
return this.name ?? base.ToString();
}
/// <summary>
/// Creates a report with the specified generator.
/// </summary>
/// <param name="reportGenerator">The report generator.</param>
public void Report(IStateMachineReport<TState, TEvent> reportGenerator)
{
Guard.AgainstNullArgument("reportGenerator", reportGenerator);
reportGenerator.Report(this.ToString(), this.states.GetStates(), this.initialStateId);
}
public void Save(IStateMachineSaver<TState> stateMachineSaver)
{
Guard.AgainstNullArgument("stateMachineSaver", stateMachineSaver);
stateMachineSaver.SaveCurrentState(this.currentState != null ?
new Initializable<TState> { Value = this.currentState.Id } :
new Initializable<TState>());
IEnumerable<IState<TState, TEvent>> superStatesWithLastActiveState = this.states.GetStates()
.Where(s => s.SubStates.Any())
.Where(s => s.LastActiveState != null)
.ToList();
var historyStates = superStatesWithLastActiveState.ToDictionary(
s => s.Id,
s => s.LastActiveState.Id);
stateMachineSaver.SaveHistoryStates(historyStates);
}
public void Load(IStateMachineLoader<TState> stateMachineLoader)
{
Guard.AgainstNullArgument("stateMachineLoader", stateMachineLoader);
this.CheckThatStateMachineIsNotAlreadyInitialized();
this.LoadCurrentState(stateMachineLoader);
this.LoadHistoryStates(stateMachineLoader);
}
// ReSharper disable once UnusedParameter.Local
private static void RethrowExceptionIfNoHandlerRegistered<T>(Exception exception, EventHandler<T> exceptionHandler) where T : EventArgs
{
if (exceptionHandler == null)
{
throw new StateMachineException("No exception listener is registered. Exception: ", exception);
}
}
/// <summary>
/// Fires the <see cref="TransitionDeclined"/> event.
/// </summary>
/// <param name="transitionContext">The transition event context.</param>
private void OnTransitionDeclined(ITransitionContext<TState, TEvent> transitionContext)
{
this.RaiseEvent(this.TransitionDeclined, new TransitionEventArgs<TState, TEvent>(transitionContext), transitionContext, true);
}
/// <summary>
/// Fires the <see cref="TransitionCompleted"/> event.
/// </summary>
/// <param name="transitionContext">The transition event context.</param>
private void OnTransitionCompleted(ITransitionContext<TState, TEvent> transitionContext)
{
this.RaiseEvent(this.TransitionCompleted, new TransitionCompletedEventArgs<TState, TEvent>(this.CurrentStateId, transitionContext), transitionContext, true);
}
private void LoadCurrentState(IStateMachineLoader<TState> stateMachineLoader)
{
Initializable<TState> loadedCurrentState = stateMachineLoader.LoadCurrentState();
this.currentState = loadedCurrentState.IsInitialized ? this.states[loadedCurrentState.Value] : null;
}
private void LoadHistoryStates(IStateMachineLoader<TState> stateMachineLoader)
{
IDictionary<TState, TState> historyStates = stateMachineLoader.LoadHistoryStates();
foreach (KeyValuePair<TState, TState> historyState in historyStates)
{
IState<TState, TEvent> superState = this.states[historyState.Key];
IState<TState, TEvent> lastActiveState = this.states[historyState.Value];
if (!superState.SubStates.Contains(lastActiveState))
{
throw new InvalidOperationException(ExceptionMessages.CannotSetALastActiveStateThatIsNotASubState);
}
superState.LastActiveState = lastActiveState;
}
}
/// <summary>
/// Initializes the state machine by setting the specified initial state.
/// </summary>
/// <param name="initialState">The initial state.</param>
private void Initialize(IState<TState, TEvent> initialState)
{
if (this.initialStateId.IsInitialized)
{
throw new InvalidOperationException(ExceptionMessages.StateMachineIsAlreadyInitialized);
}
this.initialStateId.Value = initialState.Id;
}
private void EnterInitialState(IState<TState, TEvent> initialState, ITransitionContext<TState, TEvent> context)
{
var initializer = this.factory.CreateStateMachineInitializer(initialState, context);
this.CurrentState = initializer.EnterInitialState();
}
private void RaiseEvent<T>(EventHandler<T> eventHandler, T arguments, ITransitionContext<TState, TEvent> context, bool raiseEventOnException) where T : EventArgs
{
try
{
if (eventHandler == null)
{
return;
}
eventHandler(this, arguments);
}
catch (Exception e)
{
if (!raiseEventOnException)
{
throw;
}
((INotifier<TState, TEvent>)this).OnExceptionThrown(context, e);
}
}
private void CheckThatStateMachineIsInitialized()
{
if (this.currentState == null && !this.initialStateId.IsInitialized)
{
throw new InvalidOperationException(ExceptionMessages.StateMachineNotInitialized);
}
}
private void CheckThatStateMachineIsNotAlreadyInitialized()
{
if (this.currentState != null || this.initialStateId.IsInitialized)
{
throw new InvalidOperationException(ExceptionMessages.StateMachineIsAlreadyInitialized);
}
}
private void CheckThatStateMachineHasEnteredInitialState()
{
if (this.currentState == null)
{
throw new InvalidOperationException(ExceptionMessages.StateMachineHasNotYetEnteredInitialState);
}
}
}
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
namespace OpenMetaverse
{
/// <summary>
/// Wrapper around a byte array that allows bit to be packed and unpacked
/// one at a time or by a variable amount. Useful for very tightly packed
/// data like LayerData packets
/// </summary>
public class BitPack
{
/// <summary></summary>
public byte[] Data;
/// <summary></summary>
public int BytePos
{
get
{
if (bytePos != 0 && bitPos == 0)
return bytePos - 1;
else
return bytePos;
}
}
/// <summary></summary>
public int BitPos { get { return bitPos; } }
private const int MAX_BITS = 8;
private static readonly byte[] ON = new byte[] { 1 };
private static readonly byte[] OFF = new byte[] { 0 };
private int bytePos;
private int bitPos;
private bool weAreBigEndian = !BitConverter.IsLittleEndian;
/// <summary>
/// Default constructor, initialize the bit packer / bit unpacker
/// with a byte array and starting position
/// </summary>
/// <param name="data">Byte array to pack bits in to or unpack from</param>
/// <param name="pos">Starting position in the byte array</param>
public BitPack(byte[] data, int pos)
{
Data = data;
bytePos = pos;
}
/// <summary>
/// Pack a floating point value in to the data
/// </summary>
/// <param name="data">Floating point value to pack</param>
public void PackFloat(float data)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, 32);
}
/// <summary>
/// Pack part or all of an integer in to the data
/// </summary>
/// <param name="data">Integer containing the data to pack</param>
/// <param name="totalCount">Number of bits of the integer to pack</param>
public void PackBits(int data, int totalCount)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, totalCount);
}
/// <summary>
/// Pack part or all of an unsigned integer in to the data
/// </summary>
/// <param name="data">Unsigned integer containing the data to pack</param>
/// <param name="totalCount">Number of bits of the integer to pack</param>
public void PackBits(uint data, int totalCount)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, totalCount);
}
/// <summary>
/// Pack a single bit in to the data
/// </summary>
/// <param name="bit">Bit to pack</param>
public void PackBit(bool bit)
{
if (bit)
PackBitArray(ON, 1);
else
PackBitArray(OFF, 1);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="isSigned"></param>
/// <param name="intBits"></param>
/// <param name="fracBits"></param>
public void PackFixed(float data, bool isSigned, int intBits, int fracBits)
{
int unsignedBits = intBits + fracBits;
int totalBits = unsignedBits;
int min, max;
if (isSigned)
{
totalBits++;
min = 1 << intBits;
min *= -1;
}
else
{
min = 0;
}
max = 1 << intBits;
float fixedVal = Utils.Clamp(data, (float)min, (float)max);
if (isSigned) fixedVal += max;
fixedVal *= 1 << fracBits;
if (totalBits <= 8)
PackBits((uint)fixedVal, 8);
else if (totalBits <= 16)
PackBits((uint)fixedVal, 16);
else if (totalBits <= 31)
PackBits((uint)fixedVal, 32);
else
throw new Exception("Can't use fixed point packing for " + totalBits);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public void PackUUID(UUID data)
{
byte[] bytes = data.GetBytes();
// Not sure if our PackBitArray function can handle 128-bit byte
//arrays, so using this for now
for (int i = 0; i < 16; i++)
PackBits(bytes[i], 8);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public void PackColor(Color4 data)
{
byte[] bytes = data.GetBytes();
PackBitArray(bytes, 32);
}
/// <summary>
/// Unpacking a floating point value from the data
/// </summary>
/// <returns>Unpacked floating point value</returns>
public float UnpackFloat()
{
byte[] output = UnpackBitsArray(32);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToSingle(output, 0);
}
/// <summary>
/// Unpack a variable number of bits from the data in to integer format
/// </summary>
/// <param name="totalCount">Number of bits to unpack</param>
/// <returns>An integer containing the unpacked bits</returns>
/// <remarks>This function is only useful up to 32 bits</remarks>
public int UnpackBits(int totalCount)
{
byte[] output = UnpackBitsArray(totalCount);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToInt32(output, 0);
}
/// <summary>
/// Unpack a variable number of bits from the data in to unsigned
/// integer format
/// </summary>
/// <param name="totalCount">Number of bits to unpack</param>
/// <returns>An unsigned integer containing the unpacked bits</returns>
/// <remarks>This function is only useful up to 32 bits</remarks>
public uint UnpackUBits(int totalCount)
{
byte[] output = UnpackBitsArray(totalCount);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToUInt32(output, 0);
}
/// <summary>
/// Unpack a 16-bit signed integer
/// </summary>
/// <returns>16-bit signed integer</returns>
public short UnpackShort()
{
return (short)UnpackBits(16);
}
/// <summary>
/// Unpack a 16-bit unsigned integer
/// </summary>
/// <returns>16-bit unsigned integer</returns>
public ushort UnpackUShort()
{
return (ushort)UnpackUBits(16);
}
/// <summary>
/// Unpack a 32-bit signed integer
/// </summary>
/// <returns>32-bit signed integer</returns>
public int UnpackInt()
{
return UnpackBits(32);
}
/// <summary>
/// Unpack a 32-bit unsigned integer
/// </summary>
/// <returns>32-bit unsigned integer</returns>
public uint UnpackUInt()
{
return UnpackUBits(32);
}
public byte UnpackByte()
{
byte[] output = UnpackBitsArray(8);
return output[0];
}
public float UnpackFixed(bool signed, int intBits, int fracBits)
{
int minVal;
int maxVal;
int unsignedBits = intBits + fracBits;
int totalBits = unsignedBits;
float fixedVal;
if (signed)
{
totalBits++;
minVal = 1 << intBits;
minVal *= -1;
}
maxVal = 1 << intBits;
if (totalBits <= 8)
fixedVal = (float)UnpackByte();
else if (totalBits <= 16)
fixedVal = (float)UnpackUBits(16);
else if (totalBits <= 31)
fixedVal = (float)UnpackUBits(32);
else
return 0.0f;
fixedVal /= (float)(1 << fracBits);
if (signed) fixedVal -= (float)maxVal;
return fixedVal;
}
public string UnpackString(int size)
{
if (bitPos != 0 || bytePos + size > Data.Length) throw new IndexOutOfRangeException();
string str = System.Text.UTF8Encoding.UTF8.GetString(Data, bytePos, size);
bytePos += size;
return str;
}
public UUID UnpackUUID()
{
if (bitPos != 0) throw new IndexOutOfRangeException();
UUID val = new UUID(Data, bytePos);
bytePos += 16;
return val;
}
private void PackBitArray(byte[] data, int totalCount)
{
int count = 0;
int curBytePos = 0;
int curBitPos = 0;
while (totalCount > 0)
{
if (totalCount > MAX_BITS)
{
count = MAX_BITS;
totalCount -= MAX_BITS;
}
else
{
count = totalCount;
totalCount = 0;
}
while (count > 0)
{
byte curBit = (byte)(0x80 >> bitPos);
if ((data[curBytePos] & (0x01 << (count - 1))) != 0)
Data[bytePos] |= curBit;
else
Data[bytePos] &= (byte)~curBit;
--count;
++bitPos;
++curBitPos;
if (bitPos >= MAX_BITS)
{
bitPos = 0;
++bytePos;
}
if (curBitPos >= MAX_BITS)
{
curBitPos = 0;
++curBytePos;
}
}
}
}
private byte[] UnpackBitsArray(int totalCount)
{
int count = 0;
byte[] output = new byte[4];
int curBytePos = 0;
int curBitPos = 0;
while (totalCount > 0)
{
if (totalCount > MAX_BITS)
{
count = MAX_BITS;
totalCount -= MAX_BITS;
}
else
{
count = totalCount;
totalCount = 0;
}
while (count > 0)
{
// Shift the previous bits
output[curBytePos] <<= 1;
// Grab one bit
if ((Data[bytePos] & (0x80 >> bitPos++)) != 0)
++output[curBytePos];
--count;
++curBitPos;
if (bitPos >= MAX_BITS)
{
bitPos = 0;
++bytePos;
}
if (curBitPos >= MAX_BITS)
{
curBitPos = 0;
++curBytePos;
}
}
}
return output;
}
}
}
| |
using Xunit;
namespace NeinLinq.Tests;
public class InjectLambdaQueryTest_Static
{
[Fact]
public void Query_WithoutSibling_Throws()
{
var query = CreateQuery().ToInjectable(typeof(Functions)).Select(m => Functions.VelocityWithoutSibling(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Static+Functions.VelocityWithoutSibling: no matching parameterless member found.", error.Message);
}
[Fact]
public void Query_WithConvention_Injects()
{
var query = CreateQuery().ToInjectable(typeof(Functions)).Select(m => Functions.VelocityWithConvention(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .125 }, result);
}
[Fact]
public void Query_WithMetadata_Injects()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithMetadata(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .125 }, result);
}
[Fact]
public void Query_WithTypeAndMethodMetadata_Injects()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithTypeAndMethodMetadata(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .125 }, result);
}
[Fact]
public void Query_WithTypeMetadata_Injects()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithTypeMetadata(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .125 }, result);
}
[Fact]
public void Query_WithMethodMetadata_Injects()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithMethodMetadata(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .125 }, result);
}
[Fact]
public void Query_WithNullLambda_Throws()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithNullLambda(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Lambda factory for VelocityWithNullLambda returns null.", error.Message);
}
[Fact]
public void Query_WithoutLambda_Throws()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithoutLambda(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Static+Functions.VelocityWithoutLambda: returns no lambda expression.", error.Message);
}
[Fact]
public void Query_WithoutExpression_Throws()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithoutExpression(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Static+Functions.VelocityWithoutExpression: returns no lambda expression.", error.Message);
}
[Fact]
public void Query_WithoutSignature_Throws()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithoutSignature(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Static+Functions.VelocityWithoutSignature: returns non-matching expression.", error.Message);
}
[Fact]
public void Query_WithoutMatchingSignatureType_Throws()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithoutMatchingSignatureType(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Static+Functions.VelocityWithoutMatchingSignatureType: returns non-matching expression.", error.Message);
}
[Fact]
public void Query_WithoutMatchingSignatureSize_Throws()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithoutMatchingSignatureSize(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Static+Functions.VelocityWithoutMatchingSignatureSize: returns non-matching expression.", error.Message);
}
[Fact]
public void Query_WithGenericArgument_Injects()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithGenericArgument(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .125 }, result);
}
[Fact]
public void Query_WithoutMatchingGenericArgument_Throws()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithoutMatchingGenericArgument(m));
var error = Assert.Throws<InvalidOperationException>(() => query.ToList());
Assert.Equal("Unable to retrieve lambda expression from NeinLinq.Tests.InjectLambdaQueryTest_Static+Functions.VelocityWithoutMatchingGenericArgument: no matching parameterless member found.", error.Message);
}
[Fact]
public void Query_WithPrivateSibling_Injects()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithPrivateSibling(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .125 }, result);
}
[Fact]
public void Query_WithCachedExpression_Injects()
{
var query = CreateQuery().ToInjectable().Select(m => Functions.VelocityWithCachedExpression(m));
var result = query.ToList();
Assert.Equal(new[] { 200.0, .0, .125 }, result);
}
private static IQueryable<Model> CreateQuery()
{
var data = new[]
{
new Model { Id = 1, Name = "Asdf", Distance = 66, Time = .33 },
new Model { Id = 2, Name = "Narf", Distance = 0, Time = 3.14 },
new Model { Id = 3, Name = "Qwer", Distance = 8, Time = 64 }
};
return data.AsQueryable();
}
private interface IModel
{
int Id { get; set; }
string Name { get; set; }
double Distance { get; set; }
double Time { get; set; }
}
private class Model : IModel
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public double Distance { get; set; }
public double Time { get; set; }
}
private static class Functions
{
public static double VelocityWithoutSibling(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static double VelocityWithConvention(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Expression<Func<Model, double>> VelocityWithConvention()
=> v => v.Distance / v.Time;
[InjectLambda]
public static double VelocityWithMetadata(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Expression<Func<Model, double>> VelocityWithMetadata()
=> v => v.Distance / v.Time;
[InjectLambda(typeof(OtherFunctions), nameof(OtherFunctions.Narf))]
public static double VelocityWithTypeAndMethodMetadata(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda(typeof(OtherFunctions))]
public static double VelocityWithTypeMetadata(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
[InjectLambda(nameof(Narf))]
public static double VelocityWithMethodMetadata(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Expression<Func<Model, double>> Narf()
=> v => v.Distance / v.Time;
[InjectLambda]
public static double VelocityWithNullLambda(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Expression<Func<Model, double>> VelocityWithNullLambda()
=> null!;
[InjectLambda]
public static double VelocityWithoutLambda(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static IEnumerable<Func<Model, double>> VelocityWithoutLambda()
=> new Func<Model, double>[] { v => v.Distance / v.Time };
[InjectLambda]
public static double VelocityWithoutExpression(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Func<Model, double> VelocityWithoutExpression()
=> v => v.Distance / v.Time;
[InjectLambda]
public static double VelocityWithoutSignature(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static LambdaExpression VelocityWithoutSignature()
=> (Expression<Func<Model, double>>)(v => v.Distance / v.Time);
[InjectLambda]
public static double VelocityWithoutMatchingSignatureType(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Expression<Func<Model, float>> VelocityWithoutMatchingSignatureType()
=> v => (float)(v.Distance / v.Time);
[InjectLambda]
public static double VelocityWithoutMatchingSignatureSize(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Expression<Func<double, double, double>> VelocityWithoutMatchingSignatureSize()
=> (d, t) => d / t;
[InjectLambda]
public static double VelocityWithGenericArgument<TModel>(TModel value)
where TModel : IModel
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Expression<Func<TModel, double>> VelocityWithGenericArgument<TModel>()
where TModel : IModel
=> v => v.Distance / v.Time;
[InjectLambda]
public static double VelocityWithoutMatchingGenericArgument<TModel>(TModel value)
where TModel : IModel
=> throw new NotSupportedException($"Unable to process {value.Name}.");
public static Expression<Func<Model, double>> VelocityWithoutMatchingGenericArgument()
=> v => v.Distance / v.Time;
[InjectLambda]
public static double VelocityWithPrivateSibling(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
private static Expression<Func<Model, double>> VelocityWithPrivateSibling()
=> v => v.Distance / v.Time;
[InjectLambda]
public static double VelocityWithCachedExpression(Model value)
=> throw new NotSupportedException($"Unable to process {value.Name}.");
private static CachedExpression<Func<Model, double>> VelocityWithCachedExpressionExpr { get; }
= CachedExpression.From<Func<Model, double>>(v => v.Distance / v.Time);
}
private static class OtherFunctions
{
public static Expression<Func<Model, double>> Narf()
=> v => v.Distance / v.Time;
public static Expression<Func<Model, double>> VelocityWithTypeMetadata()
=> v => v.Distance / v.Time;
}
}
| |
#region Imported Types
using DeviceSQL.SQLTypes.ROC.Data;
using Microsoft.SqlServer.Server;
using System;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
#endregion
namespace DeviceSQL.SQLTypes.ROC
{
[Serializable()]
[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 28)]
public struct ROCPlusAlarmRecord : INullable, IBinarySerialize
{
#region Fields
private byte[] data;
#endregion
#region Properties
public bool IsNull
{
get;
internal set;
}
public static ROCPlusAlarmRecord Null
{
get
{
return new ROCPlusAlarmRecord() { IsNull = true };
}
}
public byte[] Data
{
get
{
if (data == null)
{
data = new byte[23];
}
return data;
}
internal set
{
data = value;
}
}
public int Index
{
get;
internal set;
}
public SqlDateTime DateTimeStamp
{
get
{
var dateTimeStamp = new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).DateTimeStamp;
return dateTimeStamp.HasValue ? dateTimeStamp.Value : SqlDateTime.Null;
}
}
public SqlString AlarmSrbxState
{
get
{
return new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).AlarmSrbxState.ToString();
}
}
public SqlString AlarmCondition
{
get
{
return new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).AlarmCondition.ToString();
}
}
public SqlString AlarmType
{
get
{
return new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).AlarmType.ToString();
}
}
public SqlString AlarmCode
{
get
{
var alarmCode = new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).AlarmCode;
return alarmCode.HasValue ? alarmCode.Value.ToString() : SqlString.Null;
}
}
public string AlarmDescription
{
get
{
return new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).AlarmDescription;
}
}
internal Tlp Tlp
{
get
{
return new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).Tlp;
}
}
public SqlByte PointType
{
get
{
return Tlp.PointType;
}
}
public SqlByte LogicalNumber
{
get
{
return Tlp.LogicalNumber;
}
}
public SqlByte ParameterNumber
{
get
{
return Tlp.Parameter;
}
}
public Parameter ParameterValue
{
get
{
if (!PointType.IsNull && !ParameterNumber.IsNull)
{
var pointType = PointType.Value;
var parameterNumber = ParameterNumber.Value;
var parameterDefinition = ParameterDatabase.ParameterDefinitions.Where(pd => pd.PointType == pointType && pd.Parameter == parameterNumber).FirstOrDefault();
var data = new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).data.Skip(19).Take(4).ToArray();
switch (parameterDefinition.DataType)
{
case "BIN":
return new Parameter() { RawType = ParameterType.BIN, RawValue = data.Take(1).ToArray() };
case "FL":
return new Parameter() { RawType = ParameterType.FL, RawValue = data };
case "INT16":
return new Parameter() { RawType = ParameterType.INT16, RawValue = data.Take(2).ToArray() };
case "INT32":
return new Parameter() { RawType = ParameterType.INT32, RawValue = data };
case "INT8":
return new Parameter() { RawType = ParameterType.INT8, RawValue = data.Take(1).ToArray() };
case "TLP":
return new Parameter() { RawType = ParameterType.TLP, RawValue = data.Take(3).ToArray() };
case "UINT16":
return new Parameter() { RawType = ParameterType.UINT16, RawValue = data.Take(2).ToArray() };
case "UINT32":
return new Parameter() { RawType = ParameterType.UINT32, RawValue = data };
case "TIME":
return new Parameter() { RawType = ParameterType.TIME, RawValue = data };
case "UINT8":
return new Parameter() { RawType = ParameterType.UINT8, RawValue = data.Take(1).ToArray() };
default:
return Parameter.Null;
}
}
else
{
return Parameter.Null;
}
}
}
public SqlSingle Value
{
get
{
var value = new Data.ROCPlusAlarmRecord(Convert.ToUInt16(Index), Data).Value;
return value.HasValue ? value.Value : SqlSingle.Null;
}
}
#endregion
#region Helper Methods
public static ROCPlusAlarmRecord Parse(SqlString stringToParse)
{
var parsedROCPlusAlarmRecord = stringToParse.Value.Split(",".ToCharArray());
var base64Bytes = Convert.FromBase64String(parsedROCPlusAlarmRecord[1]);
if (base64Bytes.Length == 23)
{
return new ROCPlusAlarmRecord() { Index = ushort.Parse(parsedROCPlusAlarmRecord[0]), Data = base64Bytes };
}
else
{
throw new ArgumentException("Input must be exactly 23 bytes");
}
}
public override string ToString()
{
return string.Format("{0},{1}", Index, Convert.ToBase64String(Data));
}
#endregion
#region Serialization Methods
public void Read(BinaryReader binaryReader)
{
IsNull = binaryReader.ReadBoolean();
Index = binaryReader.ReadInt32();
if (!IsNull)
{
Data = binaryReader.ReadBytes(23);
}
}
public void Write(BinaryWriter binaryWriter)
{
binaryWriter.Write(IsNull);
binaryWriter.Write(Index);
if (!IsNull)
{
binaryWriter.Write(Data, 0, 23);
}
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/rpc/group_booking_search_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.Booking.RPC {
public static partial class GroupBookingSearchSvc
{
static readonly string __ServiceName = "holms.types.booking.rpc.GroupBookingSearchSvc";
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest> __Marshaller_GroupBookingSvcGetFilteredBookingsListRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> __Marshaller_GroupBookingSvcGetFilteredBookingsListResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest> __Marshaller_GroupBookingSvcGetDateFilteredBookingsListRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange> __Marshaller_PbInclusiveOpsdateRange = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange.Parser.ParseFrom);
static readonly grpc::Method<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> __Method_GetFilteredBookingsList = new grpc::Method<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetFilteredBookingsList",
__Marshaller_GroupBookingSvcGetFilteredBookingsListRequest,
__Marshaller_GroupBookingSvcGetFilteredBookingsListResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> __Method_GetArrivalsByCalendarDate = new grpc::Method<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetArrivalsByCalendarDate",
__Marshaller_GroupBookingSvcGetDateFilteredBookingsListRequest,
__Marshaller_GroupBookingSvcGetFilteredBookingsListResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> __Method_GetDeparturesByCalendarDate = new grpc::Method<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetDeparturesByCalendarDate",
__Marshaller_GroupBookingSvcGetDateFilteredBookingsListRequest,
__Marshaller_GroupBookingSvcGetFilteredBookingsListResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> __Method_GetAllDuringDate = new grpc::Method<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetAllDuringDate",
__Marshaller_GroupBookingSvcGetDateFilteredBookingsListRequest,
__Marshaller_GroupBookingSvcGetFilteredBookingsListResponse);
static readonly grpc::Method<global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> __Method_GetGroupBookingForMasterClient = new grpc::Method<global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange, global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetGroupBookingForMasterClient",
__Marshaller_PbInclusiveOpsdateRange,
__Marshaller_GroupBookingSvcGetFilteredBookingsListResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.Booking.RPC.GroupBookingSearchSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of GroupBookingSearchSvc</summary>
public abstract partial class GroupBookingSearchSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetFilteredBookingsList(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetArrivalsByCalendarDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetDeparturesByCalendarDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetAllDuringDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetGroupBookingForMasterClient(global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for GroupBookingSearchSvc</summary>
public partial class GroupBookingSearchSvcClient : grpc::ClientBase<GroupBookingSearchSvcClient>
{
/// <summary>Creates a new client for GroupBookingSearchSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public GroupBookingSearchSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for GroupBookingSearchSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public GroupBookingSearchSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected GroupBookingSearchSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected GroupBookingSearchSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetFilteredBookingsList(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetFilteredBookingsList(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetFilteredBookingsList(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetFilteredBookingsList, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetFilteredBookingsListAsync(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetFilteredBookingsListAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetFilteredBookingsListAsync(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetFilteredBookingsList, null, options, request);
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetArrivalsByCalendarDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetArrivalsByCalendarDate(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetArrivalsByCalendarDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetArrivalsByCalendarDate, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetArrivalsByCalendarDateAsync(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetArrivalsByCalendarDateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetArrivalsByCalendarDateAsync(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetArrivalsByCalendarDate, null, options, request);
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetDeparturesByCalendarDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetDeparturesByCalendarDate(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetDeparturesByCalendarDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetDeparturesByCalendarDate, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetDeparturesByCalendarDateAsync(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetDeparturesByCalendarDateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetDeparturesByCalendarDateAsync(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetDeparturesByCalendarDate, null, options, request);
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetAllDuringDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetAllDuringDate(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetAllDuringDate(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetAllDuringDate, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetAllDuringDateAsync(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetAllDuringDateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetAllDuringDateAsync(global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetDateFilteredBookingsListRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetAllDuringDate, null, options, request);
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetGroupBookingForMasterClient(global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetGroupBookingForMasterClient(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse GetGroupBookingForMasterClient(global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetGroupBookingForMasterClient, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetGroupBookingForMasterClientAsync(global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetGroupBookingForMasterClientAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.GroupBookingSvcGetFilteredBookingsListResponse> GetGroupBookingForMasterClientAsync(global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetGroupBookingForMasterClient, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override GroupBookingSearchSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new GroupBookingSearchSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(GroupBookingSearchSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetFilteredBookingsList, serviceImpl.GetFilteredBookingsList)
.AddMethod(__Method_GetArrivalsByCalendarDate, serviceImpl.GetArrivalsByCalendarDate)
.AddMethod(__Method_GetDeparturesByCalendarDate, serviceImpl.GetDeparturesByCalendarDate)
.AddMethod(__Method_GetAllDuringDate, serviceImpl.GetAllDuringDate)
.AddMethod(__Method_GetGroupBookingForMasterClient, serviceImpl.GetGroupBookingForMasterClient).Build();
}
}
}
#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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using Windows.Foundation;
namespace System.Threading.Tasks
{
/// <summary>Provides a bridge between IAsyncOperation* and Task.</summary>
/// <typeparam name="TResult">Specifies the type of the result of the asynchronous operation.</typeparam>
/// <typeparam name="TProgress">Specifies the type of progress notification data.</typeparam>
internal sealed class AsyncInfoToTaskBridge<TResult, TProgress> : TaskCompletionSource<TResult>
{
/// <summary>The CancellationToken associated with this operation.</summary>
private readonly CancellationToken _ct;
/// <summary>A registration for cancellation that needs to be disposed of when the operation completes.</summary>
private CancellationTokenRegistration _ctr;
/// <summary>A flag set to true as soon as the completion callback begins to execute.</summary>
private bool _completing;
internal AsyncInfoToTaskBridge(CancellationToken cancellationToken)
{
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Task.Id, "WinRT Operation as Task", 0);
if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled)
System.Threading.Tasks.Task.AddToActiveTasks(this.Task);
_ct = cancellationToken;
}
/// <summary>The synchronization object to use for protecting the state of this bridge.</summary>
private object StateLock
{
get { return this; } // "this" isn't available publicly, so we can safely use it as a syncobj
}
/// <summary>Registers the async operation for cancellation.</summary>
/// <param name="asyncInfo">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
internal void RegisterForCancellation(IAsyncInfo asyncInfo)
{
Contract.Requires(asyncInfo != null);
try
{
if (_ct.CanBeCanceled && !_completing)
{ // benign race on m_completing... it's ok if it's not up-to-date.
var ctr = _ct.Register(ai => ((IAsyncInfo)ai).Cancel(), asyncInfo); // delegate cached by compiler
// The operation may already be completing by this time, in which case
// we might need to dispose of our new cancellation registration here.
bool disposeOfCtr = false;
lock (StateLock)
{
if (_completing)
disposeOfCtr = true;
else
_ctr = ctr; // under lock to avoid torn writes
}
if (disposeOfCtr)
ctr.TryDeregister();
}
}
catch (Exception ex)
{
// We do not want exceptions propagating out of the AsTask / GetAwaiter calls, as the
// Completed handler will instead store the exception into the returned Task.
// Such exceptions should cause the Completed handler to be invoked synchronously and thus the Task should already be completed.
if (!base.Task.IsFaulted)
{
Debug.Assert(false, String.Format("Expected base task to already be faulted but found it in state {0}", base.Task.Status));
base.TrySetException(ex);
}
}
}
/// <summary>Bridge to Completed handler on IAsyncAction.</summary>
internal void CompleteFromAsyncAction(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, null, asyncStatus);
}
/// <summary>Bridge to Completed handler on IAsyncActionWithProgress{TProgress}.</summary>
internal void CompleteFromAsyncActionWithProgress(IAsyncActionWithProgress<TProgress> asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, null, asyncStatus);
}
/// <summary>Bridge to Completed handler on IAsyncOperation{TResult}.</summary>
internal void CompleteFromAsyncOperation(IAsyncOperation<TResult> asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, ai => ((IAsyncOperation<TResult>)ai).GetResults(), asyncStatus); // delegate cached by compiler
}
/// <summary>Bridge to Completed handler on IAsyncOperationWithProgress{TResult,TProgress}.</summary>
internal void CompleteFromAsyncOperationWithProgress(IAsyncOperationWithProgress<TResult, TProgress> asyncInfo, AsyncStatus asyncStatus)
{
// delegate cached by compiler:
Complete(asyncInfo, ai => ((IAsyncOperationWithProgress<TResult, TProgress>)ai).GetResults(), asyncStatus);
}
/// <summary>Completes the task from the completed asynchronous operation.</summary>
/// <param name="asyncInfo">The asynchronous operation.</param>
/// <param name="getResultsFunction">A function used to retrieve the TResult from the async operation; may be null.</param>
/// <param name="asyncStatus">The status of the asynchronous operation.</param>
private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult> getResultsFunction, AsyncStatus asyncStatus)
{
if (asyncInfo == null)
throw new ArgumentNullException("asyncInfo");
Contract.EndContractBlock();
if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled)
{
System.Threading.Tasks.Task.RemoveFromActiveTasks(base.Task.Id);
}
try
{
Debug.Assert(asyncInfo.Status == asyncStatus,
"asyncInfo.Status does not match asyncStatus; are we dealing with a faulty IAsyncInfo implementation?");
// Assuming a correct underlying implementation, the task should not have been
// completed yet. If it is completed, we shouldn't try to do any further work
// with the operation or the task, as something is horked.
bool taskAlreadyCompleted = Task.IsCompleted;
Debug.Assert(!taskAlreadyCompleted, "Expected the task to not yet be completed.");
if (taskAlreadyCompleted)
throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
// Clean up our registration with the cancellation token, noting that we're now in the process of cleaning up.
CancellationTokenRegistration ctr;
lock (StateLock)
{
_completing = true;
ctr = _ctr; // under lock to avoid torn reads
_ctr = default(CancellationTokenRegistration);
}
ctr.TryDeregister(); // It's ok if we end up unregistering a not-initialized registration; it'll just be a nop.
try
{
// Find out how the async operation completed. It must be in a terminal state.
bool terminalState = asyncStatus == AsyncStatus.Completed
|| asyncStatus == AsyncStatus.Canceled
|| asyncStatus == AsyncStatus.Error;
Debug.Assert(terminalState, "The async operation should be in a terminal state.");
if (!terminalState)
throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
// Retrieve the completion data from the IAsyncInfo.
TResult result = default(TResult);
Exception error = null;
if (asyncStatus == AsyncStatus.Error)
{
error = asyncInfo.ErrorCode;
// Defend against a faulty IAsyncInfo implementation:
if (error == null)
{
Debug.Assert(false, "IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
error = new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
}
else
{
error = RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(asyncInfo.ErrorCode);
}
}
else if (asyncStatus == AsyncStatus.Completed && getResultsFunction != null)
{
try
{
result = getResultsFunction(asyncInfo);
}
catch (Exception resultsEx)
{
// According to the WinRT team, this can happen in some egde cases, such as marshalling errors in GetResults.
error = resultsEx;
asyncStatus = AsyncStatus.Error;
}
}
// Nothing to retrieve for a canceled operation or for a completed operation with no result.
// Complete the task based on the previously retrieved results:
bool success = false;
switch (asyncStatus)
{
case AsyncStatus.Completed:
if (AsyncCausalityTracer.LoggingOn)
{
AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, base.Task.Id, AsyncCausalityStatus.Completed);
}
success = base.TrySetResult(result);
break;
case AsyncStatus.Error:
Debug.Assert(error != null, "The error should have been retrieved previously.");
success = base.TrySetException(error);
break;
case AsyncStatus.Canceled:
success = base.TrySetCanceled(_ct.IsCancellationRequested ? _ct : new CancellationToken(true));
break;
}
Debug.Assert(success, "Expected the outcome to be successfully transfered to the task.");
}
catch (Exception exc)
{
// This really shouldn't happen, but could in a variety of misuse cases
// such as a faulty underlying IAsyncInfo implementation.
Debug.Assert(false, string.Format("Unexpected exception in Complete: {0}", exc.ToString()));
if (AsyncCausalityTracer.LoggingOn)
{
AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, base.Task.Id, AsyncCausalityStatus.Error);
}
// For these cases, store the exception into the task so that it makes its way
// back to the caller. Only if something went horribly wrong and we can't store the exception
// do we allow it to be propagated out to the invoker of the Completed handler.
if (!base.TrySetException(exc))
{
Debug.Assert(false, "The task was already completed and thus the exception couldn't be stored.");
throw;
}
}
}
finally
{
// We may be called on an STA thread which we don't own, so make sure that the RCW is released right
// away. Otherwise, if we leave it up to the finalizer, the apartment may already be gone.
if (Marshal.IsComObject(asyncInfo))
Marshal.ReleaseComObject(asyncInfo);
}
} // private void Complete(..)
} // class AsyncInfoToTaskBridge<TResult, TProgress>
} // namespace
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using JetBrains.Annotations;
namespace NLog
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using NLog.Common;
using NLog.Internal;
using NLog.Layouts;
using NLog.MessageTemplates;
using NLog.Time;
/// <summary>
/// Represents the logging event.
/// </summary>
public class LogEventInfo
{
/// <summary>
/// Gets the date of the first log event created.
/// </summary>
public static readonly DateTime ZeroDate = DateTime.UtcNow;
internal static readonly LogMessageFormatter StringFormatMessageFormatter = GetStringFormatMessageFormatter;
internal static LogMessageFormatter DefaultMessageFormatter { get; private set; } = LogMessageTemplateFormatter.DefaultAuto.MessageFormatter;
private static int globalSequenceId;
/// <summary>
/// The formatted log message.
/// </summary>
private string _formattedMessage;
/// <summary>
/// The log message including any parameter placeholders
/// </summary>
private string _message;
private object[] _parameters;
private IFormatProvider _formatProvider;
private LogMessageFormatter _messageFormatter = DefaultMessageFormatter;
private IDictionary<Layout, object> _layoutCache;
private PropertiesDictionary _properties;
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
public LogEventInfo()
{
TimeStamp = TimeSource.Current.Time;
SequenceID = Interlocked.Increment(ref globalSequenceId);
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message)
: this(level, loggerName, null, message, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="messageTemplateParameters">Already parsed message template parameters.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IList<MessageTemplateParameter> messageTemplateParameters)
: this(level, loggerName, null, message, null, null)
{
if (messageTemplateParameters != null)
{
var messagePropertyCount = messageTemplateParameters.Count;
if (messagePropertyCount > 0)
{
var messageProperties = new MessageTemplateParameter[messagePropertyCount];
for (int i = 0; i < messagePropertyCount; ++i)
messageProperties[i] = messageTemplateParameters[i];
_properties = new PropertiesDictionary(messageProperties);
}
}
}
#if !NET3_5 && !NET4_0 && !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Override default Logger name. Default <see cref="Logger.Name"/> is used when <c>null</c></param>
/// <param name="message">Log message.</param>
/// <param name="eventProperties">List of event-properties</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IReadOnlyList<KeyValuePair<object, object>> eventProperties)
: this(level, loggerName, null, message, null, null)
{
if (eventProperties?.Count > 0)
{
_properties = new PropertiesDictionary(eventProperties);
}
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
: this(level, loggerName, formatProvider, message, parameters, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
/// <param name="exception">Exception information.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception): this()
{
Level = level;
LoggerName = loggerName;
_formatProvider = formatProvider;
_message = message;
Parameters = parameters;
Exception = exception;
if (NeedToPreformatMessage(parameters))
{
CalcFormattedMessage();
}
}
/// <summary>
/// Gets the unique identifier of log event which is automatically generated
/// and monotonously increasing.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "Backwards compatibility")]
// ReSharper disable once InconsistentNaming
public int SequenceID { get; private set; }
/// <summary>
/// Gets or sets the timestamp of the logging event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp", Justification = "Backwards compatibility.")]
public DateTime TimeStamp { get; set; }
/// <summary>
/// Gets or sets the level of the logging event.
/// </summary>
public LogLevel Level { get; set; }
[CanBeNull] internal CallSiteInformation CallSiteInformation { get; private set; }
[NotNull]
internal CallSiteInformation GetCallSiteInformationInternal() { return CallSiteInformation ?? (CallSiteInformation = new CallSiteInformation()); }
/// <summary>
/// Gets a value indicating whether stack trace has been set for this event.
/// </summary>
public bool HasStackTrace => CallSiteInformation?.StackTrace != null;
/// <summary>
/// Gets the stack frame of the method that did the logging.
/// </summary>
public StackFrame UserStackFrame => CallSiteInformation?.UserStackFrame;
/// <summary>
/// Gets the number index of the stack frame that represents the user
/// code (not the NLog code).
/// </summary>
public int UserStackFrameNumber => CallSiteInformation?.UserStackFrameNumberLegacy ?? CallSiteInformation?.UserStackFrameNumber ?? 0;
/// <summary>
/// Gets the entire stack trace.
/// </summary>
public StackTrace StackTrace => CallSiteInformation?.StackTrace;
/// <summary>
/// Gets the callsite class name
/// </summary>
public string CallerClassName => CallSiteInformation?.GetCallerClassName(null, true, true, true);
/// <summary>
/// Gets the callsite member function name
/// </summary>
public string CallerMemberName => CallSiteInformation?.GetCallerMemberName(null, false, true, true);
/// <summary>
/// Gets the callsite source file path
/// </summary>
public string CallerFilePath => CallSiteInformation?.GetCallerFilePath(0);
/// <summary>
/// Gets the callsite source file line number
/// </summary>
public int CallerLineNumber => CallSiteInformation?.GetCallerLineNumber(0) ?? 0;
/// <summary>
/// Gets or sets the exception information.
/// </summary>
[CanBeNull]
public Exception Exception { get; set; }
/// <summary>
/// Gets or sets the logger name.
/// </summary>
[CanBeNull]
public string LoggerName { get; set; }
/// <summary>
/// Gets the logger short name.
/// </summary>
/// <remarks>This property was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks>
[Obsolete("This property should not be used. Marked obsolete on NLog 2.0")]
public string LoggerShortName
{
// NOTE: This property is not referenced by NLog code anymore.
get
{
if (LoggerName == null) return LoggerName;
int lastDot = LoggerName.LastIndexOf('.');
if (lastDot >= 0)
{
return LoggerName.Substring(lastDot + 1);
}
return LoggerName;
}
}
/// <summary>
/// Gets or sets the log message including any parameter placeholders.
/// </summary>
public string Message
{
get => _message;
set
{
bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters();
_message = value;
ResetFormattedMessage(rebuildMessageTemplateParameters);
}
}
/// <summary>
/// Gets or sets the parameter values or null if no parameters have been specified.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "For backwards compatibility.")]
public object[] Parameters
{
get => _parameters;
set
{
bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters();
_parameters = value;
ResetFormattedMessage(rebuildMessageTemplateParameters);
}
}
/// <summary>
/// Gets or sets the format provider that was provided while logging or <see langword="null" />
/// when no formatProvider was specified.
/// </summary>
public IFormatProvider FormatProvider
{
get => _formatProvider;
set
{
if (_formatProvider != value)
{
_formatProvider = value;
ResetFormattedMessage(false);
}
}
}
/// <summary>
/// Gets or sets the message formatter for generating <see cref="LogEventInfo.FormattedMessage"/>
/// Uses string.Format(...) when nothing else has been configured.
/// </summary>
public LogMessageFormatter MessageFormatter
{
get => _messageFormatter;
set
{
_messageFormatter = value ?? StringFormatMessageFormatter;
ResetFormattedMessage(false);
}
}
/// <summary>
/// Gets the formatted message.
/// </summary>
public string FormattedMessage
{
get
{
if (_formattedMessage == null)
{
CalcFormattedMessage();
}
return _formattedMessage;
}
}
/// <summary>
/// Checks if any per-event properties (Without allocation)
/// </summary>
public bool HasProperties
{
get
{
if (_properties != null)
{
return _properties.Count > 0;
}
else
{
return CreateOrUpdatePropertiesInternal(false)?.Count > 0;
}
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
public IDictionary<object, object> Properties => CreateOrUpdatePropertiesInternal();
/// <summary>
/// Gets the dictionary of per-event context properties.
/// Internal helper for the PropertiesDictionary type.
/// </summary>
/// <param name="forceCreate">Create the event-properties dictionary, even if no initial template parameters</param>
/// <param name="templateParameters">Provided when having parsed the message template and capture template parameters (else null)</param>
/// <returns></returns>
internal PropertiesDictionary CreateOrUpdatePropertiesInternal(bool forceCreate = true, IList<MessageTemplateParameter> templateParameters = null)
{
var properties = _properties;
if (properties == null)
{
if (forceCreate || templateParameters?.Count > 0 || (templateParameters == null && HasMessageTemplateParameters))
{
properties = new PropertiesDictionary(templateParameters);
Interlocked.CompareExchange(ref _properties, properties, null);
if (templateParameters == null && (!forceCreate || HasMessageTemplateParameters))
{
// Trigger capture of MessageTemplateParameters from logevent-message
CalcFormattedMessage();
}
}
}
else if (templateParameters != null)
{
properties.MessageProperties = templateParameters;
}
return _properties;
}
private bool HasMessageTemplateParameters
{
get
{
// Have not yet parsed/rendered the FormattedMessage, so check with ILogMessageFormatter
if (_formattedMessage == null && _parameters?.Length > 0)
{
var logMessageFormatter = _messageFormatter?.Target as ILogMessageFormatter;
return logMessageFormatter?.HasProperties(this) ?? false;
}
return false;
}
}
/// <summary>
/// Gets the named parameters extracted from parsing <see cref="Message"/> as MessageTemplate
/// </summary>
public MessageTemplateParameters MessageTemplateParameters
{
get
{
if (_properties != null && _properties.MessageProperties.Count > 0)
{
return new MessageTemplateParameters(_properties.MessageProperties, _message, _parameters);
}
else if (_parameters?.Length > 0)
{
return new MessageTemplateParameters(_message, _parameters);
}
else
{
return MessageTemplateParameters.Empty; // No parameters, means nothing to parse
}
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
/// <remarks>This property was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks>
[Obsolete("Use LogEventInfo.Properties instead. Marked obsolete on NLog 2.0", true)]
public IDictionary Context => CreateOrUpdatePropertiesInternal().EventContext;
/// <summary>
/// Creates the null event.
/// </summary>
/// <returns>Null log event.</returns>
public static LogEventInfo CreateNullEvent()
{
return new LogEventInfo(LogLevel.Off, string.Empty, string.Empty);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message)
{
return new LogEventInfo(logLevel, loggerName, null, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message)
{
Exception exception = message as Exception;
if (exception == null && message is LogEventInfo logEvent)
{
logEvent.LoggerName = loggerName;
logEvent.Level = logLevel;
logEvent.FormatProvider = formatProvider ?? logEvent.FormatProvider;
return logEvent;
}
return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message }, exception);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
/// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("use Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, string message) instead. Marked obsolete before v4.3.11")]
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message, Exception exception)
{
return new LogEventInfo(logLevel, loggerName, null, message, null, exception);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message)
{
return Create(logLevel, loggerName, exception, formatProvider, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="exception">The exception.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Instance of <see cref="LogEventInfo"/>.</returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName,formatProvider, message, parameters, exception);
}
/// <summary>
/// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns>
public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation)
{
return new AsyncLogEventInfo(this, asyncContinuation);
}
/// <summary>
/// Returns a string representation of this log event.
/// </summary>
/// <returns>String representation of the log event.</returns>
public override string ToString()
{
return $"Log Event: Logger='{LoggerName}' Level={Level} Message='{FormattedMessage}' SequenceID={SequenceID}";
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace (Negative means NLog should skip stackframes from System-assemblies).</param>
public void SetStackTrace(StackTrace stackTrace, int userStackFrame)
{
GetCallSiteInformationInternal().SetStackTrace(stackTrace, userStackFrame >= 0 ? userStackFrame : (int?)null);
}
/// <summary>
/// Sets the details retrieved from the Caller Information Attributes
/// </summary>
/// <param name="callerClassName"></param>
/// <param name="callerMemberName"></param>
/// <param name="callerFilePath"></param>
/// <param name="callerLineNumber"></param>
public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber)
{
GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber);
}
internal void AddCachedLayoutValue(Layout layout, object value)
{
if (_layoutCache == null)
{
var dictionary = new Dictionary<Layout, object>();
dictionary[layout] = value; // Faster than collection initializer
if (Interlocked.CompareExchange(ref _layoutCache, dictionary, null) == null)
{
return; // No need to use lock
}
}
lock (_layoutCache)
{
_layoutCache[layout] = value;
}
}
internal bool TryGetCachedLayoutValue(Layout layout, out object value)
{
if (_layoutCache == null)
{
// We don't need lock to see if dictionary has been created
value = null;
return false;
}
lock (_layoutCache)
{
if (_layoutCache.Count == 0)
{
value = null;
return false;
}
return _layoutCache.TryGetValue(layout, out value);
}
}
private static bool NeedToPreformatMessage(object[] parameters)
{
// we need to preformat message if it contains any parameters which could possibly
// do logging in their ToString()
if (parameters == null || parameters.Length == 0)
{
return false;
}
if (parameters.Length > 5)
{
// too many parameters, too costly to check
return true;
}
for (int i = 0; i < parameters.Length; ++i)
{
if (!IsSafeToDeferFormatting(parameters[i]))
return true;
}
return false;
}
private static bool IsSafeToDeferFormatting(object value)
{
return Convert.GetTypeCode(value) != TypeCode.Object;
}
internal bool IsLogEventMutableSafe()
{
if (Exception != null || _formattedMessage != null)
return false;
var properties = CreateOrUpdatePropertiesInternal(false);
if (properties == null || properties.Count == 0)
return true; // No mutable state, no need to precalculate
if (properties.Count > 5)
return false; // too many properties, too costly to check
if (properties.Count == _parameters?.Length && properties.Count == properties.MessageProperties.Count)
return true; // Already checked formatted message, no need to do it twice
return HasImmutableProperties(properties);
}
private static bool HasImmutableProperties(PropertiesDictionary properties)
{
if (properties.Count == properties.MessageProperties.Count)
{
// Skip enumerator allocation when all properties comes from the message-template
for (int i = 0; i < properties.MessageProperties.Count; ++i)
{
var property = properties.MessageProperties[i];
if (!IsSafeToDeferFormatting(property.Value))
return false;
}
}
else
{
// Already spent the time on allocating a Dictionary, also have time for an enumerator
foreach (var property in properties)
{
if (!IsSafeToDeferFormatting(property.Value))
return false;
}
}
return true;
}
internal bool CanLogEventDeferMessageFormat()
{
if (_formattedMessage != null)
return false; // Already formatted, cannot be deferred
if (_parameters == null || _parameters.Length == 0)
return false; // No parameters to format
if (_message?.Length < 256 && ReferenceEquals(MessageFormatter, LogMessageTemplateFormatter.DefaultAuto.MessageFormatter))
return true; // Not too expensive to scan for properties
else
return false;
}
private static string GetStringFormatMessageFormatter(LogEventInfo logEvent)
{
if (logEvent.Parameters == null || logEvent.Parameters.Length == 0)
{
return logEvent.Message;
}
else
{
return string.Format(logEvent.FormatProvider ?? CultureInfo.CurrentCulture, logEvent.Message, logEvent.Parameters);
}
}
private void CalcFormattedMessage()
{
try
{
_formattedMessage = _messageFormatter(this);
}
catch (Exception exception)
{
_formattedMessage = Message;
InternalLogger.Warn(exception, "Error when formatting a message.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
internal void AppendFormattedMessage(ILogMessageFormatter messageFormatter, System.Text.StringBuilder builder)
{
if (_formattedMessage != null)
{
builder.Append(_formattedMessage);
}
else
{
int originalLength = builder.Length;
try
{
messageFormatter.AppendFormattedMessage(this, builder);
}
catch (Exception ex)
{
builder.Length = originalLength;
builder.Append(_message ?? string.Empty);
InternalLogger.Warn(ex, "Error when formatting a message.");
if (ex.MustBeRethrown())
{
throw;
}
}
}
}
private void ResetFormattedMessage(bool rebuildMessageTemplateParameters)
{
_formattedMessage = null;
if (rebuildMessageTemplateParameters && HasMessageTemplateParameters)
{
CalcFormattedMessage();
}
}
private bool ResetMessageTemplateParameters()
{
if (_properties != null)
{
if (HasMessageTemplateParameters)
_properties.MessageProperties = null;
return _properties.MessageProperties.Count == 0;
}
return false;
}
/// <summary>
/// Set the <see cref="DefaultMessageFormatter"/>
/// </summary>
/// <param name="mode">true = Always, false = Never, null = Auto Detect</param>
internal static void SetDefaultMessageFormatter(bool? mode)
{
if (mode == true)
{
InternalLogger.Info("Message Template Format always enabled");
DefaultMessageFormatter = LogMessageTemplateFormatter.Default.MessageFormatter;
}
else if (mode == false)
{
InternalLogger.Info("Message Template String Format always enabled");
DefaultMessageFormatter = StringFormatMessageFormatter;
}
else
{
//null = auto
InternalLogger.Info("Message Template Auto Format enabled");
DefaultMessageFormatter = LogMessageTemplateFormatter.DefaultAuto.MessageFormatter;
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// MenuScreen.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Input;
#endregion
namespace GameStateManagement
{
/// <summary>
/// Base class for screens that contain a menu of options. The user can
/// move up and down to select an entry, or cancel to back out of the screen.
/// </summary>
abstract class MenuScreen : GameScreen
{
#region Fields
// the number of pixels to pad above and below menu entries for touch input
const int menuEntryPadding = 35;
List<MenuEntry> menuEntries = new List<MenuEntry>();
int selectedEntry = 0;
string menuTitle;
#endregion
#region Properties
/// <summary>
/// Gets the list of menu entries, so derived classes can add
/// or change the menu contents.
/// </summary>
protected IList<MenuEntry> MenuEntries
{
get { return menuEntries; }
}
#endregion
#region Initialization
/// <summary>
/// Constructor.
/// </summary>
public MenuScreen(string menuTitle)
{
// menus generally only need Tap for menu selection
EnabledGestures = GestureType.Tap;
this.menuTitle = menuTitle;
TransitionOnTime = TimeSpan.FromSeconds(0.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
}
#endregion
#region Handle Input
/// <summary>
/// Allows the screen to create the hit bounds for a particular menu entry.
/// </summary>
protected virtual Rectangle GetMenuEntryHitBounds(MenuEntry entry)
{
// the hit bounds are the entire width of the screen, and the height of the entry
// with some additional padding above and below.
return new Rectangle(
0,
(int)entry.Position.Y - menuEntryPadding,
ScreenManager.GraphicsDevice.Viewport.Width,
entry.GetHeight(this) + (menuEntryPadding * 2));
}
/// <summary>
/// Responds to user input, changing the selected entry and accepting
/// or cancelling the menu.
/// </summary>
public override void HandleInput(InputState input)
{
// we cancel the current menu screen if the user presses the back button
PlayerIndex player;
if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player))
{
OnCancel(player);
}
// look for any taps that occurred and select any entries that were tapped
foreach (GestureSample gesture in input.Gestures)
{
if (gesture.GestureType == GestureType.Tap)
{
// convert the position to a Point that we can test against a Rectangle
Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y);
// iterate the entries to see if any were tapped
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
if (GetMenuEntryHitBounds(menuEntry).Contains(tapLocation))
{
// select the entry. since gestures are only available on Windows Phone,
// we can safely pass PlayerIndex.One to all entries since there is only
// one player on Windows Phone.
OnSelectEntry(i, PlayerIndex.One);
}
}
}
}
}
/// <summary>
/// Handler for when the user has chosen a menu entry.
/// </summary>
protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
{
menuEntries[entryIndex].OnSelectEntry(playerIndex);
}
/// <summary>
/// Handler for when the user has cancelled the menu.
/// </summary>
protected virtual void OnCancel(PlayerIndex playerIndex)
{
ExitScreen();
}
/// <summary>
/// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
/// </summary>
protected void OnCancel(object sender, PlayerIndexEventArgs e)
{
OnCancel(e.PlayerIndex);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen the chance to position the menu entries. By default
/// all menu entries are lined up in a vertical list, centered on the screen.
/// </summary>
protected virtual void UpdateMenuEntryLocations()
{
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// start at Y = 475; each X value is generated per entry
Vector2 position = new Vector2(0f, 475f);
// update each menu entry's location in turn
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
// each entry is to be centered horizontally
position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2;
if (ScreenState == ScreenState.TransitionOn)
position.X -= transitionOffset * 256;
else
position.X += transitionOffset * 512;
// set the entry's position
menuEntry.Position = position;
// move down for the next entry the size of this entry plus our padding
position.Y += menuEntry.GetHeight(this) + (menuEntryPadding * 2);
}
}
/// <summary>
/// Updates the menu.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
// Update each nested MenuEntry object.
for (int i = 0; i < menuEntries.Count; i++)
{
bool isSelected = IsActive && (i == selectedEntry);
menuEntries[i].Update(this, isSelected, gameTime);
}
}
/// <summary>
/// Draws the menu.
/// </summary>
public override void Draw(GameTime gameTime)
{
// make sure our entries are in the right place before we draw them
UpdateMenuEntryLocations();
GraphicsDevice graphics = ScreenManager.GraphicsDevice;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
SpriteFont font = ScreenManager.Font;
spriteBatch.Begin();
// Draw each menu entry in turn.
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
bool isSelected = IsActive && (i == selectedEntry);
menuEntry.Draw(this, isSelected, gameTime);
}
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// Draw the menu title centered on the screen
Vector2 titlePosition = new Vector2(graphics.Viewport.Width / 2, 375);
Vector2 titleOrigin = font.MeasureString(menuTitle) / 2;
Color titleColor = new Color(192, 192, 192) * TransitionAlpha;
float titleScale = 1.25f;
titlePosition.Y -= transitionOffset * 100;
spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0,
titleOrigin, titleScale, SpriteEffects.None, 0);
spriteBatch.End();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using Blade;
using Maui.Data.Recognition.Html;
using Maui.Data.Recognition.Html.WinForms;
using Maui.Data.Recognition.Spec;
namespace Maui.Data.Recognition.Core
{
public class LegacyDocumentBrowser : ManagedObject, IServiceComponent, IDocumentBrowser
{
private DownloadController myDownloadController;
private bool myIsInitialized = false;
private bool myOwnWebBrowser = false;
private const int DownloadChunkSize = 1024; // bytes
public LegacyDocumentBrowser()
: this( new WebBrowser() )
{
myOwnWebBrowser = true;
}
/// <summary>
/// Creates a WebScrapSC with a given/existing WebBrowser control.
/// The ownership of the WebBrowser control passed is not taken over.
/// </summary>
public LegacyDocumentBrowser( WebBrowser webBrowser )
{
myOwnWebBrowser = false;
Browser = webBrowser;
Browser.Navigating += WebBrowser_Navigating;
myDownloadController = new DownloadController();
myDownloadController.Options = BrowserOptions.NotRunActiveX | BrowserOptions.NoActiveXDownload |
BrowserOptions.NoBehaviors | BrowserOptions.NoJava | BrowserOptions.NoScripts |
BrowserOptions.Utf8;
}
protected override void Dispose( bool disposing )
{
try
{
if ( IsDisposed )
{
return;
}
if ( disposing )
{
// TODO: restore the old proxy
if ( myOwnWebBrowser )
{
Browser.Dispose();
}
}
Browser = null;
}
finally
{
base.Dispose( disposing );
}
}
public void Init( ServiceProvider serviceProvider )
{
}
public WebBrowser Browser
{
get;
private set;
}
public HtmlDocument Document
{
get { return Browser.Document; }
}
/// <summary>
/// Default options:
/// BrowserOptions.DontRunActiveX | BrowserOptions.NoActiveXDownload |
/// BrowserOptions.NoBehaviours | BrowserOptions.NoJava | BrowserOptions.NoScripts |
/// BrowserOptions.UTF8
/// </summary>
public IDownloadController DownloadController
{
get { return myDownloadController; }
}
public void Navigate( string url )
{
Browser.Navigate( url );
}
/// <summary>
/// Loads a document specified by the given user steps.
/// Regular expressions in response URLs (embedded in {}) are matched. The
/// resulting parameter is set to the next request URL using
/// string.Format() at placeholder {0}.
/// </summary>
public IHtmlDocument LoadDocument( IEnumerable<NavigatorUrl> navigationSteps )
{
string url = NavigateToFinalSite( navigationSteps );
return LoadDocument( url );
}
/// <summary>
/// Navigates to the final site specified by the user steps and
/// returns the Uri of the last site.
/// </summary>
private string NavigateToFinalSite( IEnumerable<NavigatorUrl> navigationSteps )
{
IHtmlDocument doc = null;
string param = null;
var last = navigationSteps.Last().UrlString;
foreach ( NavigatorUrl navUrl in navigationSteps )
{
this.Require( x => navUrl.UrlType != UriType.None );
if ( navUrl.UrlType == UriType.Request )
{
string url = navUrl.UrlString;
if ( param != null )
{
url = string.Format( url, param );
}
else if ( HasPlaceHolder( url ) )
{
var ex = new ApplicationException( "Did not find a parameter for placeholder" );
ex.Data[ "Url" ] = url;
throw ex;
}
if ( navUrl.UrlString == last )
{
return url;
}
else
{
doc = LoadDocument( url );
}
}
else
{
// get param from response url if any
param = PatternMatching.MatchEmbeddedRegex( navUrl.UrlString, doc.Url.ToString() );
}
}
// list empty?
return null;
}
private IHtmlDocument LoadDocument( string url )
{
Browser.Navigate( url );
while ( !
(Browser.ReadyState == WebBrowserReadyState.Complete ||
(Browser.ReadyState == WebBrowserReadyState.Interactive && !Browser.IsBusy)) )
{
Thread.Sleep( 100 );
Application.DoEvents();
}
return new HtmlDocumentAdapter(Browser.Document);
}
public IDocument GetDocument( Navigation navi )
{
var doc = TryNavigateWithWildcards( navi );
if ( doc != null )
{
return doc;
}
if ( navi.DocumentType == DocumentType.Html )
{
return new HtmlDocumentHandle( LoadDocument( navi.Uris ) );
}
else if ( navi.DocumentType == DocumentType.Text )
{
return new TextDocument( DownloadFile( navi.Uris ) );
}
throw new NotSupportedException( "DocumentType: " + navi.DocumentType );
}
/// <summary>
/// Downloads a file specified by the given user steps.
/// </summary>
private string DownloadFile( IEnumerable<NavigatorUrl> navigationSteps )
{
string url = NavigateToFinalSite( navigationSteps );
return DownloadFile( new Uri(url) );
}
private string DownloadFile( string uri )
{
// TODO: check for protocol in url - maybe the file is local
return DownloadFile( new Uri( uri ) );
}
private string DownloadFile( Uri uri )
{
if ( uri.IsFile )
{
return ( File.Exists( uri.LocalPath ) ? uri.LocalPath : null );
}
WebRequest request = WebRequest.Create( uri );
HttpWebResponse response = null;
Stream responseStream = null;
try
{
// Send the 'HttpWebRequest' and wait for response.
response = (HttpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
//System.Text.Encoding ec = System.Text.Encoding.GetEncoding( "utf-8" );
string file = Path.GetTempFileName();
using ( StreamReader reader = new StreamReader( responseStream ) )
{
char[] chars = new Char[ DownloadChunkSize ];
int count = reader.Read( chars, 0, DownloadChunkSize );
using ( StreamWriter writer = new StreamWriter( file ) )
{
while ( count > 0 )
{
writer.Write( chars, 0, count );
count = reader.Read( chars, 0, DownloadChunkSize );
}
}
}
// TODO: who removes this temp file?
return file;
}
finally
{
if ( response != null )
{
response.Close();
}
if ( responseStream != null )
{
responseStream.Close();
}
}
}
private IDocument Navigate( DocumentType docType, NavigatorUrl url )
{
if ( docType == DocumentType.Html )
{
return new HtmlDocumentHandle( LoadDocument( url.UrlString ) );
}
else if ( docType == DocumentType.Text )
{
return new TextDocument( DownloadFile( url.UrlString ) );
}
throw new NotSupportedException( "DocumentType: " + docType );
}
// TODO: this should not only happen when loading a document with a complete
// navigation -> policy based?
private IDocument TryNavigateWithWildcards( Navigation navi )
{
if ( navi.Uris.Count != 1 )
{
// we can only handle single urls
return null;
}
var url = navi.Uris[ 0 ];
Uri uri = new Uri( url.UrlString );
if ( !uri.IsFile && !uri.IsUnc )
{
// we cannot handle e.g. http now
return null;
}
// currently we only handle "/xyz/*/file.txt"
int pos = url.UrlString.IndexOf( "/*/" );
if ( pos <= 0 )
{
// no pattern found
return null;
}
string root = url.UrlString.Substring( 0, pos );
string file = url.UrlString.Substring( pos + 3 );
string[] dirs = Directory.GetDirectories( root, "*" );
// now try everything with "or"
// first path which returns s.th. wins
foreach ( string dir in dirs )
{
string tmpFile = Path.Combine( dir, file );
if ( !File.Exists( tmpFile ) )
{
continue;
}
var doc = Navigate( navi.DocumentType, new NavigatorUrl( url.UrlType, tmpFile ) );
if ( doc != null )
{
return doc;
}
}
// so in this case we got a pattern navigation url but we were not able
// to navigate to that url --> throw an exception
throw new Exception( "Failed to navigate to the document" );
}
private bool HasPlaceHolder( string url )
{
int begin = url.IndexOf( '{' );
int end = url.IndexOf( '}' );
if ( begin < 0 || end < 0 )
{
return false;
}
return Math.Abs( end - begin ) < 3;
}
private void WebBrowser_Navigating( object sender, WebBrowserNavigatingEventArgs e )
{
if ( IsDisposed )
{
return;
}
if ( myIsInitialized )
{
return;
}
myDownloadController.HookUp( Browser );
myIsInitialized = true;
}
private Uri SelectUrl( IList<string> urls )
{
int idx = 0;
string url = urls[ idx ];
urls.RemoveAt( idx );
return new Uri( url );
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using GitVersion.Cache;
using GitVersion.Configuration;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using Microsoft.Extensions.Options;
namespace GitVersion.VersionCalculation.Cache
{
public class GitVersionCacheKeyFactory : IGitVersionCacheKeyFactory
{
private readonly IFileSystem fileSystem;
private readonly ILog log;
private readonly IOptions<GitVersionOptions> options;
private readonly IConfigFileLocator configFileLocator;
private readonly IGitRepository gitRepository;
private readonly IGitRepositoryInfo repositoryInfo;
public GitVersionCacheKeyFactory(IFileSystem fileSystem, ILog log,
IOptions<GitVersionOptions> options, IConfigFileLocator configFileLocator,
IGitRepository gitRepository, IGitRepositoryInfo repositoryInfo)
{
this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
this.log = log ?? throw new ArgumentNullException(nameof(log));
this.options = options ?? throw new ArgumentNullException(nameof(options));
this.configFileLocator = configFileLocator ?? throw new ArgumentNullException(nameof(configFileLocator));
this.gitRepository = gitRepository ?? throw new ArgumentNullException(nameof(gitRepository));
this.repositoryInfo = repositoryInfo ?? throw new ArgumentNullException(nameof(repositoryInfo));
}
public GitVersionCacheKey Create(Config overrideConfig)
{
var gitSystemHash = GetGitSystemHash();
var configFileHash = GetConfigFileHash();
var repositorySnapshotHash = GetRepositorySnapshotHash();
var overrideConfigHash = GetOverrideConfigHash(overrideConfig);
var compositeHash = GetHash(gitSystemHash, configFileHash, repositorySnapshotHash, overrideConfigHash);
return new GitVersionCacheKey(compositeHash);
}
private string GetGitSystemHash()
{
var dotGitDirectory = repositoryInfo.DotGitDirectory;
// traverse the directory and get a list of files, use that for GetHash
var contents = CalculateDirectoryContents(Path.Combine(dotGitDirectory, "refs"));
return GetHash(contents.ToArray());
}
// based on https://msdn.microsoft.com/en-us/library/bb513869.aspx
private List<string> CalculateDirectoryContents(string root)
{
var result = new List<string>();
// Data structure to hold names of subfolders to be
// examined for files.
var dirs = new Stack<string>();
if (!Directory.Exists(root))
{
throw new DirectoryNotFoundException($"Root directory does not exist: {root}");
}
dirs.Push(root);
while (dirs.Any())
{
var currentDir = dirs.Pop();
var di = new DirectoryInfo(currentDir);
result.Add(di.Name);
string[] subDirs;
try
{
subDirs = Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
log.Error(e.Message);
continue;
}
catch (DirectoryNotFoundException e)
{
log.Error(e.Message);
continue;
}
string[] files;
try
{
files = Directory.GetFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
log.Error(e.Message);
continue;
}
catch (DirectoryNotFoundException e)
{
log.Error(e.Message);
continue;
}
foreach (var file in files)
{
try
{
var fi = new FileInfo(file);
result.Add(fi.Name);
result.Add(File.ReadAllText(file));
}
catch (IOException e)
{
log.Error(e.Message);
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
// push in reverse order
for (var i = subDirs.Length - 1; i >= 0; i--)
{
dirs.Push(subDirs[i]);
}
}
return result;
}
private string GetRepositorySnapshotHash()
{
var head = gitRepository.Head;
if (head.Tip == null)
{
return head.Name.Canonical;
}
var hash = string.Join(":", head.Name.Canonical, head.Tip.Sha);
return GetHash(hash);
}
private static string GetOverrideConfigHash(Config overrideConfig)
{
if (overrideConfig == null)
{
return string.Empty;
}
// Doesn't depend on command line representation and
// includes possible changes in default values of Config per se.
var stringBuilder = new StringBuilder();
using (var stream = new StringWriter(stringBuilder))
{
ConfigSerializer.Write(overrideConfig, stream);
stream.Flush();
}
var configContent = stringBuilder.ToString();
return GetHash(configContent);
}
private string GetConfigFileHash()
{
// will return the same hash even when config file will be moved
// from workingDirectory to rootProjectDirectory. It's OK. Config essentially is the same.
var configFilePath = configFileLocator.SelectConfigFilePath(options.Value, repositoryInfo);
if (!fileSystem.Exists(configFilePath))
{
return string.Empty;
}
var configFileContent = fileSystem.ReadAllText(configFilePath);
return GetHash(configFileContent);
}
private static string GetHash(params string[] textsToHash)
{
var textToHash = string.Join(":", textsToHash);
return GetHash(textToHash);
}
private static string GetHash(string textToHash)
{
if (string.IsNullOrEmpty(textToHash))
{
return string.Empty;
}
using var sha1 = SHA1.Create();
var bytes = Encoding.UTF8.GetBytes(textToHash);
var hashedBytes = sha1.ComputeHash(bytes);
var hashedString = BitConverter.ToString(hashedBytes);
return hashedString.Replace("-", "");
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace tk2dEditor.SpriteCollectionEditor
{
// As nasty as this is, its a necessary evil for backwards compatibility
public class SpriteCollectionProxy
{
public SpriteCollectionProxy()
{
}
public SpriteCollectionProxy(tk2dSpriteCollection obj)
{
this.obj = obj;
CopyFromSource(true);
}
public SpriteCollectionProxy(tk2dSpriteCollection obj, bool copyBuilt)
{
this.obj = obj;
CopyFromSource(copyBuilt);
}
public void CopyBuiltFromSource(tk2dSpriteCollection source) {
SpriteCollectionProxy target = this;
target.spriteCollection = source.spriteCollection;
CopyArray(ref target.altMaterials, source.altMaterials);
CopyArray(ref target.atlasMaterials, source.atlasMaterials);
CopyArray(ref target.atlasTextures, source.atlasTextures);
CopyArray(ref target.atlasTextureFiles, source.atlasTextureFiles);
}
public void CopyFromSource() {
CopyFromSource(true);
}
public void CopyFromSource(bool copyBuilt)
{
this.obj.Upgrade(); // make sure its up to date
textureParams = new List<tk2dSpriteCollectionDefinition>(obj.textureParams.Length);
foreach (var v in obj.textureParams)
{
if (v == null)
textureParams.Add(null);
else
{
var t = new tk2dSpriteCollectionDefinition();
t.CopyFrom(v);
textureParams.Add(t);
}
}
spriteSheets = new List<tk2dSpriteSheetSource>();
if (obj.spriteSheets != null)
{
foreach (var v in obj.spriteSheets)
{
if (v == null)
spriteSheets.Add(null);
else
{
var t = new tk2dSpriteSheetSource();
t.CopyFrom(v);
spriteSheets.Add(t);
}
}
}
fonts = new List<tk2dSpriteCollectionFont>();
if (obj.fonts != null)
{
foreach (var v in obj.fonts)
{
if (v == null)
fonts.Add(null);
else
{
var t = new tk2dSpriteCollectionFont();
t.CopyFrom(v);
fonts.Add(t);
}
}
}
attachPointTestSprites.Clear();
foreach (var v in obj.attachPointTestSprites) {
if (v.spriteCollection != null && v.spriteCollection.IsValidSpriteId(v.spriteId)) {
tk2dSpriteCollection.AttachPointTestSprite ap = new tk2dSpriteCollection.AttachPointTestSprite();
ap.CopyFrom(v);
attachPointTestSprites[v.attachPointName] = v;
}
}
UpgradeLegacySpriteSheets();
var target = this;
var source = obj;
target.platforms = new List<tk2dSpriteCollectionPlatform>();
foreach (tk2dSpriteCollectionPlatform plat in source.platforms)
{
tk2dSpriteCollectionPlatform p = new tk2dSpriteCollectionPlatform();
p.CopyFrom(plat);
target.platforms.Add(p);
}
if (target.platforms.Count == 0)
{
tk2dSpriteCollectionPlatform plat = new tk2dSpriteCollectionPlatform(); // add a null platform
target.platforms.Add(plat);
}
target.assetName = source.assetName;
target.loadable = source.loadable;
target.atlasFormat = source.atlasFormat;
target.maxTextureSize = source.maxTextureSize;
target.forceTextureSize = source.forceTextureSize;
target.forcedTextureWidth = source.forcedTextureWidth;
target.forcedTextureHeight = source.forcedTextureHeight;
target.textureCompression = source.textureCompression;
target.atlasWidth = source.atlasWidth;
target.atlasHeight = source.atlasHeight;
target.forceSquareAtlas = source.forceSquareAtlas;
target.atlasWastage = source.atlasWastage;
target.allowMultipleAtlases = source.allowMultipleAtlases;
target.disableRotation = source.disableRotation;
target.removeDuplicates = source.removeDuplicates;
target.premultipliedAlpha = source.premultipliedAlpha;
target.sizeDef.CopyFrom( source.sizeDef );
target.globalScale = source.globalScale;
target.globalTextureRescale = source.globalTextureRescale;
target.physicsDepth = source.physicsDepth;
target.physicsEngine = source.physicsEngine;
target.disableTrimming = source.disableTrimming;
target.normalGenerationMode = source.normalGenerationMode;
target.padAmount = source.padAmount;
target.autoUpdate = source.autoUpdate;
target.editorDisplayScale = source.editorDisplayScale;
// Texture settings
target.filterMode = source.filterMode;
target.wrapMode = source.wrapMode;
target.userDefinedTextureSettings = source.userDefinedTextureSettings;
target.mipmapEnabled = source.mipmapEnabled;
target.anisoLevel = source.anisoLevel;
target.linkedSpriteCollections.Clear();
for (int i = 0; i < source.linkedSpriteCollections.Count; ++i) {
tk2dLinkedSpriteCollection t = new tk2dLinkedSpriteCollection();
t.name = source.linkedSpriteCollections[i].name;
t.spriteCollection = source.linkedSpriteCollections[i].spriteCollection;
target.linkedSpriteCollections.Add(t);
}
if (copyBuilt) {
CopyBuiltFromSource(source);
}
}
void CopyArray<T>(ref T[] dest, T[] source)
{
if (source == null)
{
dest = new T[0];
}
else
{
dest = new T[source.Length];
for (int i = 0; i < source.Length; ++i)
dest[i] = source[i];
}
}
void UpgradeLegacySpriteSheets()
{
if (spriteSheets != null)
{
for (int i = 0; i < spriteSheets.Count; ++i)
{
var spriteSheet = spriteSheets[i];
if (spriteSheet != null && spriteSheet.version == 0)
{
if (spriteSheet.texture == null)
{
spriteSheet.active = false;
}
else
{
spriteSheet.tileWidth = spriteSheet.texture.width / spriteSheet.tilesX;
spriteSheet.tileHeight = spriteSheet.texture.height / spriteSheet.tilesY;
spriteSheet.active = true;
for (int j = 0; j < textureParams.Count; ++j)
{
var param = textureParams[j];
if (param.fromSpriteSheet && param.texture == spriteSheet.texture)
{
param.fromSpriteSheet = false;
param.hasSpriteSheetId = true;
param.spriteSheetId = i;
param.spriteSheetX = param.regionId % spriteSheet.tilesX;
param.spriteSheetY = param.regionId / spriteSheet.tilesX;
}
}
}
spriteSheet.version = tk2dSpriteSheetSource.CURRENT_VERSION;
}
}
}
}
public void DeleteUnusedData()
{
foreach (tk2dSpriteCollectionFont font in obj.fonts)
{
bool found = false;
foreach (tk2dSpriteCollectionFont f in fonts)
{
if (f.data == font.data && f.editorData == font.editorData)
{
found = true;
break;
}
}
if (!found)
{
tk2dEditorUtility.DeleteAsset(font.data);
tk2dEditorUtility.DeleteAsset(font.editorData);
}
}
if (obj.altMaterials != null)
{
foreach (Material material in obj.altMaterials)
{
bool found = false;
if (altMaterials != null)
{
foreach (Material m in altMaterials)
{
if (m == material)
{
found = true;
break;
}
}
}
if (!found)
tk2dEditorUtility.DeleteAsset(material);
}
}
List<tk2dSpriteCollectionPlatform> platformsToDelete = new List<tk2dSpriteCollectionPlatform>();
if (obj.HasPlatformData && !this.HasPlatformData)
{
platformsToDelete = new List<tk2dSpriteCollectionPlatform>(obj.platforms);
atlasTextures = new Texture2D[0]; // clear all references
atlasTextureFiles = new TextAsset[0];
atlasMaterials = new Material[0];
}
else if (this.HasPlatformData && !obj.HasPlatformData)
{
// delete old sprite collection atlases and materials
foreach (Material material in obj.atlasMaterials)
tk2dEditorUtility.DeleteAsset(material);
foreach (Texture2D texture in obj.atlasTextures)
tk2dEditorUtility.DeleteAsset(texture);
foreach (TextAsset textureFile in obj.atlasTextureFiles)
tk2dEditorUtility.DeleteAsset(textureFile);
}
else if (obj.HasPlatformData && this.HasPlatformData)
{
foreach (tk2dSpriteCollectionPlatform platform in obj.platforms)
{
bool found = false;
foreach (tk2dSpriteCollectionPlatform p in platforms)
{
if (p.spriteCollection == platform.spriteCollection)
{
found = true;
break;
}
}
if (!found) // platform existed previously, but does not any more
platformsToDelete.Add(platform);
}
}
foreach (tk2dSpriteCollectionPlatform platform in platformsToDelete)
{
if (platform.spriteCollection == null) continue;
tk2dSpriteCollection sc = platform.spriteCollection;
string path = AssetDatabase.GetAssetPath(sc.spriteCollection);
tk2dEditorUtility.DeleteAsset(sc.spriteCollection);
foreach (Material material in sc.atlasMaterials)
tk2dEditorUtility.DeleteAsset(material);
foreach (Texture2D texture in sc.atlasTextures)
tk2dEditorUtility.DeleteAsset(texture);
foreach (TextAsset textureFiles in sc.atlasTextureFiles)
tk2dEditorUtility.DeleteAsset(textureFiles);
foreach (tk2dSpriteCollectionFont font in sc.fonts)
{
tk2dEditorUtility.DeleteAsset(font.editorData);
tk2dEditorUtility.DeleteAsset(font.data);
}
tk2dEditorUtility.DeleteAsset(sc);
string dataDirName = System.IO.Path.GetDirectoryName(path);
if (System.IO.Directory.Exists(dataDirName) && System.IO.Directory.GetFiles(dataDirName).Length == 0)
AssetDatabase.DeleteAsset(dataDirName);
}
}
public void ClearReferences() {
altMaterials = new Material[0];
atlasMaterials = new Material[0];
atlasTextures = new Texture2D[0];
atlasTextureFiles = new TextAsset[0];
spriteCollection = null;
obj.altMaterials = new Material[0];
obj.atlasMaterials = new Material[0];
obj.atlasTextures = new Texture2D[0];
obj.atlasTextureFiles = new TextAsset[0];
obj.spriteCollection = null;
}
public void CopyToTarget()
{
CopyToTarget(obj);
}
public void CopyToTarget(tk2dSpriteCollection target)
{
target.textureParams = textureParams.ToArray();
target.spriteSheets = spriteSheets.ToArray();
target.fonts = fonts.ToArray();
var source = this;
target.platforms = new List<tk2dSpriteCollectionPlatform>();
foreach (tk2dSpriteCollectionPlatform plat in source.platforms)
{
tk2dSpriteCollectionPlatform p = new tk2dSpriteCollectionPlatform();
p.CopyFrom(plat);
target.platforms.Add(p);
}
target.assetName = source.assetName;
target.loadable = source.loadable;
target.atlasFormat = source.atlasFormat;
target.maxTextureSize = source.maxTextureSize;
target.forceTextureSize = source.forceTextureSize;
target.forcedTextureWidth = source.forcedTextureWidth;
target.forcedTextureHeight = source.forcedTextureHeight;
target.textureCompression = source.textureCompression;
target.atlasWidth = source.atlasWidth;
target.atlasHeight = source.atlasHeight;
target.forceSquareAtlas = source.forceSquareAtlas;
target.atlasWastage = source.atlasWastage;
target.allowMultipleAtlases = source.allowMultipleAtlases;
target.disableRotation = source.disableRotation;
target.removeDuplicates = source.removeDuplicates;
target.spriteCollection = source.spriteCollection;
target.premultipliedAlpha = source.premultipliedAlpha;
CopyArray(ref target.altMaterials, source.altMaterials);
CopyArray(ref target.atlasMaterials, source.atlasMaterials);
CopyArray(ref target.atlasTextures, source.atlasTextures);
CopyArray(ref target.atlasTextureFiles, source.atlasTextureFiles);
target.sizeDef.CopyFrom( source.sizeDef );
target.globalScale = source.globalScale;
target.globalTextureRescale = source.globalTextureRescale;
target.physicsDepth = source.physicsDepth;
target.physicsEngine = source.physicsEngine;
target.disableTrimming = source.disableTrimming;
target.normalGenerationMode = source.normalGenerationMode;
target.padAmount = source.padAmount;
target.autoUpdate = source.autoUpdate;
target.editorDisplayScale = source.editorDisplayScale;
// Texture settings
target.filterMode = source.filterMode;
target.wrapMode = source.wrapMode;
target.userDefinedTextureSettings = source.userDefinedTextureSettings;
target.mipmapEnabled = source.mipmapEnabled;
target.anisoLevel = source.anisoLevel;
// Attach point test data
// Make sure we only store relevant data
HashSet<string> attachPointNames = new HashSet<string>();
foreach (tk2dSpriteCollectionDefinition def in textureParams) {
foreach (tk2dSpriteDefinition.AttachPoint ap in def.attachPoints) {
attachPointNames.Add(ap.name);
}
}
target.attachPointTestSprites.Clear();
foreach (string name in attachPointTestSprites.Keys) {
if (attachPointNames.Contains(name)) {
tk2dSpriteCollection.AttachPointTestSprite lut = new tk2dSpriteCollection.AttachPointTestSprite();
lut.CopyFrom( attachPointTestSprites[name] );
lut.attachPointName = name;
target.attachPointTestSprites.Add(lut);
}
}
target.linkedSpriteCollections.Clear();
for (int i = 0; i < source.linkedSpriteCollections.Count; ++i) {
tk2dLinkedSpriteCollection t = new tk2dLinkedSpriteCollection();
t.name = source.linkedSpriteCollections[i].name;
t.spriteCollection = source.linkedSpriteCollections[i].spriteCollection;
target.linkedSpriteCollections.Add(t);
}
}
public bool AllowAltMaterials
{
get
{
return !allowMultipleAtlases;
}
}
public int FindOrCreateEmptySpriteSlot()
{
for (int index = 0; index < textureParams.Count; ++index)
{
if (textureParams[index].texture == null && textureParams[index].name.Length == 0)
return index;
}
textureParams.Add(new tk2dSpriteCollectionDefinition());
return textureParams.Count - 1;
}
public int FindOrCreateEmptyFontSlot()
{
for (int index = 0; index < fonts.Count; ++index)
{
if (!fonts[index].active)
{
fonts[index].active = true;
return index;
}
}
var font = new tk2dSpriteCollectionFont();
font.active = true;
fonts.Add(font);
return fonts.Count - 1;
}
public int FindOrCreateEmptySpriteSheetSlot()
{
for (int index = 0; index < spriteSheets.Count; ++index)
{
if (!spriteSheets[index].active)
{
spriteSheets[index].active = true;
spriteSheets[index].version = tk2dSpriteSheetSource.CURRENT_VERSION;
return index;
}
}
var spriteSheet = new tk2dSpriteSheetSource();
spriteSheet.active = true;
spriteSheet.version = tk2dSpriteSheetSource.CURRENT_VERSION;
spriteSheets.Add(spriteSheet);
return spriteSheets.Count - 1;
}
public string FindUniqueTextureName(string name)
{
int at = name.LastIndexOf('@');
if (at != -1) {
name = name.Substring(0, at);
}
List<string> textureNames = new List<string>();
foreach (var entry in textureParams)
{
textureNames.Add(entry.name);
}
if (textureNames.IndexOf(name) == -1)
return name;
int count = 1;
do
{
string currName = name + " " + count.ToString();
if (textureNames.IndexOf(currName) == -1)
return currName;
++count;
} while(count < 1024); // arbitrary large number
return name; // failed to find a name
}
public int FindSpriteBySource(Texture2D tex) {
for (int i = 0; i < textureParams.Count; ++i) {
if (textureParams[i].texture == tex) {
return i;
}
}
return -1;
}
public bool Empty { get { return textureParams.Count == 0 && fonts.Count == 0 && spriteSheets.Count == 0; } }
// Call after deleting anything
public void Trim()
{
int lastIndex = textureParams.Count - 1;
while (lastIndex >= 0)
{
if (textureParams[lastIndex].texture != null || textureParams[lastIndex].name.Length > 0)
break;
lastIndex--;
}
int count = textureParams.Count - 1 - lastIndex;
if (count > 0)
{
textureParams.RemoveRange( lastIndex + 1, count );
}
lastIndex = fonts.Count - 1;
while (lastIndex >= 0)
{
if (fonts[lastIndex].active)
break;
lastIndex--;
}
count = fonts.Count - 1 - lastIndex;
if (count > 0) fonts.RemoveRange(lastIndex + 1, count);
lastIndex = spriteSheets.Count - 1;
while (lastIndex >= 0)
{
if (spriteSheets[lastIndex].active)
break;
lastIndex--;
}
count = spriteSheets.Count - 1 - lastIndex;
if (count > 0) spriteSheets.RemoveRange(lastIndex + 1, count);
lastIndex = atlasMaterials.Length - 1;
while (lastIndex >= 0)
{
if (atlasMaterials[lastIndex] != null)
break;
lastIndex--;
}
count = atlasMaterials.Length - 1 - lastIndex;
if (count > 0)
System.Array.Resize(ref atlasMaterials, lastIndex + 1);
}
public int GetSpriteSheetId(tk2dSpriteSheetSource spriteSheet)
{
for (int index = 0; index < spriteSheets.Count; ++index)
if (spriteSheets[index] == spriteSheet) return index;
return 0;
}
// Delete all sprites from a spritesheet
public void DeleteSpriteSheet(tk2dSpriteSheetSource spriteSheet)
{
int index = GetSpriteSheetId(spriteSheet);
for (int i = 0; i < textureParams.Count; ++i)
{
if (textureParams[i].hasSpriteSheetId && textureParams[i].spriteSheetId == index)
{
textureParams[i] = new tk2dSpriteCollectionDefinition();
}
}
spriteSheets[index] = new tk2dSpriteSheetSource();
Trim();
}
public string GetAssetPath()
{
return AssetDatabase.GetAssetPath(obj);
}
public string GetOrCreateDataPath()
{
return tk2dSpriteCollectionBuilder.GetOrCreateDataPath(obj);
}
public bool Ready { get { return obj != null; } }
tk2dSpriteCollection obj;
// Mirrored data objects
public List<tk2dSpriteCollectionDefinition> textureParams = new List<tk2dSpriteCollectionDefinition>();
public List<tk2dSpriteSheetSource> spriteSheets = new List<tk2dSpriteSheetSource>();
public List<tk2dSpriteCollectionFont> fonts = new List<tk2dSpriteCollectionFont>();
// Mirrored from sprite collection
public string assetName;
public int maxTextureSize;
public tk2dSpriteCollection.TextureCompression textureCompression;
public int atlasWidth, atlasHeight;
public bool forceSquareAtlas;
public float atlasWastage;
public bool allowMultipleAtlases;
public bool disableRotation;
public bool removeDuplicates;
public tk2dSpriteCollectionData spriteCollection;
public bool premultipliedAlpha;
public List<tk2dSpriteCollectionPlatform> platforms = new List<tk2dSpriteCollectionPlatform>();
public bool HasPlatformData { get { return platforms.Count > 1; } }
public Material[] altMaterials;
public Material[] atlasMaterials;
public Texture2D[] atlasTextures;
public TextAsset[] atlasTextureFiles;
public tk2dSpriteCollectionSize sizeDef = new tk2dSpriteCollectionSize();
public float globalScale;
public float globalTextureRescale;
// Attach point test data
public Dictionary<string, tk2dSpriteCollection.AttachPointTestSprite> attachPointTestSprites = new Dictionary<string, tk2dSpriteCollection.AttachPointTestSprite>();
// Texture settings
public FilterMode filterMode;
public TextureWrapMode wrapMode;
public bool userDefinedTextureSettings;
public bool mipmapEnabled = true;
public int anisoLevel = 1;
public tk2dSpriteDefinition.PhysicsEngine physicsEngine;
public float physicsDepth;
public bool disableTrimming;
public bool forceTextureSize = false;
public int forcedTextureWidth = 1024;
public int forcedTextureHeight = 1024;
public tk2dSpriteCollection.NormalGenerationMode normalGenerationMode;
public int padAmount;
public bool autoUpdate;
public bool loadable;
public tk2dSpriteCollection.AtlasFormat atlasFormat;
// Linked sprite collections
public List<tk2dLinkedSpriteCollection> linkedSpriteCollections = new List<tk2dLinkedSpriteCollection>();
public float editorDisplayScale;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Debug = System.Diagnostics.Debug;
namespace System.Xml.Linq
{
internal class XNodeReader : XmlReader, IXmlLineInfo
{
private static readonly char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' };
// The reader position is encoded by the tuple (source, parent).
// Lazy text uses (instance, parent element). Attribute value
// uses (instance, parent attribute). End element uses (instance,
// instance). Common XObject uses (instance, null).
object source;
object parent;
ReadState state;
XNode root;
XmlNameTable nameTable;
bool omitDuplicateNamespaces;
internal XNodeReader(XNode node, XmlNameTable nameTable, ReaderOptions options)
{
this.source = node;
this.root = node;
this.nameTable = nameTable != null ? nameTable : CreateNameTable();
this.omitDuplicateNamespaces = (options & ReaderOptions.OmitDuplicateNamespaces) != 0 ? true : false;
}
internal XNodeReader(XNode node, XmlNameTable nameTable)
: this(node, nameTable,
(node.GetSaveOptionsFromAnnotations() & SaveOptions.OmitDuplicateNamespaces) != 0 ?
ReaderOptions.OmitDuplicateNamespaces : ReaderOptions.None)
{
}
public override int AttributeCount
{
get
{
if (!IsInteractive)
{
return 0;
}
int count = 0;
XElement e = GetElementInAttributeScope();
if (e != null)
{
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (!omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a))
{
count++;
}
} while (a != e.lastAttr);
}
}
return count;
}
}
public override string BaseURI
{
get
{
XObject o = source as XObject;
if (o != null)
{
return o.BaseUri;
}
o = parent as XObject;
if (o != null)
{
return o.BaseUri;
}
return string.Empty;
}
}
public override int Depth
{
get
{
if (!IsInteractive)
{
return 0;
}
XObject o = source as XObject;
if (o != null)
{
return GetDepth(o);
}
o = parent as XObject;
if (o != null)
{
return GetDepth(o) + 1;
}
return 0;
}
}
static int GetDepth(XObject o)
{
int depth = 0;
while (o.parent != null)
{
depth++;
o = o.parent;
}
if (o is XDocument)
{
depth--;
}
return depth;
}
public override bool EOF
{
get { return state == ReadState.EndOfFile; }
}
public override bool HasAttributes
{
get
{
if (!IsInteractive)
{
return false;
}
XElement e = GetElementInAttributeScope();
if (e != null && e.lastAttr != null)
{
if (omitDuplicateNamespaces)
{
return GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next) != null;
}
else
{
return true;
}
}
else
{
return false;
}
}
}
public override bool HasValue
{
get
{
if (!IsInteractive)
{
return false;
}
XObject o = source as XObject;
if (o != null)
{
switch (o.NodeType)
{
case XmlNodeType.Attribute:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.DocumentType:
return true;
default:
return false;
}
}
return true;
}
}
public override bool IsEmptyElement
{
get
{
if (!IsInteractive)
{
return false;
}
XElement e = source as XElement;
return e != null && e.IsEmpty;
}
}
public override string LocalName
{
get { return nameTable.Add(GetLocalName()); }
}
string GetLocalName()
{
if (!IsInteractive)
{
return string.Empty;
}
XElement e = source as XElement;
if (e != null)
{
return e.Name.LocalName;
}
XAttribute a = source as XAttribute;
if (a != null)
{
return a.Name.LocalName;
}
XProcessingInstruction p = source as XProcessingInstruction;
if (p != null)
{
return p.Target;
}
XDocumentType n = source as XDocumentType;
if (n != null)
{
return n.Name;
}
return string.Empty;
}
public override string Name
{
get
{
string prefix = GetPrefix();
if (prefix.Length == 0)
{
return nameTable.Add(GetLocalName());
}
return nameTable.Add(string.Concat(prefix, ":", GetLocalName()));
}
}
public override string NamespaceURI
{
get { return nameTable.Add(GetNamespaceURI()); }
}
string GetNamespaceURI()
{
if (!IsInteractive)
{
return string.Empty;
}
XElement e = source as XElement;
if (e != null)
{
return e.Name.NamespaceName;
}
XAttribute a = source as XAttribute;
if (a != null)
{
string namespaceName = a.Name.NamespaceName;
if (namespaceName.Length == 0 && a.Name.LocalName == "xmlns")
{
return XNamespace.xmlnsPrefixNamespace;
}
return namespaceName;
}
return string.Empty;
}
public override XmlNameTable NameTable
{
get { return nameTable; }
}
public override XmlNodeType NodeType
{
get
{
if (!IsInteractive)
{
return XmlNodeType.None;
}
XObject o = source as XObject;
if (o != null)
{
if (IsEndElement)
{
return XmlNodeType.EndElement;
}
XmlNodeType nt = o.NodeType;
if (nt != XmlNodeType.Text)
{
return nt;
}
if (o.parent != null && o.parent.parent == null && o.parent is XDocument)
{
return XmlNodeType.Whitespace;
}
return XmlNodeType.Text;
}
if (parent is XDocument)
{
return XmlNodeType.Whitespace;
}
return XmlNodeType.Text;
}
}
public override string Prefix
{
get { return nameTable.Add(GetPrefix()); }
}
string GetPrefix()
{
if (!IsInteractive)
{
return string.Empty;
}
XElement e = source as XElement;
if (e != null)
{
string prefix = e.GetPrefixOfNamespace(e.Name.Namespace);
if (prefix != null)
{
return prefix;
}
return string.Empty;
}
XAttribute a = source as XAttribute;
if (a != null)
{
string prefix = a.GetPrefixOfNamespace(a.Name.Namespace);
if (prefix != null)
{
return prefix;
}
}
return string.Empty;
}
public override ReadState ReadState
{
get { return state; }
}
public override XmlReaderSettings Settings
{
get
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.CheckCharacters = false;
return settings;
}
}
public override string Value
{
get
{
if (!IsInteractive)
{
return string.Empty;
}
XObject o = source as XObject;
if (o != null)
{
switch (o.NodeType)
{
case XmlNodeType.Attribute:
return ((XAttribute)o).Value;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
return ((XText)o).Value;
case XmlNodeType.Comment:
return ((XComment)o).Value;
case XmlNodeType.ProcessingInstruction:
return ((XProcessingInstruction)o).Data;
case XmlNodeType.DocumentType:
return ((XDocumentType)o).InternalSubset;
default:
return string.Empty;
}
}
return (string)source;
}
}
public override string XmlLang
{
get
{
if (!IsInteractive)
{
return string.Empty;
}
XElement e = GetElementInScope();
if (e != null)
{
XName name = XNamespace.Xml.GetName("lang");
do
{
XAttribute a = e.Attribute(name);
if (a != null)
{
return a.Value;
}
e = e.parent as XElement;
} while (e != null);
}
return string.Empty;
}
}
public override XmlSpace XmlSpace
{
get
{
if (!IsInteractive)
{
return XmlSpace.None;
}
XElement e = GetElementInScope();
if (e != null)
{
XName name = XNamespace.Xml.GetName("space");
do
{
XAttribute a = e.Attribute(name);
if (a != null)
{
switch (a.Value.Trim(WhitespaceChars))
{
case "preserve":
return XmlSpace.Preserve;
case "default":
return XmlSpace.Default;
default:
break;
}
}
e = e.parent as XElement;
} while (e != null);
}
return XmlSpace.None;
}
}
protected override void Dispose(bool disposing)
{
if (disposing && ReadState != ReadState.Closed)
{
Close();
}
}
private void Close()
{
source = null;
parent = null;
root = null;
state = ReadState.Closed;
}
public override string GetAttribute(string name)
{
if (!IsInteractive)
{
return null;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
string localName, namespaceName;
GetNameInAttributeScope(name, e, out localName, out namespaceName);
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName)
{
if (omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a))
{
return null;
}
else
{
return a.Value;
}
}
} while (a != e.lastAttr);
}
return null;
}
XDocumentType n = source as XDocumentType;
if (n != null)
{
switch (name)
{
case "PUBLIC":
return n.PublicId;
case "SYSTEM":
return n.SystemId;
}
}
return null;
}
public override string GetAttribute(string localName, string namespaceName)
{
if (!IsInteractive)
{
return null;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
if (localName == "xmlns")
{
if (namespaceName != null && namespaceName.Length == 0)
{
return null;
}
if (namespaceName == XNamespace.xmlnsPrefixNamespace)
{
namespaceName = string.Empty;
}
}
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName)
{
if (omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a))
{
return null;
}
else
{
return a.Value;
}
}
} while (a != e.lastAttr);
}
}
return null;
}
public override string GetAttribute(int index)
{
if (!IsInteractive)
{
return null;
}
if (index < 0)
{
return null;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (!omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a))
{
if (index-- == 0)
{
return a.Value;
}
}
} while (a != e.lastAttr);
}
}
return null;
}
public override string LookupNamespace(string prefix)
{
if (!IsInteractive)
{
return null;
}
if (prefix == null)
{
return null;
}
XElement e = GetElementInScope();
if (e != null)
{
XNamespace ns = prefix.Length == 0 ? e.GetDefaultNamespace() : e.GetNamespaceOfPrefix(prefix);
if (ns != null)
{
return nameTable.Add(ns.NamespaceName);
}
}
return null;
}
public override bool MoveToAttribute(string name)
{
if (!IsInteractive)
{
return false;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
string localName, namespaceName;
GetNameInAttributeScope(name, e, out localName, out namespaceName);
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.Name.LocalName == localName &&
a.Name.NamespaceName == namespaceName)
{
if (omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a))
{
// If it's a duplicate namespace attribute just act as if it doesn't exist
return false;
}
else
{
source = a;
parent = null;
return true;
}
}
} while (a != e.lastAttr);
}
}
return false;
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
if (!IsInteractive)
{
return false;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
if (localName == "xmlns")
{
if (namespaceName != null && namespaceName.Length == 0)
{
return false;
}
if (namespaceName == XNamespace.xmlnsPrefixNamespace)
{
namespaceName = string.Empty;
}
}
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.Name.LocalName == localName &&
a.Name.NamespaceName == namespaceName)
{
if (omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a))
{
// If it's a duplicate namespace attribute just act as if it doesn't exist
return false;
}
else
{
source = a;
parent = null;
return true;
}
}
} while (a != e.lastAttr);
}
}
return false;
}
public override void MoveToAttribute(int index)
{
if (!IsInteractive)
{
return;
}
if (index < 0) throw new ArgumentOutOfRangeException("index");
XElement e = GetElementInAttributeScope();
if (e != null)
{
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (!omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a))
{
// Only count those which are non-duplicates if we're asked to
if (index-- == 0)
{
source = a;
parent = null;
return;
}
}
} while (a != e.lastAttr);
}
}
throw new ArgumentOutOfRangeException("index");
}
public override bool MoveToElement()
{
if (!IsInteractive)
{
return false;
}
XAttribute a = source as XAttribute;
if (a == null)
{
a = parent as XAttribute;
}
if (a != null)
{
if (a.parent != null)
{
source = a.parent;
parent = null;
return true;
}
}
return false;
}
public override bool MoveToFirstAttribute()
{
if (!IsInteractive)
{
return false;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
if (e.lastAttr != null)
{
if (omitDuplicateNamespaces)
{
object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next);
if (na == null)
{
return false;
}
source = na;
}
else
{
source = e.lastAttr.next;
}
return true;
}
}
return false;
}
public override bool MoveToNextAttribute()
{
if (!IsInteractive)
{
return false;
}
XElement e = source as XElement;
if (e != null)
{
if (IsEndElement)
{
return false;
}
if (e.lastAttr != null)
{
if (omitDuplicateNamespaces)
{
// Skip duplicate namespace attributes
// We must NOT modify the this.source until we find the one we're looking for
// because if we don't find anything, we need to stay positioned where we're now
object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next);
if (na == null)
{
return false;
}
source = na;
}
else
{
source = e.lastAttr.next;
}
return true;
}
return false;
}
XAttribute a = source as XAttribute;
if (a == null)
{
a = parent as XAttribute;
}
if (a != null)
{
if (a.parent != null && ((XElement)a.parent).lastAttr != a)
{
if (omitDuplicateNamespaces)
{
// Skip duplicate namespace attributes
// We must NOT modify the this.source until we find the one we're looking for
// because if we don't find anything, we need to stay positioned where we're now
object na = GetFirstNonDuplicateNamespaceAttribute(a.next);
if (na == null)
{
return false;
}
source = na;
}
else
{
source = a.next;
}
parent = null;
return true;
}
}
return false;
}
public override bool Read()
{
switch (state)
{
case ReadState.Initial:
state = ReadState.Interactive;
XDocument d = source as XDocument;
if (d != null)
{
return ReadIntoDocument(d);
}
return true;
case ReadState.Interactive:
return Read(false);
default:
return false;
}
}
public override bool ReadAttributeValue()
{
if (!IsInteractive)
{
return false;
}
XAttribute a = source as XAttribute;
if (a != null)
{
return ReadIntoAttribute(a);
}
return false;
}
public override bool ReadToDescendant(string localName, string namespaceName)
{
if (!IsInteractive)
{
return false;
}
MoveToElement();
XElement c = source as XElement;
if (c != null && !c.IsEmpty)
{
if (IsEndElement)
{
return false;
}
foreach (XElement e in c.Descendants())
{
if (e.Name.LocalName == localName &&
e.Name.NamespaceName == namespaceName)
{
source = e;
return true;
}
}
IsEndElement = true;
}
return false;
}
public override bool ReadToFollowing(string localName, string namespaceName)
{
while (Read())
{
XElement e = source as XElement;
if (e != null)
{
if (IsEndElement) continue;
if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName)
{
return true;
}
}
}
return false;
}
public override bool ReadToNextSibling(string localName, string namespaceName)
{
if (!IsInteractive)
{
return false;
}
MoveToElement();
if (source != root)
{
XNode n = source as XNode;
if (n != null)
{
foreach (XElement e in n.ElementsAfterSelf())
{
if (e.Name.LocalName == localName &&
e.Name.NamespaceName == namespaceName)
{
source = e;
IsEndElement = false;
return true;
}
}
if (n.parent is XElement)
{
source = n.parent;
IsEndElement = true;
return false;
}
}
else
{
if (parent is XElement)
{
source = parent;
parent = null;
IsEndElement = true;
return false;
}
}
}
return ReadToEnd();
}
public override void ResolveEntity()
{
}
public override void Skip()
{
if (!IsInteractive)
{
return;
}
Read(true);
}
bool IXmlLineInfo.HasLineInfo()
{
if (IsEndElement)
{
// Special case for EndElement - we store the line info differently in this case
// we also know that the current node (source) is XElement
XElement e = source as XElement;
if (e != null)
{
return e.Annotation<LineInfoEndElementAnnotation>() != null;
}
}
else
{
IXmlLineInfo li = source as IXmlLineInfo;
if (li != null)
{
return li.HasLineInfo();
}
}
return false;
}
int IXmlLineInfo.LineNumber
{
get
{
if (IsEndElement)
{
// Special case for EndElement - we store the line info differently in this case
// we also know that the current node (source) is XElement
XElement e = source as XElement;
if (e != null)
{
LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>();
if (a != null)
{
return a.lineNumber;
}
}
}
else
{
IXmlLineInfo li = source as IXmlLineInfo;
if (li != null)
{
return li.LineNumber;
}
}
return 0;
}
}
int IXmlLineInfo.LinePosition
{
get
{
if (IsEndElement)
{
// Special case for EndElement - we store the line info differently in this case
// we also know that the current node (source) is XElement
XElement e = source as XElement;
if (e != null)
{
LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>();
if (a != null)
{
return a.linePosition;
}
}
}
else
{
IXmlLineInfo li = source as IXmlLineInfo;
if (li != null)
{
return li.LinePosition;
}
}
return 0;
}
}
bool IsEndElement
{
get { return parent == source; }
set { parent = value ? source : null; }
}
bool IsInteractive
{
get { return state == ReadState.Interactive; }
}
static XmlNameTable CreateNameTable()
{
XmlNameTable nameTable = new NameTable();
nameTable.Add(string.Empty);
nameTable.Add(XNamespace.xmlnsPrefixNamespace);
nameTable.Add(XNamespace.xmlPrefixNamespace);
return nameTable;
}
XElement GetElementInAttributeScope()
{
XElement e = source as XElement;
if (e != null)
{
if (IsEndElement)
{
return null;
}
return e;
}
XAttribute a = source as XAttribute;
if (a != null)
{
return (XElement)a.parent;
}
a = parent as XAttribute;
if (a != null)
{
return (XElement)a.parent;
}
return null;
}
XElement GetElementInScope()
{
XElement e = source as XElement;
if (e != null)
{
return e;
}
XNode n = source as XNode;
if (n != null)
{
return n.parent as XElement;
}
XAttribute a = source as XAttribute;
if (a != null)
{
return (XElement)a.parent;
}
e = parent as XElement;
if (e != null)
{
return e;
}
a = parent as XAttribute;
if (a != null)
{
return (XElement)a.parent;
}
return null;
}
static void GetNameInAttributeScope(string qualifiedName, XElement e, out string localName, out string namespaceName)
{
if (qualifiedName != null && qualifiedName.Length != 0)
{
int i = qualifiedName.IndexOf(':');
if (i != 0 && i != qualifiedName.Length - 1)
{
if (i == -1)
{
localName = qualifiedName;
namespaceName = string.Empty;
return;
}
XNamespace ns = e.GetNamespaceOfPrefix(qualifiedName.Substring(0, i));
if (ns != null)
{
localName = qualifiedName.Substring(i + 1, qualifiedName.Length - i - 1);
namespaceName = ns.NamespaceName;
return;
}
}
}
localName = null;
namespaceName = null;
}
bool Read(bool skipContent)
{
XElement e = source as XElement;
if (e != null)
{
if (e.IsEmpty || IsEndElement || skipContent)
{
return ReadOverNode(e);
}
return ReadIntoElement(e);
}
XNode n = source as XNode;
if (n != null)
{
return ReadOverNode(n);
}
XAttribute a = source as XAttribute;
if (a != null)
{
return ReadOverAttribute(a, skipContent);
}
return ReadOverText(skipContent);
}
bool ReadIntoDocument(XDocument d)
{
XNode n = d.content as XNode;
if (n != null)
{
source = n.next;
return true;
}
string s = d.content as string;
if (s != null)
{
if (s.Length > 0)
{
source = s;
parent = d;
return true;
}
}
return ReadToEnd();
}
bool ReadIntoElement(XElement e)
{
XNode n = e.content as XNode;
if (n != null)
{
source = n.next;
return true;
}
string s = e.content as string;
if (s != null)
{
if (s.Length > 0)
{
source = s;
parent = e;
}
else
{
source = e;
IsEndElement = true;
}
return true;
}
return ReadToEnd();
}
bool ReadIntoAttribute(XAttribute a)
{
source = a.value;
parent = a;
return true;
}
bool ReadOverAttribute(XAttribute a, bool skipContent)
{
XElement e = (XElement)a.parent;
if (e != null)
{
if (e.IsEmpty || skipContent)
{
return ReadOverNode(e);
}
return ReadIntoElement(e);
}
return ReadToEnd();
}
bool ReadOverNode(XNode n)
{
if (n == root)
{
return ReadToEnd();
}
XNode next = n.next;
if (null == next || next == n || n == n.parent.content)
{
if (n.parent == null || (n.parent.parent == null && n.parent is XDocument))
{
return ReadToEnd();
}
source = n.parent;
IsEndElement = true;
}
else
{
source = next;
IsEndElement = false;
}
return true;
}
bool ReadOverText(bool skipContent)
{
if (parent is XElement)
{
source = parent;
parent = null;
IsEndElement = true;
return true;
}
if (parent is XAttribute)
{
XAttribute a = (XAttribute)parent;
parent = null;
return ReadOverAttribute(a, skipContent);
}
return ReadToEnd();
}
bool ReadToEnd()
{
state = ReadState.EndOfFile;
return false;
}
/// <summary>
/// Determines if the specified attribute would be a duplicate namespace declaration
/// - one which we already reported on some ancestor, so it's not necessary to report it here
/// </summary>
/// <param name="a">The attribute to test</param>
/// <returns>true if the attribute is a duplicate namespace declaration attribute</returns>
bool IsDuplicateNamespaceAttribute(XAttribute candidateAttribute)
{
if (!candidateAttribute.IsNamespaceDeclaration)
{
return false;
}
else
{
// Split the method in two to enable inlining of this piece (Which will work for 95% of cases)
return IsDuplicateNamespaceAttributeInner(candidateAttribute);
}
}
bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute)
{
// First of all - if this is an xmlns:xml declaration then it's a duplicate
// since xml prefix can't be redeclared and it's declared by default always.
if (candidateAttribute.Name.LocalName == "xml")
{
return true;
}
// The algorithm we use is:
// Go up the tree (but don't go higher than the root of this reader)
// and find the closest namespace declaration attribute which declares the same prefix
// If it declares that prefix to the exact same URI as ours does then ours is a duplicate
// Note that if we find a namespace declaration for the same prefix but with a different URI, then we don't have a dupe!
XElement element = candidateAttribute.parent as XElement;
if (element == root || element == null)
{
// If there's only the parent element of our attribute, there can be no duplicates
return false;
}
element = element.parent as XElement;
while (element != null)
{
// Search all attributes of this element for the same prefix declaration
// Trick - a declaration for the same prefix will have the exact same XName - so we can do a quick ref comparison of names
// (The default ns decl is represented by an XName "xmlns{}", even if you try to create
// an attribute with XName "xmlns{http://www.w3.org/2000/xmlns/}" it will fail,
// because it's treated as a declaration of prefix "xmlns" which is invalid)
XAttribute a = element.lastAttr;
if (a != null)
{
do
{
if (a.name == candidateAttribute.name)
{
// Found the same prefix decl
if (a.Value == candidateAttribute.Value)
{
// And it's for the same namespace URI as well - so ours is a duplicate
return true;
}
else
{
// It's not for the same namespace URI - which means we have to keep ours
// (no need to continue the search as this one overrides anything above it)
return false;
}
}
a = a.next;
} while (a != element.lastAttr);
}
if (element == root)
{
return false;
}
element = element.parent as XElement;
}
return false;
}
/// <summary>
/// Finds a first attribute (starting with the parameter) which is not a duplicate namespace attribute
/// </summary>
/// <param name="candidate">The attribute to start with</param>
/// <returns>The first attribute which is not a namespace attribute or null if the end of attributes has bean reached</returns>
XAttribute GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate)
{
Debug.Assert(omitDuplicateNamespaces, "This method should only be caled if we're omitting duplicate namespace attribute." +
"For perf reason it's better to test this flag in the caller method.");
if (!IsDuplicateNamespaceAttribute(candidate))
{
return candidate;
}
XElement e = candidate.parent as XElement;
if (e != null && candidate != e.lastAttr)
{
do
{
candidate = candidate.next;
if (!IsDuplicateNamespaceAttribute(candidate))
{
return candidate;
}
} while (candidate != e.lastAttr);
}
return null;
}
}
}
| |
/*
insert license info here
*/
using System;
using System.Collections;
namespace Business.Data
{
/// <summary>
/// Generated by MyGeneration using the NHibernate Object Mapping template
/// </summary>
[Serializable]
public sealed class Efector : Business.BaseDataAccess
{
#region Private Members
private bool m_isChanged;
private int m_idefector;
private string m_nombre;
private Zona m_idzona;
private string m_nombrenacion;
private string m_complejidad;
private int m_idefectorsuperior;
private string m_domicilio;
private string m_telefono;
private string m_reponsable;
#endregion
#region Default ( Empty ) Class Constuctor
/// <summary>
/// default constructor
/// </summary>
public Efector()
{
m_idefector = 0;
m_nombre = String.Empty;
m_idzona =new Zona();
m_nombrenacion = String.Empty;
m_complejidad = String.Empty;
m_idefectorsuperior =0;
m_domicilio = String.Empty;
m_telefono = String.Empty;
m_reponsable = String.Empty;
}
#endregion // End of Default ( Empty ) Class Constuctor
#region Required Fields Only Constructor
/// <summary>
/// required (not null) fields only constructor
/// </summary>
public Efector(
string nombre,
Zona idzona,
string nombrenacion,
string complejidad,
int idefectorsuperior,
string domicilio,
string telefono,
string reponsable)
: this()
{
m_nombre = nombre;
m_idzona = idzona;
m_nombrenacion = nombrenacion;
m_complejidad = complejidad;
m_idefectorsuperior = idefectorsuperior;
m_domicilio = domicilio;
m_telefono = telefono;
m_reponsable = reponsable;
}
#endregion // End Required Fields Only Constructor
#region Public Properties
/// <summary>
///
/// </summary>
public int IdEfector
{
get { return m_idefector; }
set
{
m_isChanged |= ( m_idefector != value );
m_idefector = value;
}
}
/// <summary>
///
/// </summary>
public string Nombre
{
get { return m_nombre; }
set
{
if( value == null )
throw new ArgumentOutOfRangeException("Null value not allowed for Nombre", value, "null");
if( value.Length > 100)
throw new ArgumentOutOfRangeException("Invalid value for Nombre", value, value.ToString());
m_isChanged |= (m_nombre != value); m_nombre = value;
}
}
/// <summary>
///
/// </summary>
public Zona IdZona
{
get { return m_idzona; }
set
{
m_isChanged |= ( m_idzona != value );
m_idzona = value;
}
}
/// <summary>
///
/// </summary>
public string NombreNacion
{
get { return m_nombrenacion; }
set
{
if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for NombreNacion", value, "null");
if( value.Length > 100)
throw new ArgumentOutOfRangeException("Invalid value for NombreNacion", value, value.ToString());
m_isChanged |= (m_nombrenacion != value); m_nombrenacion = value;
}
}
/// <summary>
///
/// </summary>
public string Complejidad
{
get { return m_complejidad; }
set
{
if( value == null )
throw new ArgumentOutOfRangeException("Null value not allowed for Complejidad", value, "null");
if( value.Length > 10)
throw new ArgumentOutOfRangeException("Invalid value for Complejidad", value, value.ToString());
m_isChanged |= (m_complejidad != value); m_complejidad = value;
}
}
/// <summary>
///
/// </summary>
public int IdEfectorSuperior
{
get { return m_idefectorsuperior; }
set
{
m_isChanged |= (m_idefectorsuperior != value);
m_idefectorsuperior = value;
}
}
/// <summary>
///
/// </summary>
public string Domicilio
{
get { return m_domicilio; }
set
{
if( value == null )
throw new ArgumentOutOfRangeException("Null value not allowed for Domicilio", value, "null");
if( value.Length > 200)
throw new ArgumentOutOfRangeException("Invalid value for Domicilio", value, value.ToString());
m_isChanged |= (m_domicilio != value); m_domicilio = value;
}
}
/// <summary>
///
/// </summary>
public string Telefono
{
get { return m_telefono; }
set
{
if( value == null )
throw new ArgumentOutOfRangeException("Null value not allowed for Telefono", value, "null");
if( value.Length > 10)
throw new ArgumentOutOfRangeException("Invalid value for Telefono", value, value.ToString());
m_isChanged |= (m_telefono != value); m_telefono = value;
}
}
/// <summary>
///
/// </summary>
public string Reponsable
{
get { return m_reponsable; }
set
{
if( value == null )
throw new ArgumentOutOfRangeException("Null value not allowed for Reponsable", value, "null");
if( value.Length > 100)
throw new ArgumentOutOfRangeException("Invalid value for Reponsable", value, value.ToString());
m_isChanged |= (m_reponsable != value); m_reponsable = value;
}
}
/// <summary>
/// Returns whether or not the object has changed it's values.
/// </summary>
public bool IsChanged
{
get { return m_isChanged; }
}
#endregion
}
}
| |
#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 Newtonsoft.Json.Serialization;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class CamelCaseNamingStrategyTests : TestFixtureBase
{
[Test]
public void JsonConvertSerializerSettings()
{
Person person = new Person();
person.BirthDate = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.LastModified = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.Name = "Name!";
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = contractResolver
});
StringAssert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""2000-11-20T23:55:44Z"",
""lastModified"": ""2000-11-20T23:55:44Z""
}", json);
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate);
Assert.AreEqual(person.LastModified, deserializedPerson.LastModified);
Assert.AreEqual(person.Name, deserializedPerson.Name);
json = JsonConvert.SerializeObject(person, Formatting.Indented);
StringAssert.AreEqual(@"{
""Name"": ""Name!"",
""BirthDate"": ""2000-11-20T23:55:44Z"",
""LastModified"": ""2000-11-20T23:55:44Z""
}", json);
}
[Test]
public void JTokenWriter_OverrideSpecifiedName()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = true
}
};
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = contractResolver;
JTokenWriter writer = new JTokenWriter();
serializer.Serialize(writer, ignoreAttributeOnClassTestClass);
JObject o = (JObject)writer.Token;
JProperty p = o.Property("theField");
Assert.IsNotNull(p);
Assert.AreEqual(int.MinValue, (int)p.Value);
}
[Test]
public void BlogPostExample()
{
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = contractResolver }
);
//{
// "name": "Widget",
// "expiryDate": "\/Date(1292868060000)\/",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
StringAssert.AreEqual(@"{
""name"": ""Widget"",
""expiryDate"": ""2010-12-20T18:01:00Z"",
""price"": 9.99,
""sizes"": [
""Small"",
""Medium"",
""Large""
]
}", json);
}
#if !(NET35 || NET20 || PORTABLE40)
[Test]
public void DynamicCamelCasePropertyNames()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
ProcessDictionaryKeys = true
}
};
string json = JsonConvert.SerializeObject(o, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = contractResolver
});
StringAssert.AreEqual(@"{
""explicit"": false,
""text"": ""Text!"",
""integer"": 2147483647,
""int"": 0,
""childObject"": null
}", json);
}
#endif
[Test]
public void DictionaryCamelCasePropertyNames_Disabled()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "First", "Value1!" },
{ "Second", "Value2!" }
};
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = contractResolver
});
StringAssert.AreEqual(@"{
""First"": ""Value1!"",
""Second"": ""Value2!""
}", json);
}
[Test]
public void DictionaryCamelCasePropertyNames_Enabled()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "First", "Value1!" },
{ "Second", "Value2!" }
};
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
ProcessDictionaryKeys = true
}
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = contractResolver
});
StringAssert.AreEqual(@"{
""first"": ""Value1!"",
""second"": ""Value2!""
}", json);
}
public class PropertyAttributeNamingStrategyTestClass
{
[JsonProperty]
public string HasNoAttributeNamingStrategy { get; set; }
[JsonProperty(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public string HasAttributeNamingStrategy { get; set; }
}
[Test]
public void JsonPropertyAttribute_NamingStrategyType()
{
PropertyAttributeNamingStrategyTestClass c = new PropertyAttributeNamingStrategyTestClass
{
HasNoAttributeNamingStrategy = "Value1!",
HasAttributeNamingStrategy = "Value2!"
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
StringAssert.AreEqual(@"{
""HasNoAttributeNamingStrategy"": ""Value1!"",
""hasAttributeNamingStrategy"": ""Value2!""
}", json);
}
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class ContainerAttributeNamingStrategyTestClass
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
[JsonProperty(NamingStrategyType = typeof(DefaultNamingStrategy))]
public string HasAttributeNamingStrategy { get; set; }
}
[Test]
public void JsonObjectAttribute_NamingStrategyType()
{
ContainerAttributeNamingStrategyTestClass c = new ContainerAttributeNamingStrategyTestClass
{
Prop1 = "Value1!",
Prop2 = "Value2!"
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
StringAssert.AreEqual(@"{
""prop1"": ""Value1!"",
""prop2"": ""Value2!"",
""HasAttributeNamingStrategy"": null
}", json);
}
[JsonDictionary(NamingStrategyType = typeof(CamelCaseNamingStrategy), NamingStrategyParameters = new object[] { true, true })]
public class DictionaryAttributeNamingStrategyTestClass : Dictionary<string, string>
{
}
[Test]
public void JsonDictionaryAttribute_NamingStrategyType()
{
DictionaryAttributeNamingStrategyTestClass c = new DictionaryAttributeNamingStrategyTestClass
{
["Key1"] = "Value1!",
["Key2"] = "Value2!"
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
StringAssert.AreEqual(@"{
""key1"": ""Value1!"",
""key2"": ""Value2!""
}", json);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureParameterGrouping
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ParameterGroupingOperations operations.
/// </summary>
internal partial class ParameterGroupingOperations : IServiceOperations<AutoRestParameterGroupingTestServiceClient>, IParameterGroupingOperations
{
/// <summary>
/// Initializes a new instance of the ParameterGroupingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ParameterGroupingOperations(AutoRestParameterGroupingTestServiceClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestParameterGroupingTestServiceClient
/// </summary>
public AutoRestParameterGroupingTestServiceClient Client { get; private set; }
/// <summary>
/// Post a bunch of required parameters grouped
/// </summary>
/// <param name='parameterGroupingPostRequiredParameters'>
/// Additional parameters for the operation
/// </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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParameters parameterGroupingPostRequiredParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (parameterGroupingPostRequiredParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameterGroupingPostRequiredParameters");
}
if (parameterGroupingPostRequiredParameters != null)
{
parameterGroupingPostRequiredParameters.Validate();
}
int body = default(int);
if (parameterGroupingPostRequiredParameters != null)
{
body = parameterGroupingPostRequiredParameters.Body;
}
string customHeader = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
customHeader = parameterGroupingPostRequiredParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostRequiredParameters != null)
{
query = parameterGroupingPostRequiredParameters.Query;
}
string path = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
path = parameterGroupingPostRequiredParameters.Path;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("path", path);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postRequired/{path}").ToString();
_url = _url.Replace("{path}", System.Uri.EscapeDataString(path));
List<string> _queryParameters = new List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
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;
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post a bunch of optional parameters grouped
/// </summary>
/// <param name='parameterGroupingPostOptionalParameters'>
/// Additional parameters for the operation
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostOptionalWithHttpMessagesAsync(ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = default(ParameterGroupingPostOptionalParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string customHeader = default(string);
if (parameterGroupingPostOptionalParameters != null)
{
customHeader = parameterGroupingPostOptionalParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostOptionalParameters != null)
{
query = parameterGroupingPostOptionalParameters.Query;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostOptional", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postOptional").ToString();
List<string> _queryParameters = new List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters from multiple different parameter groups
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='parameterGroupingPostMultiParamGroupsSecondParamGroup'>
/// Additional parameters for the operation
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMultiParamGroupsWithHttpMessagesAsync(FirstParameterGroup firstParameterGroup = default(FirstParameterGroup), ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = default(ParameterGroupingPostMultiParamGroupsSecondParamGroup), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
string headerTwo = default(string);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.HeaderTwo;
}
int? queryTwo = default(int?);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.QueryTwo;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("headerTwo", headerTwo);
tracingParameters.Add("queryTwo", queryTwo);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMultiParamGroups", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postMultipleParameterGroups").ToString();
List<string> _queryParameters = new List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, Client.SerializationSettings).Trim('"'))));
}
if (queryTwo != null)
{
_queryParameters.Add(string.Format("query-two={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryTwo, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (headerTwo != null)
{
if (_httpRequest.Headers.Contains("header-two"))
{
_httpRequest.Headers.Remove("header-two");
}
_httpRequest.Headers.TryAddWithoutValidation("header-two", headerTwo);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters with a shared parameter group object
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostSharedParameterGroupObjectWithHttpMessagesAsync(FirstParameterGroup firstParameterGroup = default(FirstParameterGroup), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostSharedParameterGroupObject", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/sharedParameterGroupObject").ToString();
List<string> _queryParameters = new List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Internal.TypeSystem;
namespace Internal.JitInterface
{
internal unsafe partial class CorInfoImpl
{
private struct IntrinsicKey
{
public string MethodName;
public string TypeNamespace;
public string TypeName;
public bool Equals(IntrinsicKey other)
{
return (MethodName == other.MethodName) &&
(TypeNamespace == other.TypeNamespace) &&
(TypeName == other.TypeName);
}
public override int GetHashCode()
{
return MethodName.GetHashCode() +
((TypeNamespace != null) ? TypeNamespace.GetHashCode() : 0) +
((TypeName != null) ? TypeName.GetHashCode() : 0);
}
}
private class IntrinsicEntry
{
public IntrinsicKey Key;
public CorInfoIntrinsics Id;
}
private class IntrinsicHashtable : LockFreeReaderHashtable<IntrinsicKey, IntrinsicEntry>
{
protected override bool CompareKeyToValue(IntrinsicKey key, IntrinsicEntry value)
{
return key.Equals(value.Key);
}
protected override bool CompareValueToValue(IntrinsicEntry value1, IntrinsicEntry value2)
{
return value1.Key.Equals(value2.Key);
}
protected override IntrinsicEntry CreateValueFromKey(IntrinsicKey key)
{
Debug.Assert(false, "CreateValueFromKey not supported");
return null;
}
protected override int GetKeyHashCode(IntrinsicKey key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(IntrinsicEntry value)
{
return value.Key.GetHashCode();
}
public void Add(CorInfoIntrinsics id, string methodName, string typeNamespace, string typeName)
{
var entry = new IntrinsicEntry();
entry.Id = id;
entry.Key.MethodName = methodName;
entry.Key.TypeNamespace = typeNamespace;
entry.Key.TypeName = typeName;
AddOrGetExisting(entry);
}
}
static IntrinsicHashtable InitializeIntrinsicHashtable()
{
IntrinsicHashtable table = new IntrinsicHashtable();
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sin, "Sin", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cos, "Cos", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sqrt, "Sqrt", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Abs, "Abs", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Round, "Round", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cosh, "Cosh", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sinh, "Sinh", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tan, "Tan", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tanh, "Tanh", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Asin, "Asin", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Acos, "Acos", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan, "Atan", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan2, "Atan2", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Log10, "Log10", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Pow, "Pow", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Exp, "Exp", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Ceiling, "Ceiling", "System", "Math");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Floor, "Floor", "System", "Math");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetChar, null, null, null); // unused
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_GetDimLength, "GetLength", "System", "Array"); // not handled
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Get, "Get", null, null);
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Address, "Address", null, null);
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Set, "Set", null, null);
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StringGetChar, "get_Chars", "System", "String");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StringLength, "get_Length", "System", "String");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray, "InitializeArray", "System.Runtime.CompilerServices", "RuntimeHelpers");
//table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetTypeFromHandle, "GetTypeFromHandle", "System", "Type"); // RuntimeTypeHandle has to be RuntimeType
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal, "GetValueInternal", "System", "RuntimeTypeHandle");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeEQ, "op_Equality", "System", "Type"); // not in .NET Core
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeNEQ, "op_Inequality", "System", "Type"); // not in .NET Core
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Object_GetType, "GetType", "System", "Object");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContext, "GetStubContext", "System.StubHelpers", "StubHelpers"); // interop-specific
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr, "GetStubContextAddr", "System.StubHelpers", "StubHelpers"); // interop-specific
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetNDirectTarget, "GetNDirectTarget", "System.StubHelpers", "StubHelpers"); // interop-specific
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedAdd32, "Add", System.Threading", "Interlocked"); // unused
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedAdd64, "Add", System.Threading", "Interlocked"); // unused
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32, "ExchangeAdd", "System.Threading", "Interlocked");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd64, "ExchangeAdd", "System.Threading", "Interlocked"); // ambiguous match
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32, "Exchange", "System.Threading", "Interlocked");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg64, "Exchange", "System.Threading", "Interlocked"); // ambiguous match
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32, "CompareExchange", "System.Threading", "Interlocked");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg64, "CompareExchange", "System.Threading", "Interlocked"); // ambiguous match
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_MemoryBarrier, "MemoryBarrier", "System.Threading", "Interlocked");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetCurrentManagedThread, "GetCurrentThreadNative", "System", "Thread"); // not in .NET Core
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetManagedThreadId, "get_ManagedThreadId", "System", "Thread"); // not in .NET Core
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_ByReference_Ctor, ".ctor", "System", "ByReference`1");
table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_ByReference_Value, "get_Value", "System", "ByReference`1");
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Span_GetItem, "get_Item", "System", "Span`1"); // not handled
// table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_ReadOnlySpan_GetItem, "get_Item", "System", "ReadOnlySpan`1"); // not handled
// If this assert fails, make sure to add the new intrinsics to the table above and update the expected count below.
Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_Count == 49);
return table;
}
static IntrinsicHashtable s_IntrinsicHashtable = InitializeIntrinsicHashtable();
private CorInfoIntrinsics getIntrinsicID(CORINFO_METHOD_STRUCT_* ftn, ref bool pMustExpand)
{
pMustExpand = false;
var method = HandleToObject(ftn);
Debug.Assert(method.IsIntrinsic);
IntrinsicKey key = new IntrinsicKey();
key.MethodName = method.Name;
var metadataType = method.OwningType as MetadataType;
if (metadataType != null)
{
key.TypeNamespace = metadataType.Namespace;
key.TypeName = metadataType.Name;
}
IntrinsicEntry entry;
if (!s_IntrinsicHashtable.TryGetValue(key, out entry))
return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal;
// Some intrinsics need further disambiguation
CorInfoIntrinsics id = entry.Id;
switch (id)
{
case CorInfoIntrinsics.CORINFO_INTRINSIC_Abs:
{
// RyuJIT handles floating point overloads only
var returnTypeCategory = method.Signature.ReturnType.Category;
if (returnTypeCategory != TypeFlags.Double && returnTypeCategory != TypeFlags.Single)
return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal;
}
break;
case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Get:
case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Address:
case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Set:
if (!method.OwningType.IsArray)
return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal;
break;
case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32:
case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32:
case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32:
{
// RyuJIT handles int32 and int64 overloads only
var returnTypeCategory = method.Signature.ReturnType.Category;
if (returnTypeCategory != TypeFlags.Int32 && returnTypeCategory != TypeFlags.Int64 && returnTypeCategory != TypeFlags.IntPtr)
return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal;
// int64 overloads have different ids
if (returnTypeCategory == TypeFlags.Int64)
{
Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd64);
Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg64);
Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg64);
id = (CorInfoIntrinsics)((int)id + 1);
}
}
break;
case CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal:
case CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray:
case CorInfoIntrinsics.CORINFO_INTRINSIC_ByReference_Ctor:
case CorInfoIntrinsics.CORINFO_INTRINSIC_ByReference_Value:
pMustExpand = true;
break;
default:
break;
}
return id;
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Sensation {
public enum Connection {
NotDefined,
Straight,
Smooth,
Flat
}
public class TrackBuilder {
private class KeyframeBuilder {
private class Tangent {
public float angleTangens = float.NaN;
public float time = float.NaN;
public float value = float.NaN;
public float angle {
get {
return (float)Math.Atan(angleTangens);
}
set {
angleTangens = (float)Math.Tan(value);
}
}
public Tangent(float angleTangens) {
this.angleTangens = angleTangens;
}
}
public float time;
public float value;
public Connection leftConnection = Connection.NotDefined;
public Connection rightConnection = Connection.NotDefined;
private Tangent inTangent;
private Tangent outTangent;
public KeyframeBuilder previous;
public KeyframeBuilder next;
public KeyframeBuilder(float time, float value, Connection leftConnection, Connection rightConnection) {
this.time = time;
this.value = value;
this.leftConnection = leftConnection;
this.rightConnection = rightConnection;
}
public KeyframeBuilder(float time, float value, float inAngle, float outAngle) {
this.time = time;
this.value = value;
this.inTangent = new Tangent(inAngle);
this.outTangent = new Tangent(outAngle);
}
private float DeltaTime(float from, float to) {
var delta = to - from;
if (Math.Abs(delta) < 0.0001f) {
delta = 0.0001f * Math.Sign(delta);
}
return delta;
}
public Track.Keyframe Build() {
// calculate tangents for straight or flat connection (tan(angle))
if (previous != null) {
if (leftConnection != Connection.NotDefined) {
var angleTangens = leftConnection == Connection.Flat ? 0 : (value - previous.value) / DeltaTime(previous.time, time);
inTangent = new Tangent(angleTangens);
}
} else {
inTangent = null;
leftConnection = Connection.NotDefined;
}
if (next != null) {
if (rightConnection != Connection.NotDefined) {
var angleTangens = rightConnection == Connection.Flat ? 0 : (next.value - value) / DeltaTime(time, next.time);
outTangent = new Tangent(angleTangens);
}
} else {
outTangent = null;
rightConnection = Connection.NotDefined;
}
// smooth
if (inTangent != null && outTangent != null) {
// the closer to a point, the higher the weight
var outAngleWeight = DeltaTime(previous.time, time) / DeltaTime(previous.time, next.time);
var inAngleWeight = 1 - outAngleWeight;
var averageAngle = inTangent.angle * inAngleWeight + outTangent.angle * outAngleWeight;
if (leftConnection == Connection.Smooth) {
inTangent.angle = averageAngle;
}
if (rightConnection == Connection.Smooth) {
outTangent.angle = averageAngle;
}
}
// calculate tangents
if (inTangent != null) {
var tangentTime = DeltaTime(previous.time, time) / 3f;
inTangent.time = time - tangentTime;
inTangent.value = value - tangentTime * inTangent.angleTangens;
}
if (outTangent != null) {
var tangentTime = DeltaTime(time, next.time) / 3f;
outTangent.time = time + tangentTime;
outTangent.value = value + tangentTime * outTangent.angleTangens;
}
// build result
var keyframe = new Track.Keyframe();
keyframe.ControlPoint = BuildPoint(time, value);
if (inTangent != null) {
keyframe.InTangentStart = BuildPoint(inTangent.time, inTangent.value);
}
if (outTangent != null) {
keyframe.OutTangentEnd = BuildPoint(outTangent.time, outTangent.value);
}
return keyframe;
}
private Track.Keyframe.Point BuildPoint(float time, float value) {
var point = new Track.Keyframe.Point();
point.Time = time;
point.Value = value;
return point;
}
}
private Vibration.Region region;
private int actorIndex;
private SortedDictionary<float, KeyframeBuilder> keyframeBuilders = new SortedDictionary<float, KeyframeBuilder>();
public TrackBuilder(Vibration.Region region, int actorIndex) {
this.region = region;
this.actorIndex = actorIndex;
}
public TrackBuilder AddKeyframe(float time, float value) {
return AddKeyframe(time, value, Connection.Smooth);
}
public TrackBuilder AddKeyframe(float time, float value, Connection connection) {
return AddKeyframe(time, value, connection, connection);
}
public TrackBuilder AddKeyframe(float time, float value, Connection leftConnection, Connection rightConnection) {
return AddKeyframeBuilder(new KeyframeBuilder(time, value, leftConnection, rightConnection));
}
public TrackBuilder AddKeyframe(float time, float value, float inAngle, float outAngle) {
return AddKeyframeBuilder(new KeyframeBuilder(time, value, inAngle, outAngle));
}
private TrackBuilder AddKeyframeBuilder(KeyframeBuilder builder) {
keyframeBuilders.Add(builder.time, builder);
return this;
}
public Track Build() {
KeyframeBuilder previousKeyframeBuilder = null;
foreach (var builder in keyframeBuilders.Values) {
builder.previous = previousKeyframeBuilder;
if (previousKeyframeBuilder != null) {
previousKeyframeBuilder.next = builder;
}
previousKeyframeBuilder = builder;
}
var keyframes = new List<Track.Keyframe>();
foreach (var builder in keyframeBuilders.Values) {
keyframes.Add(builder.Build());
}
var track = new Track();
track.TargetRegion = region;
track.ActorIndex = actorIndex;
track.Keyframes = keyframes.ToArray();
return track;
}
}
public class PatternBuilder {
private List<TrackBuilder> trackBuilders = new List<TrackBuilder>();
private string identifier;
public PatternBuilder(string identifier) {
this.identifier = identifier;
}
public TrackBuilder AddTrack(Vibration.Region region, int actorIndex) {
var builder = new TrackBuilder(region, actorIndex);
trackBuilders.Add(builder);
return builder;
}
public LoadPattern Build() {
var pattern = new LoadPattern();
pattern.Identifier = identifier;
var tracks = new List<Track>();
foreach (var builder in trackBuilders) {
tracks.Add(builder.Build());
}
pattern.Tracks = tracks.ToArray();
return pattern;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using NLog.Config;
using NLog.Filters;
using Xunit;
public class RuleConfigurationTests : NLogTestBase
{
[Fact]
public void NoRulesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
</rules>
</nlog>");
Assert.Equal(0, c.LoggingRules.Count);
}
[Fact]
public void SimpleRuleTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal("*", rule.LoggerNamePattern);
Assert.Equal(4, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Info));
Assert.True(rule.Levels.Contains(LogLevel.Warn));
Assert.True(rule.Levels.Contains(LogLevel.Error));
Assert.True(rule.Levels.Contains(LogLevel.Fatal));
Assert.Equal(1, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.False(rule.Final);
Assert.Equal(0, rule.Filters.Count);
}
[Fact]
public void SingleLevelTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(1, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Warn));
}
[Fact]
public void MinMaxLevelTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' maxLevel='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Info));
Assert.True(rule.Levels.Contains(LogLevel.Warn));
}
[Fact]
public void NoLevelsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(6, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Trace));
Assert.True(rule.Levels.Contains(LogLevel.Debug));
Assert.True(rule.Levels.Contains(LogLevel.Info));
Assert.True(rule.Levels.Contains(LogLevel.Warn));
Assert.True(rule.Levels.Contains(LogLevel.Error));
Assert.True(rule.Levels.Contains(LogLevel.Fatal));
}
[Fact]
public void ExplicitLevelsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' levels='Trace,Info,Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Levels.Count);
Assert.True(rule.Levels.Contains(LogLevel.Trace));
Assert.True(rule.Levels.Contains(LogLevel.Info));
Assert.True(rule.Levels.Contains(LogLevel.Warn));
}
[Fact]
public void MultipleTargetsTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.Same(c.FindTargetByName("d2"), rule.Targets[1]);
Assert.Same(c.FindTargetByName("d3"), rule.Targets[2]);
}
[Fact]
public void MultipleRulesSameTargetTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
<target name='d3' type='Debug' layout='${message}' />
<target name='d4' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
<logger name='*' level='Warn' writeTo='d2' />
<logger name='*' level='Warn' writeTo='d3' />
</rules>
</nlog>");
LogFactory factory = new LogFactory(c);
var loggerConfig = factory.GetConfigurationForLogger("AAA", c);
var targets = loggerConfig.GetTargetsForLevel(LogLevel.Warn);
Assert.Equal("d1", targets.Target.Name);
Assert.Equal("d2", targets.NextInChain.Target.Name);
Assert.Equal("d3", targets.NextInChain.NextInChain.Target.Name);
Assert.Null(targets.NextInChain.NextInChain.NextInChain);
LogManager.Configuration = c;
var logger = LogManager.GetLogger("BBB");
logger.Warn("test1234");
this.AssertDebugLastMessage("d1", "test1234");
this.AssertDebugLastMessage("d2", "test1234");
this.AssertDebugLastMessage("d3", "test1234");
this.AssertDebugLastMessage("d4", string.Empty);
}
[Fact]
public void ChildRulesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<logger name='Foo*' writeTo='d4' />
<logger name='Bar*' writeTo='d4' />
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.ChildRules.Count);
Assert.Equal("Foo*", rule.ChildRules[0].LoggerNamePattern);
Assert.Equal("Bar*", rule.ChildRules[1].LoggerNamePattern);
}
[Fact]
public void FiltersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<filters>
<when condition=""starts-with(message, 'x')"" action='Ignore' />
<when condition=""starts-with(message, 'z')"" action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Filters.Count);
var conditionBasedFilter = rule.Filters[0] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'x')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
conditionBasedFilter = rule.Filters[1] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'z')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
}
[Fact]
public void LoggingRule_Final_SuppressesOnlyMatchingLevels()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='a' level='Debug' final='true' />
<logger name='*' minlevel='Debug' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = c;
Logger a = LogManager.GetLogger("a");
Assert.False(a.IsDebugEnabled);
Assert.True(a.IsInfoEnabled);
a.Info("testInfo");
a.Debug("suppressedDebug");
AssertDebugLastMessage("d1", "testInfo");
Logger b = LogManager.GetLogger("b");
b.Debug("testDebug");
AssertDebugLastMessage("d1", "testDebug");
}
}
}
| |
/*
* This is a part of the BugTrap package.
* Copyright (c) 2005-2009 IntelleSoft.
* All rights reserved.
*
* Description: Web request handler.
* Author: Maksim Pyatkovskiy.
*
* This source code is only intended as a supplement to the
* BugTrap package reference and related electronic documentation
* provided with the product. See these sources for detailed
* information regarding the BugTrap package.
*/
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Diagnostics;
using System.Collections.Generic;
using System.Web;
using System.Xml;
using IntelleSoft.Collections;
namespace BugTrapServer
{
/// <summary>
/// Web request handler.
/// </summary>
public partial class RequestHandler : System.Web.UI.Page
{
/// <summary>
/// Protocol signature.
/// </summary>
private const string protocolSignature = "BT01";
/// <summary>
/// Shared XML writer settings.
/// </summary>
private static XmlWriterSettings settings;
/// <summary>
/// Protocol message type.
/// </summary>
private enum MessageType
{
/// <summary>
/// Compound message that includes project info and report data.
/// </summary>
CompundMessage = 1
};
/// <summary>
/// Compound message flags.
/// </summary>
[Flags]
private enum CompoundMessageFlags
{
/// <summary>
/// No flags specified.
/// </summary>
None = 0x00,
};
static RequestHandler()
{
RequestHandler.settings = new XmlWriterSettings();
RequestHandler.settings.ConformanceLevel = ConformanceLevel.Fragment;
RequestHandler.settings.Indent = true;
}
/// <summary>
/// Generate directory name from the application name.
/// </summary>
/// <param name="appTitle">Application title.</param>
/// <returns>Directory name.</returns>
private static string GetAppDirName(string appTitle)
{
const string allowedChars = " _(){}.,;!+-";
StringBuilder dirName = new StringBuilder();
int position = 0, length = appTitle.Length;
while (position < length)
{
if (char.IsSurrogate(appTitle, position))
{
if (char.IsLetterOrDigit(appTitle, position))
{
dirName.Append(appTitle[position++]);
dirName.Append(appTitle[position++]);
}
}
else
{
char ch = appTitle[position++];
if ((char.IsLetterOrDigit(ch) || allowedChars.IndexOf(ch) >= 0))
dirName.Append(ch);
}
}
return dirName.ToString();
}
/// <summary>
/// Find application entry in the application item list.
/// </summary>
/// <param name="applicationSettings">Application settings.</param>
/// <param name="appEntry">Application entry to search for.</param>
/// <returns>True if appropriate entry was found and false otherwise.</returns>
private bool FindAppEntry(ApplicationSettings applicationSettings, AppEntry appEntry)
{
Set<AppEntry> applicationList = applicationSettings.ApplicationList;
if (applicationList == null || applicationList.Count == 0)
return true;
if (applicationList.Contains(appEntry))
return true;
if (appEntry.Version != null)
{
AppEntry appEntry2 = new AppEntry(appEntry.Name);
if (applicationList.Contains(appEntry2))
return true;
}
return false;
}
/// <summary>
/// Find report file extension in the list of accepted extensions.
/// </summary>
/// <param name="applicationSettings">Application settings.</param>
/// <param name="extension">Report file extension.</param>
/// <returns>True if appropriate extension was found and false otherwise.</returns>
private bool FindReportFileExtension(ApplicationSettings applicationSettings, string extension)
{
Set<string> reportFileExtensions = applicationSettings.ReportFileExtensions;
if (reportFileExtensions == null || reportFileExtensions.Count == 0)
return true;
return reportFileExtensions.Contains(extension);
}
/// <summary>
/// Send notification e-mail.
/// </summary>
/// <param name="applicationSettings">Application settings.</param>
/// <param name="email">Notification e-mail address.</param>
/// <param name="appTitle">Application title.</param>
private void SendEMail(ApplicationSettings applicationSettings, string email, string appTitle)
{
if (!string.IsNullOrEmpty(applicationSettings.SmtpHost) &&
!string.IsNullOrEmpty(email))
{
string senderAddress = applicationSettings.SenderAddress ?? string.Empty;
MailMessage message = new MailMessage(senderAddress, email);
message.Subject = '\"' + appTitle + "\" error report";
message.Body = "BugTrap server received error report of \"" + appTitle + "\" on " + DateTime.Now.ToString();
SmtpClient smtpClient;
if (applicationSettings.SmtpPort > 0)
smtpClient = new SmtpClient(applicationSettings.SmtpHost, applicationSettings.SmtpPort);
else
smtpClient = new SmtpClient(applicationSettings.SmtpHost);
smtpClient.EnableSsl = applicationSettings.SmtpSSL;
if (applicationSettings.SmtpUser != null)
smtpClient.Credentials = new NetworkCredential(applicationSettings.SmtpUser, applicationSettings.SmtpPassword);
smtpClient.Send(message);
}
}
/// <summary>
/// Handle client request.
/// </summary>
private void HandleRequest()
{
ApplicationSettings applicationSettings = (ApplicationSettings)this.Application["applicationSettings"];
Dictionary<string, AppDirInfo> lastReportNumbers = (Dictionary<string, AppDirInfo>)this.Application["lastReportNumbers"];
if (this.Request.Form["protocolSignature"] != RequestHandler.protocolSignature)
throw new ApplicationException("Unsupported protocol version");
MessageType messageType = (MessageType)byte.Parse(this.Request.Form["messageType"]);
if (messageType != MessageType.CompundMessage)
throw new Exception("Unsupported message type");
CompoundMessageFlags messageFlags = (CompoundMessageFlags)uint.Parse(this.Request.Form["messageFlags"]);
if (messageFlags != CompoundMessageFlags.None)
throw new Exception("Unsupported message flags");
string appName = this.Request.Form["appName"];
string appVersion = this.Request.Form["appVersion"];
if (appName == string.Empty)
appName = "(UNTITLED)";
string appTitle = appVersion == string.Empty ? appName : appName + ' ' + appVersion;
AppEntry appEntry = new AppEntry(appName, appVersion);
if (!this.FindAppEntry(applicationSettings, appEntry))
throw new Exception("Report excluded by filter");
string extension = this.Request.Form["reportFileExtension"];
if (!this.FindReportFileExtension(applicationSettings, extension))
throw new Exception("Invalid report file extension");
HttpPostedFile reportDataFile = this.Request.Files["reportData"];
if (reportDataFile == null)
throw new Exception("Invalid report data");
int reportSize = reportDataFile.ContentLength;
if ((applicationSettings.MaxReportSize >= 0 && reportSize > applicationSettings.MaxReportSize) || reportSize <= 0)
throw new Exception("Report exceeds size limit");
string email = this.Request.Form["notificationEMail"];
string dirName = GetAppDirName(appTitle);
int maxReportNumber = 0, numReports = 0;
lock (lastReportNumbers)
{
AppDirInfo appDirInfo;
if (lastReportNumbers.TryGetValue(dirName, out appDirInfo))
{
maxReportNumber = appDirInfo.MaxReportNumber;
numReports = appDirInfo.NumReports;
}
if (applicationSettings.ReportsLimit >= 0 && numReports > applicationSettings.ReportsLimit)
throw new ApplicationException("Number of reports exceeds the limit");
if (appDirInfo == null)
{
appDirInfo = new AppDirInfo();
lastReportNumbers[dirName] = appDirInfo;
}
appDirInfo.NumReports = ++numReports;
appDirInfo.MaxReportNumber = ++maxReportNumber;
}
string reportDir = Path.Combine(applicationSettings.ReportPath, dirName);
Directory.CreateDirectory(reportDir);
string fileName = Global.GetReportName(applicationSettings, maxReportNumber, extension);
string filePath = Path.Combine(reportDir, fileName);
Stream inputStream = null;
FileStream outputStream = null;
try
{
inputStream = reportDataFile.InputStream;
outputStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
byte[] reportData = new byte[1024];
while (reportSize > 0)
{
int chunkSize = Math.Min(reportSize, reportData.Length);
inputStream.Read(reportData, 0, chunkSize);
outputStream.Write(reportData, 0, chunkSize);
reportSize -= chunkSize;
}
this.SendEMail(applicationSettings, email, appTitle);
}
finally
{
if (inputStream != null)
inputStream.Close();
if (outputStream != null)
outputStream.Close();
}
}
/// <summary>
/// Send server response to the client.
/// <param name="code">Error code.</param>
/// <param name="description">Error description.</param>
/// </summary>
private void WriteResponse(string code, string description)
{
this.Response.Clear();
this.Response.ContentType = "text/xml";
this.Response.ContentEncoding = Encoding.UTF8;
XmlWriter writer = XmlWriter.Create(this.Response.Output, settings);
try
{
writer.WriteStartElement("result");
writer.WriteElementString("code", code);
writer.WriteElementString("description", description);
writer.WriteEndElement();
}
finally
{
writer.Close();
}
this.Response.Flush();
}
/// <summary>
/// Occurs when the server control is loaded into the Page object.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs object that contains the event data.</param>
[DoNotObfuscate]
protected void Page_Load(object sender, EventArgs e)
{
string code = "OK";
string description = "The operation completed successfully";
try
{
this.HandleRequest();
}
catch (Exception error)
{
code = "Error";
description = error.Message;
this.ReportNestedError(error);
}
finally
{
this.WriteResponse(code, description);
}
}
/// <summary>
/// Get inner exception object.
/// </summary>
/// <param name="error">Topmost exception object.</param>
/// <returns>Inner exception object.</returns>
private static Exception GetNestedError(Exception error)
{
while (error.InnerException != null)
error = error.InnerException;
return error;
}
private EventLog GetEventLog()
{
EventLog eventLog = (EventLog)this.Application["eventLog"];
if (eventLog == null)
{
eventLog = new EventLog();
eventLog.Source = "BugTrapWebServer";
this.Application["eventLog"] = eventLog;
}
return eventLog;
}
/// <summary>
/// Print error message on a console and add error message to the event log.
/// </summary>
/// <param name="error">Exception information.</param>
private void ReportError(Exception error)
{
string message = error.ToString();
Debug.WriteLine(message);
ApplicationSettings applicationSettings = (ApplicationSettings)this.Application["applicationSettings"];
if (applicationSettings.LogEvents)
{
EventLog eventLog = this.GetEventLog();
eventLog.WriteEntry(message, EventLogEntryType.Error);
}
}
/// <summary>
/// Print error message on a console and add error message to the event log.
/// </summary>
/// <param name="error">Exception information.</param>
private void ReportNestedError(Exception error)
{
error = GetNestedError(error);
this.ReportError(error);
}
}
}
| |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Should;
using Xunit;
namespace AutoMapper.UnitTests
{
namespace NullBehavior
{
public class When_mapping_a_model_with_null_items : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelDto
{
public ModelSubDto Sub { get; set; }
public int SubSomething { get; set; }
public string NullString { get; set; }
}
public class ModelSubDto
{
public int[] Items { get; set; }
}
public class ModelObject
{
public ModelSubObject Sub { get; set; }
public string NullString { get; set; }
}
public class ModelSubObject
{
public int[] GetItems()
{
return new[] { 0, 1, 2, 3 };
}
public int Something { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = false;
cfg.CreateMap<ModelObject, ModelDto>();
cfg.CreateMap<ModelSubObject, ModelSubDto>();
});
protected override void Because_of()
{
var model = new ModelObject();
model.Sub = null;
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_populate_dto_items_with_a_value()
{
_result.Sub.ShouldNotBeNull();
}
[Fact]
public void Should_provide_empty_array_for_array_type_values()
{
_result.Sub.Items.ShouldNotBeNull();
}
[Fact]
public void Should_return_default_value_of_property_in_the_chain()
{
_result.SubSomething.ShouldEqual(0);
}
[Fact]
public void Default_value_for_string_should_be_empty()
{
_result.NullString.ShouldEqual(string.Empty);
}
}
public class When_overriding_null_behavior_with_null_source_items : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelDto
{
public ModelSubDto Sub { get; set; }
public int SubSomething { get; set; }
public string NullString { get; set; }
}
public class ModelSubDto
{
public int[] Items { get; set; }
}
public class ModelObject
{
public ModelSubObject Sub { get; set; }
public string NullString { get; set; }
}
public class ModelSubObject
{
public int[] GetItems()
{
return new[] { 0, 1, 2, 3 };
}
public int Something { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = true;
cfg.CreateMap<ModelObject, ModelDto>();
cfg.CreateMap<ModelSubObject, ModelSubDto>();
});
protected override void Because_of()
{
var model = new ModelObject();
model.Sub = null;
model.NullString = null;
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_map_first_level_items_as_null()
{
_result.NullString.ShouldBeNull();
}
[Fact]
public void Should_map_primitive_items_as_default()
{
_result.SubSomething.ShouldEqual(0);
}
[Fact]
public void Should_map_any_sub_mapped_items_as_null()
{
_result.Sub.ShouldBeNull();
}
}
public class When_overriding_null_behavior_in_a_profile : AutoMapperSpecBase
{
private DefaultDestination _defaultResult;
private NullDestination _nullResult;
public class DefaultSource
{
public object Value { get; set; }
}
public class DefaultDestination
{
public object Value { get; set; }
}
public class NullSource
{
public object Value { get; set; }
}
public class NullDestination
{
public object Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateProfile("MapsNulls", p =>
{
p.AllowNullDestinationValues = false;
p.CreateMap<NullSource, NullDestination>();
});
cfg.CreateMap<DefaultSource, DefaultDestination>();
});
protected override void Because_of()
{
_defaultResult = Mapper.Map<DefaultSource, DefaultDestination>(new DefaultSource());
_nullResult = Mapper.Map<NullSource, NullDestination>(new NullSource());
}
[Fact]
public void Should_use_default_behavior_in_default_profile()
{
_defaultResult.Value.ShouldBeNull();
}
[Fact]
public void Should_use_overridden_null_behavior_in_profile()
{
_nullResult.Value.ShouldNotBeNull();
}
}
public class When_using_a_custom_resolver_and_the_source_value_is_null : NonValidatingSpecBase
{
public class NullResolver : ValueResolver<Source, string>
{
protected override string ResolveCore(Source source)
{
if (source == null)
return "jon";
return "fail";
}
}
private static Source _source;
private Destination _dest;
public class Source
{
public string MyName { get; set; }
}
public class Destination
{
public string Name { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Name, opt => opt.ResolveUsing<NullResolver>().FromMember(src => src.MyName));
_source = new Source();
});
protected override void Because_of()
{
_dest = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_perform_the_translation()
{
_dest.Name.ShouldEqual("jon");
}
}
public class When_mapping_using_a_custom_member_mapping_and_source_is_null : AutoMapperSpecBase
{
private Dest _dest;
public class Source
{
public SubSource Sub { get; set; }
}
public class SubSource
{
public int Value { get; set; }
}
public class Dest
{
public int OtherValue { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = false;
cfg.CreateMap<Source, Dest>()
.ForMember(dest => dest.OtherValue, opt => opt.MapFrom(src => src.Sub.Value));
});
protected override void Because_of()
{
_dest = Mapper.Map<Source, Dest>(new Source());
}
[Fact]
public void Should_map_to_null_on_destination_values()
{
_dest.OtherValue.ShouldEqual(0);
}
}
public class When_specifying_a_resolver_for_a_nullable_type : AutoMapperSpecBase
{
private FooViewModel _result;
public class NullableBoolToLabel : TypeConverter<bool?, string>
{
protected override string ConvertCore(bool? source)
{
if (source.HasValue)
{
if (source.Value)
return "Yes";
else
return "No";
}
else
return "(n/a)";
}
}
public class Foo
{
public bool? IsFooBarred { get; set; }
}
public class FooViewModel
{
public string IsFooBarred { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<bool?, string>().ConvertUsing<NullableBoolToLabel>();
cfg.CreateMap<Foo, FooViewModel>();
});
protected override void Because_of()
{
var foo3 = new Foo { IsFooBarred = null };
_result = Mapper.Map<Foo, FooViewModel>(foo3);
}
[Fact]
public void Should_allow_the_resolver_to_handle_null_values()
{
_result.IsFooBarred.ShouldEqual("(n/a)");
}
}
public class When_overriding_collection_null_behavior : AutoMapperSpecBase
{
private Dest _dest;
public class Source
{
public IEnumerable<int> Values1 { get; set; }
public List<int> Values2 { get; set; }
public Dictionary<string, int> Values3 { get; set; }
public int[] Values4 { get; set; }
public ReadOnlyCollection<int> Values5 { get; set; }
public Collection<int> Values6 { get; set; }
}
public class Dest
{
public IEnumerable<int> Values1 { get; set; }
public List<int> Values2 { get; set; }
public Dictionary<string, int> Values3 { get; set; }
public int[] Values4 { get; set; }
public ReadOnlyCollection<int> Values5 { get; set; }
public Collection<int> Values6 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Dest>();
cfg.AllowNullCollections = true;
});
protected override void Because_of()
{
_dest = Mapper.Map<Source, Dest>(new Source());
}
[Fact]
public void Should_allow_null_ienumerables()
{
_dest.Values1.ShouldBeNull();
}
[Fact]
public void Should_allow_null_lists()
{
_dest.Values2.ShouldBeNull();
}
[Fact]
public void Should_allow_null_dictionaries()
{
_dest.Values3.ShouldBeNull();
}
[Fact]
public void Should_allow_null_arrays()
{
_dest.Values4.ShouldBeNull();
}
[Fact]
public void Should_allow_null_read_only_collections()
{
_dest.Values5.ShouldBeNull();
}
[Fact]
public void Should_allow_null_collections()
{
_dest.Values6.ShouldBeNull();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace BrainWave.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (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.Globalization;
using Xunit;
public static class DecimalTests
{
[Fact]
public static void TestEquals()
{
// Boolean Decimal.Equals(Decimal)
Assert.True(Decimal.Zero.Equals(Decimal.Zero));
Assert.False(Decimal.Zero.Equals(Decimal.One));
Assert.True(Decimal.MaxValue.Equals(Decimal.MaxValue));
Assert.True(Decimal.MinValue.Equals(Decimal.MinValue));
Assert.False(Decimal.MaxValue.Equals(Decimal.MinValue));
Assert.False(Decimal.MinValue.Equals(Decimal.MaxValue));
}
[Fact]
public static void TestEqualsDecDec()
{
// Boolean Decimal.Equals(Decimal, Decimal)
Assert.True(Decimal.Equals(Decimal.Zero, Decimal.Zero));
Assert.False(Decimal.Equals(Decimal.Zero, Decimal.One));
Assert.True(Decimal.Equals(Decimal.MaxValue, Decimal.MaxValue));
Assert.True(Decimal.Equals(Decimal.MinValue, Decimal.MinValue));
Assert.False(Decimal.Equals(Decimal.MinValue, Decimal.MaxValue));
Assert.False(Decimal.Equals(Decimal.MaxValue, Decimal.MinValue));
}
[Fact]
public static void TestEqualsObj()
{
// Boolean Decimal.Equals(Object)
Assert.True(Decimal.Zero.Equals((object)Decimal.Zero));
Assert.False(Decimal.Zero.Equals((object)Decimal.One));
Assert.True(Decimal.MaxValue.Equals((object)Decimal.MaxValue));
Assert.True(Decimal.MinValue.Equals((object)Decimal.MinValue));
Assert.False(Decimal.MinValue.Equals((object)Decimal.MaxValue));
Assert.False(Decimal.MaxValue.Equals((object)Decimal.MinValue));
Assert.False(Decimal.One.Equals(null));
Assert.False(Decimal.One.Equals("one"));
Assert.False(Decimal.One.Equals((object)1));
}
[Fact]
public static void Testop_Equality()
{
// Boolean Decimal.op_Equality(Decimal, Decimal)
Assert.True(Decimal.Zero == Decimal.Zero);
Assert.False(Decimal.Zero == Decimal.One);
Assert.True(Decimal.MaxValue == Decimal.MaxValue);
Assert.True(Decimal.MinValue == Decimal.MinValue);
Assert.False(Decimal.MinValue == Decimal.MaxValue);
Assert.False(Decimal.MaxValue == Decimal.MinValue);
}
[Fact]
public static void Testop_GreaterThan()
{
// Boolean Decimal.op_GreaterThan(Decimal, Decimal)
Assert.False(Decimal.Zero > Decimal.Zero);
Assert.False(Decimal.Zero > Decimal.One);
Assert.True(Decimal.One > Decimal.Zero);
Assert.False(Decimal.MaxValue > Decimal.MaxValue);
Assert.False(Decimal.MinValue > Decimal.MinValue);
Assert.False(Decimal.MinValue > Decimal.MaxValue);
Assert.True(Decimal.MaxValue > Decimal.MinValue);
}
[Fact]
public static void Testop_GreaterThanOrEqual()
{
// Boolean Decimal.op_GreaterThanOrEqual(Decimal, Decimal)
Assert.True(Decimal.Zero >= Decimal.Zero);
Assert.False(Decimal.Zero >= Decimal.One);
Assert.True(Decimal.One >= Decimal.Zero);
Assert.True(Decimal.MaxValue >= Decimal.MaxValue);
Assert.True(Decimal.MinValue >= Decimal.MinValue);
Assert.False(Decimal.MinValue >= Decimal.MaxValue);
Assert.True(Decimal.MaxValue >= Decimal.MinValue);
}
[Fact]
public static void Testop_Inequality()
{
// Boolean Decimal.op_Inequality(Decimal, Decimal)
Assert.False(Decimal.Zero != Decimal.Zero);
Assert.True(Decimal.Zero != Decimal.One);
Assert.True(Decimal.One != Decimal.Zero);
Assert.False(Decimal.MaxValue != Decimal.MaxValue);
Assert.False(Decimal.MinValue != Decimal.MinValue);
Assert.True(Decimal.MinValue != Decimal.MaxValue);
Assert.True(Decimal.MaxValue != Decimal.MinValue);
}
[Fact]
public static void Testop_LessThan()
{
// Boolean Decimal.op_LessThan(Decimal, Decimal)
Assert.False(Decimal.Zero < Decimal.Zero);
Assert.True(Decimal.Zero < Decimal.One);
Assert.False(Decimal.One < Decimal.Zero);
Assert.True(5m < 15m);
decimal d5 = 5;
decimal d3 = 3;
Assert.False(d5 < d3);
Assert.False(Decimal.MaxValue < Decimal.MaxValue);
Assert.False(Decimal.MinValue < Decimal.MinValue);
Assert.True(Decimal.MinValue < Decimal.MaxValue);
Assert.False(Decimal.MaxValue < Decimal.MinValue);
}
[Fact]
public static void Testop_LessThanOrEqual()
{
// Boolean Decimal.op_LessThanOrEqual(Decimal, Decimal)
Assert.True(Decimal.Zero <= Decimal.Zero);
Assert.True(Decimal.Zero <= Decimal.One);
Assert.False(Decimal.One <= Decimal.Zero);
Assert.True(Decimal.MaxValue <= Decimal.MaxValue);
Assert.True(Decimal.MinValue <= Decimal.MinValue);
Assert.True(Decimal.MinValue <= Decimal.MaxValue);
Assert.False(Decimal.MaxValue <= Decimal.MinValue);
}
[Fact]
public static void TestToByte()
{
// Byte Decimal.ToByte(Decimal)
Assert.Equal(0, Decimal.ToByte(0));
Assert.Equal(1, Decimal.ToByte(1));
Assert.Equal(255, Decimal.ToByte(255));
Assert.Throws<OverflowException>(() => Decimal.ToByte(256));
}
private static void VerifyAdd<T>(Decimal d1, Decimal d2, Decimal expected = Decimal.Zero) where T : Exception
{
bool expectFailure = typeof(T) != typeof(Exception);
try
{
Decimal result1 = Decimal.Add(d1, d2);
Decimal result2 = d1 + d2;
Assert.False(expectFailure, "Expected an exception to be thrown");
Assert.Equal(result1, result2);
Assert.Equal(expected, result1);
}
catch (T)
{
Assert.True(expectFailure, "Didn't expect an exception to be thrown");
}
}
[Fact]
public static void TestAdd()
{
// Decimal Decimal.Add(Decimal, Decimal)
// Decimal Decimal.op_Addition(Decimal, Decimal)
VerifyAdd<Exception>(1, 1, 2);
VerifyAdd<Exception>(-1, 1, 0);
VerifyAdd<Exception>(1, -1, 0);
VerifyAdd<Exception>(Decimal.MaxValue, Decimal.Zero, Decimal.MaxValue);
VerifyAdd<Exception>(Decimal.MinValue, Decimal.Zero, Decimal.MinValue);
VerifyAdd<Exception>(79228162514264337593543950330m, 5, Decimal.MaxValue);
VerifyAdd<Exception>(79228162514264337593543950330m, -5, 79228162514264337593543950325m);
VerifyAdd<Exception>(-79228162514264337593543950330m, -5, Decimal.MinValue);
VerifyAdd<Exception>(-79228162514264337593543950330m, 5, -79228162514264337593543950325m);
VerifyAdd<Exception>(1234.5678m, 0.00009m, 1234.56789m);
VerifyAdd<Exception>(-1234.5678m, 0.00009m, -1234.56771m);
VerifyAdd<Exception>(0.1111111111111111111111111111m,
0.1111111111111111111111111111m,
0.2222222222222222222222222222m);
VerifyAdd<Exception>(0.5555555555555555555555555555m,
0.5555555555555555555555555555m,
1.1111111111111111111111111110m);
// Exceptions
VerifyAdd<OverflowException>(Decimal.MaxValue, Decimal.MaxValue);
VerifyAdd<OverflowException>(79228162514264337593543950330m, 6);
VerifyAdd<OverflowException>(-79228162514264337593543950330m, -6, Decimal.MinValue);
}
[Fact]
public static void TestCeiling()
{
// Decimal Decimal.Ceiling(Decimal)
Assert.Equal<Decimal>(123, Decimal.Ceiling((Decimal)123));
Assert.Equal<Decimal>(124, Decimal.Ceiling((Decimal)123.123));
Assert.Equal<Decimal>(-123, Decimal.Ceiling((Decimal)(-123.123)));
Assert.Equal<Decimal>(124, Decimal.Ceiling((Decimal)123.567));
Assert.Equal<Decimal>(-123, Decimal.Ceiling((Decimal)(-123.567)));
}
private static void VerifyDivide<T>(Decimal d1, Decimal d2, Decimal expected = Decimal.Zero) where T : Exception
{
bool expectFailure = typeof(T) != typeof(Exception);
try
{
Decimal result1 = Decimal.Divide(d1, d2);
Decimal result2 = d1 / d2;
Assert.False(expectFailure, "Expected an exception to be thrown");
Assert.Equal(result1, result2);
Assert.Equal(expected, result1);
}
catch (T)
{
Assert.True(expectFailure, "Didn't expect an exception to be thrown");
}
}
[Fact]
public static void TestDivide()
{
// Decimal Decimal.Divide(Decimal, Decimal)
// Decimal Decimal.op_Division(Decimal, Decimal)
// Vanilla cases
VerifyDivide<Exception>(Decimal.One, Decimal.One, Decimal.One);
VerifyDivide<Exception>(Decimal.MaxValue, Decimal.MinValue, Decimal.MinusOne);
VerifyDivide<Exception>(0.9214206543486529434634231456m, Decimal.MaxValue, Decimal.Zero);
VerifyDivide<Exception>(38214206543486529434634231456m, 0.49214206543486529434634231456m, 77648730371625094566866001277m);
VerifyDivide<Exception>(-78228162514264337593543950335m, Decimal.MaxValue, -0.987378225516463811113412343m);
VerifyDivide<Exception>(5m + 10m, 2m, 7.5m);
VerifyDivide<Exception>(10m, 2m, 5m);
// Tests near MaxValue (VSWhidbey #389382)
VerifyDivide<Exception>(792281625142643375935439503.4m, 0.1m, 7922816251426433759354395034m);
VerifyDivide<Exception>(79228162514264337593543950.34m, 0.1m, 792281625142643375935439503.4m);
VerifyDivide<Exception>(7922816251426433759354395.034m, 0.1m, 79228162514264337593543950.34m);
VerifyDivide<Exception>(792281625142643375935439.5034m, 0.1m, 7922816251426433759354395.034m);
VerifyDivide<Exception>(79228162514264337593543950335m, 10m, 7922816251426433759354395033.5m);
VerifyDivide<Exception>(79228162514264337567774146561m, 10m, 7922816251426433756777414656.1m);
VerifyDivide<Exception>(79228162514264337567774146560m, 10m, 7922816251426433756777414656m);
VerifyDivide<Exception>(79228162514264337567774146559m, 10m, 7922816251426433756777414655.9m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.1m, 72025602285694852357767227577m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.01m, 78443725261647859003508861718m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.001m, 79149013500763574019524425909.091m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0001m, 79220240490215316061937756559.344m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.00001m, 79227370240561931974224208092.919m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.000001m, 79228083286181051412492537842.462m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000001m, 79228154591448878448656105469.389m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000001m, 79228161721982720373716746597.833m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000001m, 79228162435036175158507775176.492m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000001m, 79228162506341521342909798200.709m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000001m, 79228162513472055968409229775.316m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000001m, 79228162514185109431029765225.569m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000001m, 79228162514256414777292524693.522m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000001m, 79228162514263545311918807699.547m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000001m, 79228162514264258365381436070.742m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000001m, 79228162514264329670727698908.567m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000000001m, 79228162514264336801262325192.357m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000000001m, 79228162514264337514315787820.736m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000000001m, 79228162514264337585621134083.574m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000000000001m, 79228162514264337592751668709.857m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000000000001m, 79228162514264337593464722172.486m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000000000001m, 79228162514264337593536027518.749m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000000000000001m, 79228162514264337593543158053.375m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000000000000001m, 79228162514264337593543871106.837m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000000000000001m, 79228162514264337593543942412.184m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.00000000000000000000000001m, 79228162514264337593543949542.718m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.000000000000000000000000001m, 79228162514264337593543950255.772m);
VerifyDivide<Exception>(7922816251426433759354395033.5m, 0.9999999999999999999999999999m, 7922816251426433759354395034m);
VerifyDivide<Exception>(79228162514264337593543950335m, 10000000m, 7922816251426433759354.3950335m);
VerifyDivide<Exception>(7922816251426433759354395033.5m, 1.000001m, 7922808328618105141249253784.2m);
VerifyDivide<Exception>(7922816251426433759354395033.5m, 1.0000000000000000000000000001m, 7922816251426433759354395032.7m);
VerifyDivide<Exception>(7922816251426433759354395033.5m, 1.0000000000000000000000000002m, 7922816251426433759354395031.9m);
VerifyDivide<Exception>(7922816251426433759354395033.5m, 0.9999999999999999999999999999m, 7922816251426433759354395034m);
VerifyDivide<Exception>(79228162514264337593543950335m, 1.0000000000000000000000000001m, 79228162514264337593543950327m);
Decimal boundary7 = new Decimal((int)429u, (int)2133437386u, 0, false, 0);
Decimal boundary71 = new Decimal((int)429u, (int)2133437387u, 0, false, 0);
Decimal maxValueBy7 = Decimal.MaxValue * 0.0000001m;
VerifyDivide<Exception>(maxValueBy7, 1m, maxValueBy7);
VerifyDivide<Exception>(maxValueBy7, 1m, maxValueBy7);
VerifyDivide<Exception>(maxValueBy7, 0.0000001m, Decimal.MaxValue);
VerifyDivide<Exception>(boundary7, 1m, boundary7);
VerifyDivide<Exception>(boundary7, 0.000000100000000000000000001m, 91630438009337286849083695.62m);
VerifyDivide<Exception>(boundary71, 0.000000100000000000000000001m, 91630438052286959809083695.62m);
VerifyDivide<Exception>(7922816251426433759354.3950335m, 1m, 7922816251426433759354.3950335m);
VerifyDivide<Exception>(7922816251426433759354.3950335m, 0.0000001m, 79228162514264337593543950335m);
//[] DivideByZero exceptions
VerifyDivide<DivideByZeroException>(Decimal.One, Decimal.Zero);
VerifyDivide<DivideByZeroException>(Decimal.Zero, Decimal.Zero);
VerifyDivide<DivideByZeroException>(-5.00m, (-1m) * Decimal.Zero);
VerifyDivide<DivideByZeroException>(0.0m, -0.00m);
//[] Overflow exceptions
VerifyDivide<OverflowException>(79228162514264337593543950335m, -0.9999999999999999999999999m);
VerifyDivide<OverflowException>(792281625142643.37593543950335m, 0.0000000000000079228162514264337593543950335m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.1m);
VerifyDivide<OverflowException>(7922816251426433759354395034m, 0.1m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.99999999999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.999999999999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, 0.9999999999999999999999999999m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, -0.1m);
VerifyDivide<OverflowException>(79228162514264337593543950335m, -0.9999999999999999999999999m);
VerifyDivide<OverflowException>(Decimal.MaxValue / 2, 0.5m);
}
[Fact]
public static void TestFloor()
{
// Decimal Decimal.Floor(Decimal)
Assert.Equal<Decimal>(123, Decimal.Floor((Decimal)123));
Assert.Equal<Decimal>(123, Decimal.Floor((Decimal)123.123));
Assert.Equal<Decimal>(-124, Decimal.Floor((Decimal)(-123.123)));
Assert.Equal<Decimal>(123, Decimal.Floor((Decimal)123.567));
Assert.Equal<Decimal>(-124, Decimal.Floor((Decimal)(-123.567)));
}
[Fact]
public static void TestMaxValue()
{
// Decimal Decimal.MaxValue
Assert.Equal(Decimal.MaxValue, 79228162514264337593543950335m);
}
[Fact]
public static void TestMinusOne()
{
// Decimal Decimal.MinusOne
Assert.Equal(Decimal.MinusOne, -1);
}
[Fact]
public static void TestZero()
{
// Decimal Decimal.Zero
Assert.Equal(Decimal.Zero, 0);
}
[Fact]
public static void TestOne()
{
// Decimal Decimal.One
Assert.Equal(Decimal.One, 1);
}
[Fact]
public static void TestMinValue()
{
// Decimal Decimal.MinValue
Assert.Equal(Decimal.MinValue, -79228162514264337593543950335m);
}
private static void VerifyMultiply<T>(Decimal d1, Decimal d2, Decimal expected = Decimal.Zero) where T : Exception
{
bool expectFailure = typeof(T) != typeof(Exception);
try
{
Decimal result1 = Decimal.Multiply(d1, d2);
Decimal result2 = d1 * d2;
Assert.False(expectFailure, "Expected an exception to be thrown");
Assert.Equal(result1, result2);
Assert.Equal(expected, result1);
}
catch (T)
{
Assert.True(expectFailure, "Didn't expect an exception to be thrown");
}
}
[Fact]
public static void TestMultiply()
{
// Decimal Decimal.Multiply(Decimal, Decimal)
// Decimal Decimal.op_Multiply(Decimal, Decimal)
VerifyMultiply<Exception>(Decimal.One, Decimal.One, Decimal.One);
VerifyMultiply<Exception>(7922816251426433759354395033.5m, new Decimal(10), Decimal.MaxValue);
VerifyMultiply<Exception>(0.2352523523423422342354395033m, 56033525474612414574574757495m, 13182018677937129120135020796m);
VerifyMultiply<Exception>(46161363632634613634.093453337m, 461613636.32634613634083453337m, 21308714924243214928823669051m);
VerifyMultiply<Exception>(0.0000000000000345435353453563m, .0000000000000023525235234234m, 0.0000000000000000000000000001m);
// Near MaxValue
VerifyMultiply<Exception>(79228162514264337593543950335m, 0.9m, 71305346262837903834189555302m);
VerifyMultiply<Exception>(79228162514264337593543950335m, 0.99m, 78435880889121694217608510832m);
VerifyMultiply<Exception>(79228162514264337593543950335m, 0.9999999999999999999999999999m, 79228162514264337593543950327m);
VerifyMultiply<Exception>(-79228162514264337593543950335m, 0.9m, -71305346262837903834189555302m);
VerifyMultiply<Exception>(-79228162514264337593543950335m, 0.99m, -78435880889121694217608510832m);
VerifyMultiply<Exception>(-79228162514264337593543950335m, 0.9999999999999999999999999999m, -79228162514264337593543950327m);
// Exceptions
VerifyMultiply<OverflowException>(Decimal.MaxValue, Decimal.MinValue);
VerifyMultiply<OverflowException>(Decimal.MinValue, 1.1m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.1m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.01m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.0000000000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.00000000000000000000000001m);
VerifyMultiply<OverflowException>(79228162514264337593543950335m, 1.000000000000000000000000001m);
VerifyMultiply<OverflowException>(Decimal.MaxValue / 2, 2m);
}
[Fact]
public static void TestNegate()
{
// Decimal Decimal.Negate(Decimal)
Assert.Equal(0, Decimal.Negate(0));
Assert.Equal(1, Decimal.Negate(-1));
Assert.Equal(-1, Decimal.Negate(1));
}
[Fact]
public static void Testop_Decrement()
{
// Decimal Decimal.op_Decrement(Decimal)
Decimal d = 12345;
Assert.Equal(12344, --d);
d = 12345.678m;
Assert.Equal(12344.678m, --d);
d = -12345;
Assert.Equal(-12346, --d);
d = -12345.678m;
Assert.Equal(-12346.678m, --d);
}
[Fact]
public static void Testop_Increment()
{
// Decimal Decimal.op_Increment(Decimal)
Decimal d = 12345;
Assert.Equal(12346, ++d);
d = 12345.678m;
Assert.Equal(12346.678m, ++d);
d = -12345;
Assert.Equal(-12344m, ++d);
d = -12345.678m;
Assert.Equal(-12344.678m, ++d);
}
[Fact]
public static void TestParse()
{
// Boolean Decimal.TryParse(String, NumberStyles, IFormatProvider, Decimal)
Assert.Equal(123, Decimal.Parse("123"));
Assert.Equal(-123, Decimal.Parse("-123"));
Assert.Equal(123.123m, Decimal.Parse("123.123"));
Assert.Equal(-123.123m, Decimal.Parse("-123.123"));
Decimal d;
Assert.True(Decimal.TryParse("79228162514264337593543950335", out d));
Assert.Equal(Decimal.MaxValue, d);
Assert.True(Decimal.TryParse("-79228162514264337593543950335", out d));
Assert.Equal(Decimal.MinValue, d);
Assert.True(Decimal.TryParse("79,228,162,514,264,337,593,543,950,335", NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out d));
Assert.Equal(Decimal.MaxValue, d);
Assert.False(Decimal.TryParse("ysaidufljasdf", out d));
Assert.False(Decimal.TryParse("79228162514264337593543950336", out d));
}
private static void VerifyRemainder(Decimal d1, Decimal d2, Decimal expectedResult)
{
Decimal result1 = Decimal.Remainder(d1, d2);
Decimal result2 = d1 % d2;
Assert.Equal(result1, result2);
Assert.Equal(expectedResult, result1);
}
[Fact]
public static void TestRemainder()
{
// Decimal Decimal.Remainder(Decimal, Decimal)
// Decimal Decimal.op_Modulus(Decimal, Decimal)
Decimal NegativeZero = new Decimal(0, 0, 0, true, 0);
VerifyRemainder(5m, 3m, 2m);
VerifyRemainder(5m, -3m, 2m);
VerifyRemainder(-5m, 3m, -2m);
VerifyRemainder(-5m, -3m, -2m);
VerifyRemainder(3m, 5m, 3m);
VerifyRemainder(3m, -5m, 3m);
VerifyRemainder(-3m, 5m, -3m);
VerifyRemainder(-3m, -5m, -3m);
VerifyRemainder(10m, -3m, 1m);
VerifyRemainder(-10m, 3m, -1m);
VerifyRemainder(-2.0m, 0.5m, -0.0m);
VerifyRemainder(2.3m, 0.531m, 0.176m);
VerifyRemainder(0.00123m, 3242m, 0.00123m);
VerifyRemainder(3242m, 0.00123m, 0.00044m);
VerifyRemainder(17.3m, 3m, 2.3m);
VerifyRemainder(8.55m, 2.25m, 1.80m);
VerifyRemainder(0.00m, 3m, 0.00m);
VerifyRemainder(NegativeZero, 2.2m, NegativeZero);
// [] Max/Min
VerifyRemainder(Decimal.MaxValue, Decimal.MaxValue, 0m);
VerifyRemainder(Decimal.MaxValue, Decimal.MinValue, 0m);
VerifyRemainder(Decimal.MaxValue, 1, 0m);
VerifyRemainder(Decimal.MaxValue, 2394713m, 1494647m);
VerifyRemainder(Decimal.MaxValue, -32768m, 32767m);
VerifyRemainder(-0.00m, Decimal.MaxValue, -0.00m);
VerifyRemainder(1.23984m, Decimal.MaxValue, 1.23984m);
VerifyRemainder(2398412.12983m, Decimal.MaxValue, 2398412.12983m);
VerifyRemainder(-0.12938m, Decimal.MaxValue, -0.12938m);
VerifyRemainder(Decimal.MinValue, Decimal.MinValue, NegativeZero);
VerifyRemainder(Decimal.MinValue, Decimal.MaxValue, NegativeZero);
VerifyRemainder(Decimal.MinValue, 1, NegativeZero);
VerifyRemainder(Decimal.MinValue, 2394713m, -1494647m);
VerifyRemainder(Decimal.MinValue, -32768m, -32767m); // ASURT #90921
VerifyRemainder(0.0m, Decimal.MinValue, 0.0m);
VerifyRemainder(1.23984m, Decimal.MinValue, 1.23984m);
VerifyRemainder(2398412.12983m, Decimal.MinValue, 2398412.12983m);
VerifyRemainder(-0.12938m, Decimal.MinValue, -0.12938m);
VerifyRemainder(57675350989891243676868034225m, 7m, 5m); // VSWhidbey #325142
VerifyRemainder(-57675350989891243676868034225m, 7m, -5m);
VerifyRemainder(57675350989891243676868034225m, -7m, 5m);
VerifyRemainder(-57675350989891243676868034225m, -7m, -5m);
// VSWhidbey #389382
VerifyRemainder(792281625142643375935439503.4m, 0.1m, 0.0m);
VerifyRemainder(79228162514264337593543950.34m, 0.1m, 0.04m);
VerifyRemainder(7922816251426433759354395.034m, 0.1m, 0.034m);
VerifyRemainder(792281625142643375935439.5034m, 0.1m, 0.0034m);
VerifyRemainder(79228162514264337593543950335m, 10m, 5m);
VerifyRemainder(79228162514264337567774146561m, 10m, 1m);
VerifyRemainder(79228162514264337567774146560m, 10m, 0m);
VerifyRemainder(79228162514264337567774146559m, 10m, 9m);
}
private static void VerifySubtract<T>(Decimal d1, Decimal d2, Decimal expected = Decimal.Zero) where T : Exception
{
bool expectFailure = typeof(T) != typeof(Exception);
try
{
Decimal result1 = Decimal.Subtract(d1, d2);
Decimal result2 = d1 - d2;
Assert.False(expectFailure, "Expected an exception to be thrown");
Assert.Equal(result1, result2);
Assert.Equal(expected, result1);
}
catch (T)
{
Assert.True(expectFailure, "Didn't expect an exception to be thrown");
}
}
[Fact]
public static void TestSubtract()
{
// Decimal Decimal.Subtract(Decimal, Decimal)
// Decimal Decimal.op_Subtraction(Decimal, Decimal)
VerifySubtract<Exception>(1, 1, 0);
VerifySubtract<Exception>(-1, 1, -2);
VerifySubtract<Exception>(1, -1, 2);
VerifySubtract<Exception>(Decimal.MaxValue, Decimal.Zero, Decimal.MaxValue);
VerifySubtract<Exception>(Decimal.MinValue, Decimal.Zero, Decimal.MinValue);
VerifySubtract<Exception>(79228162514264337593543950330m, -5, Decimal.MaxValue);
VerifySubtract<Exception>(79228162514264337593543950330m, 5, 79228162514264337593543950325m);
VerifySubtract<Exception>(-79228162514264337593543950330m, 5, Decimal.MinValue);
VerifySubtract<Exception>(-79228162514264337593543950330m, -5, -79228162514264337593543950325m);
VerifySubtract<Exception>(1234.5678m, 0.00009m, 1234.56771m);
VerifySubtract<Exception>(-1234.5678m, 0.00009m, -1234.56789m);
VerifySubtract<Exception>(0.1111111111111111111111111111m, 0.1111111111111111111111111111m, 0);
VerifySubtract<Exception>(0.2222222222222222222222222222m,
0.1111111111111111111111111111m,
0.1111111111111111111111111111m);
VerifySubtract<Exception>(1.1111111111111111111111111110m,
0.5555555555555555555555555555m,
0.5555555555555555555555555555m);
}
[Fact]
public static void TestTruncate()
{
// Decimal Decimal.Truncate(Decimal)
Assert.Equal<Decimal>(123, Decimal.Truncate((Decimal)123));
Assert.Equal<Decimal>(123, Decimal.Truncate((Decimal)123.123));
Assert.Equal<Decimal>(-123, Decimal.Truncate((Decimal)(-123.123)));
Assert.Equal<Decimal>(123, Decimal.Truncate((Decimal)123.567));
Assert.Equal<Decimal>(-123, Decimal.Truncate((Decimal)(-123.567)));
}
[Fact]
public static void TestRound()
{
// Decimal Decimal.Truncate(Decimal)
// Assert.AreEqual<Decimal>(123, Decimal.Round((Decimal)123, 2));
// Assert.AreEqual<Decimal>((Decimal)123.123, Decimal.Round((Decimal)123.123, 3));
// Assert.AreEqual<Decimal>((Decimal)(-123.1), Decimal.Round((Decimal)(-123.123), 1));
// Assert.AreEqual<Decimal>(124, Decimal.Round((Decimal)123.567, 0));
// Assert.AreEqual<Decimal>((Decimal)(-123.567), Decimal.Round((Decimal)(-123.567), 4));
}
[Fact]
public static void TestCompare()
{
// Int32 Decimal.Compare(Decimal, Decimal)
Assert.True(Decimal.Compare(Decimal.Zero, Decimal.Zero) == 0);
Assert.True(Decimal.Compare(Decimal.Zero, Decimal.One) < 0);
Assert.True(Decimal.Compare(Decimal.One, Decimal.Zero) > 0);
Assert.True(Decimal.Compare(Decimal.MinusOne, Decimal.Zero) < 0);
Assert.True(Decimal.Compare(Decimal.Zero, Decimal.MinusOne) > 0);
Assert.True(Decimal.Compare(5, 3) > 0);
Assert.True(Decimal.Compare(5, 5) == 0);
Assert.True(Decimal.Compare(5, 9) < 0);
Assert.True(Decimal.Compare(-123.123m, 123.123m) < 0);
Assert.True(Decimal.Compare(Decimal.MaxValue, Decimal.MaxValue) == 0);
Assert.True(Decimal.Compare(Decimal.MinValue, Decimal.MinValue) == 0);
Assert.True(Decimal.Compare(Decimal.MinValue, Decimal.MaxValue) < 0);
Assert.True(Decimal.Compare(Decimal.MaxValue, Decimal.MinValue) > 0);
}
[Fact]
public static void TestCompareTo()
{
// Int32 Decimal.CompareTo(Decimal)
Decimal d = 456;
Assert.True(d.CompareTo(456m) == 0);
Assert.True(d.CompareTo(457m) < 0);
Assert.True(d.CompareTo(455m) > 0);
}
[Fact]
public static void TestSystemIComparableCompareTo()
{
// Int32 Decimal.System.IComparable.CompareTo(Object)
IComparable d = (Decimal)248;
Assert.True(d.CompareTo(248m) == 0);
Assert.True(d.CompareTo(249m) < 0);
Assert.True(d.CompareTo(247m) > 0);
Assert.True(d.CompareTo(null) > 0);
Assert.Throws<ArgumentException>(() => d.CompareTo("248"));
}
[Fact]
public static void TestGetHashCode()
{
// Int32 Decimal.GetHashCode()
Assert.NotEqual(Decimal.MinusOne.GetHashCode(), Decimal.One.GetHashCode());
}
[Fact]
public static void TestToSingle()
{
// Single Decimal.ToSingle(Decimal)
Single s = 12345.12f;
Assert.Equal(s, Decimal.ToSingle((Decimal)s));
Assert.Equal(-s, Decimal.ToSingle((Decimal)(-s)));
s = 1e20f;
Assert.Equal(s, Decimal.ToSingle((Decimal)s));
Assert.Equal(-s, Decimal.ToSingle((Decimal)(-s)));
s = 1e27f;
Assert.Equal(s, Decimal.ToSingle((Decimal)s));
Assert.Equal(-s, Decimal.ToSingle((Decimal)(-s)));
}
[Fact]
public static void TestToDouble()
{
Double d = Decimal.ToDouble(new Decimal(0, 0, 1, false, 0));
// Double Decimal.ToDouble(Decimal)
Double dbl = 123456789.123456;
Assert.Equal(dbl, Decimal.ToDouble((Decimal)dbl));
Assert.Equal(-dbl, Decimal.ToDouble((Decimal)(-dbl)));
dbl = 1e20;
Assert.Equal(dbl, Decimal.ToDouble((Decimal)dbl));
Assert.Equal(-dbl, Decimal.ToDouble((Decimal)(-dbl)));
dbl = 1e27;
Assert.Equal(dbl, Decimal.ToDouble((Decimal)dbl));
Assert.Equal(-dbl, Decimal.ToDouble((Decimal)(-dbl)));
dbl = Int64.MaxValue;
// Need to pass in the Int64.MaxValue to ToDouble and not dbl because the conversion to double is a little lossy and we want precision
Assert.Equal(dbl, Decimal.ToDouble((Decimal)Int64.MaxValue));
Assert.Equal(-dbl, Decimal.ToDouble((Decimal)(-Int64.MaxValue)));
}
[Fact]
public static void TestToInt16()
{
// Int16 Decimal.ToInt16(Decimal)
Assert.Equal(Int16.MaxValue, Decimal.ToInt16((Decimal)Int16.MaxValue));
Assert.Equal(Int16.MinValue, Decimal.ToInt16((Decimal)Int16.MinValue));
}
[Fact]
public static void TestToInt32()
{
// Int32 Decimal.ToInt32(Decimal)
Assert.Equal(Int32.MaxValue, Decimal.ToInt32((Decimal)Int32.MaxValue));
Assert.Equal(Int32.MinValue, Decimal.ToInt32((Decimal)Int32.MinValue));
}
[Fact]
public static void TestGetBits()
{
// Int32[] Decimal.GetBits(Decimal)
}
[Fact]
public static void TestToInt64()
{
// Int64 Decimal.ToInt64(Decimal)
Assert.Equal(Int64.MaxValue, Decimal.ToInt64((Decimal)Int64.MaxValue));
Assert.Equal(Int64.MinValue, Decimal.ToInt64((Decimal)Int64.MinValue));
}
[Fact]
public static void TestToSByte()
{
// SByte Decimal.ToSByte(Decimal)
Assert.Equal(SByte.MaxValue, Decimal.ToSByte((Decimal)SByte.MaxValue));
Assert.Equal(SByte.MinValue, Decimal.ToSByte((Decimal)SByte.MinValue));
}
[Fact]
public static void TestToUInt16()
{
// UInt16 Decimal.ToUInt16(Decimal)
Assert.Equal(UInt16.MaxValue, Decimal.ToUInt16((Decimal)UInt16.MaxValue));
Assert.Equal(UInt16.MinValue, Decimal.ToUInt16((Decimal)UInt16.MinValue));
}
[Fact]
public static void TestToUInt32()
{
// UInt32 Decimal.ToUInt32(Decimal)
Assert.Equal(UInt32.MaxValue, Decimal.ToUInt32((Decimal)UInt32.MaxValue));
Assert.Equal(UInt32.MinValue, Decimal.ToUInt32((Decimal)UInt32.MinValue));
}
[Fact]
public static void TestToUInt64()
{
// UInt64 Decimal.ToUInt64(Decimal)
Assert.Equal(UInt64.MaxValue, Decimal.ToUInt64((Decimal)UInt64.MaxValue));
Assert.Equal(UInt64.MinValue, Decimal.ToUInt64((Decimal)UInt64.MinValue));
}
[Fact]
public static void TestToString()
{
// String Decimal.ToString()
Decimal d1 = 6310.23m;
Assert.Equal("6310.23", d1.ToString());
Decimal d2 = -8249.000003m;
Assert.Equal("-8249.000003", d2.ToString());
Assert.Equal("79228162514264337593543950335", Decimal.MaxValue.ToString());
Assert.Equal("-79228162514264337593543950335", Decimal.MinValue.ToString());
}
[Fact]
public static void Testctor()
{
Decimal d;
// Void Decimal..ctor(Double)
d = new Decimal((Double)123456789.123456);
Assert.Equal<Decimal>(d, (Decimal)123456789.123456);
// Void Decimal..ctor(Int32)
d = new Decimal((Int32)Int32.MaxValue);
Assert.Equal<Decimal>(d, Int32.MaxValue);
// Void Decimal..ctor(Int64)
d = new Decimal((Int64)Int64.MaxValue);
Assert.Equal<Decimal>(d, Int64.MaxValue);
// Void Decimal..ctor(Single)
d = new Decimal((Single)123.123);
Assert.Equal<Decimal>(d, (Decimal)123.123);
// Void Decimal..ctor(UInt32)
d = new Decimal((UInt32)UInt32.MaxValue);
Assert.Equal<Decimal>(d, UInt32.MaxValue);
// Void Decimal..ctor(UInt64)
d = new Decimal((UInt64)UInt64.MaxValue);
Assert.Equal<Decimal>(d, UInt64.MaxValue);
// Void Decimal..ctor(Int32, Int32, Int32, Boolean, Byte)
d = new Decimal(1, 1, 1, false, 0);
Decimal d2 = 3;
d2 += UInt32.MaxValue;
d2 += UInt64.MaxValue;
Assert.Equal(d, d2);
// Void Decimal..ctor(Int32[])
d = new Decimal(new Int32[] { 1, 1, 1, 0 });
Assert.Equal(d, d2);
}
[Fact]
public static void TestNumberBufferLimit()
{
Decimal dE = 1234567890123456789012345.6785m;
string s1 = "1234567890123456789012345.678456";
Decimal d1 = Decimal.Parse(s1);
Assert.Equal(d1, dE);
return;
}
}
| |
namespace java.text
{
[global::MonoJavaBridge.JavaClass()]
public partial class DateFormatSymbols : java.lang.Object, java.io.Serializable, java.lang.Cloneable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected DateFormatSymbols(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override bool equals(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.text.DateFormatSymbols.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.text.DateFormatSymbols._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override int hashCode()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.text.DateFormatSymbols.staticClass, "hashCode", "()I", ref global::java.text.DateFormatSymbols._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual global::java.lang.Object clone()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.text.DateFormatSymbols.staticClass, "clone", "()Ljava/lang/Object;", ref global::java.text.DateFormatSymbols._m2) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m3;
public static global::java.text.DateFormatSymbols getInstance(java.util.Locale arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.text.DateFormatSymbols._m3.native == global::System.IntPtr.Zero)
global::java.text.DateFormatSymbols._m3 = @__env.GetStaticMethodIDNoThrow(global::java.text.DateFormatSymbols.staticClass, "getInstance", "(Ljava/util/Locale;)Ljava/text/DateFormatSymbols;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.DateFormatSymbols.staticClass, global::java.text.DateFormatSymbols._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.text.DateFormatSymbols;
}
public static global::java.text.DateFormatSymbols Instance
{
get
{
return getInstance();
}
}
private static global::MonoJavaBridge.MethodId _m4;
public static global::java.text.DateFormatSymbols getInstance()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.text.DateFormatSymbols._m4.native == global::System.IntPtr.Zero)
global::java.text.DateFormatSymbols._m4 = @__env.GetStaticMethodIDNoThrow(global::java.text.DateFormatSymbols.staticClass, "getInstance", "()Ljava/text/DateFormatSymbols;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.text.DateFormatSymbols.staticClass, global::java.text.DateFormatSymbols._m4)) as java.text.DateFormatSymbols;
}
public static global::java.util.Locale[] AvailableLocales
{
get
{
return getAvailableLocales();
}
}
private static global::MonoJavaBridge.MethodId _m5;
public static global::java.util.Locale[] getAvailableLocales()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.text.DateFormatSymbols._m5.native == global::System.IntPtr.Zero)
global::java.text.DateFormatSymbols._m5 = @__env.GetStaticMethodIDNoThrow(global::java.text.DateFormatSymbols.staticClass, "getAvailableLocales", "()[Ljava/util/Locale;");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.util.Locale>(@__env.CallStaticObjectMethod(java.text.DateFormatSymbols.staticClass, global::java.text.DateFormatSymbols._m5)) as java.util.Locale[];
}
public new global::java.lang.String[] Eras
{
get
{
return getEras();
}
set
{
setEras(value);
}
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::java.lang.String[] getEras()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::java.text.DateFormatSymbols.staticClass, "getEras", "()[Ljava/lang/String;", ref global::java.text.DateFormatSymbols._m6) as java.lang.String[];
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void setEras(java.lang.String[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.DateFormatSymbols.staticClass, "setEras", "([Ljava/lang/String;)V", ref global::java.text.DateFormatSymbols._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.lang.String[] Months
{
get
{
return getMonths();
}
set
{
setMonths(value);
}
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual global::java.lang.String[] getMonths()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::java.text.DateFormatSymbols.staticClass, "getMonths", "()[Ljava/lang/String;", ref global::java.text.DateFormatSymbols._m8) as java.lang.String[];
}
public new global::java.lang.String[] ShortMonths
{
get
{
return getShortMonths();
}
set
{
setShortMonths(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual global::java.lang.String[] getShortMonths()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::java.text.DateFormatSymbols.staticClass, "getShortMonths", "()[Ljava/lang/String;", ref global::java.text.DateFormatSymbols._m9) as java.lang.String[];
}
public new global::java.lang.String[] Weekdays
{
get
{
return getWeekdays();
}
set
{
setWeekdays(value);
}
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual global::java.lang.String[] getWeekdays()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::java.text.DateFormatSymbols.staticClass, "getWeekdays", "()[Ljava/lang/String;", ref global::java.text.DateFormatSymbols._m10) as java.lang.String[];
}
public new global::java.lang.String[] ShortWeekdays
{
get
{
return getShortWeekdays();
}
set
{
setShortWeekdays(value);
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual global::java.lang.String[] getShortWeekdays()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::java.text.DateFormatSymbols.staticClass, "getShortWeekdays", "()[Ljava/lang/String;", ref global::java.text.DateFormatSymbols._m11) as java.lang.String[];
}
public new global::java.lang.String[] AmPmStrings
{
get
{
return getAmPmStrings();
}
set
{
setAmPmStrings(value);
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual global::java.lang.String[] getAmPmStrings()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::java.text.DateFormatSymbols.staticClass, "getAmPmStrings", "()[Ljava/lang/String;", ref global::java.text.DateFormatSymbols._m12) as java.lang.String[];
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void setMonths(java.lang.String[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.DateFormatSymbols.staticClass, "setMonths", "([Ljava/lang/String;)V", ref global::java.text.DateFormatSymbols._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void setShortMonths(java.lang.String[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.DateFormatSymbols.staticClass, "setShortMonths", "([Ljava/lang/String;)V", ref global::java.text.DateFormatSymbols._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void setWeekdays(java.lang.String[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.DateFormatSymbols.staticClass, "setWeekdays", "([Ljava/lang/String;)V", ref global::java.text.DateFormatSymbols._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void setShortWeekdays(java.lang.String[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.DateFormatSymbols.staticClass, "setShortWeekdays", "([Ljava/lang/String;)V", ref global::java.text.DateFormatSymbols._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setAmPmStrings(java.lang.String[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.DateFormatSymbols.staticClass, "setAmPmStrings", "([Ljava/lang/String;)V", ref global::java.text.DateFormatSymbols._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.lang.String[][] ZoneStrings
{
get
{
return getZoneStrings();
}
set
{
setZoneStrings(value);
}
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual global::java.lang.String[][] getZoneStrings()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String[]>(this, global::java.text.DateFormatSymbols.staticClass, "getZoneStrings", "()[[Ljava/lang/String;", ref global::java.text.DateFormatSymbols._m18) as java.lang.String[][];
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual void setZoneStrings(java.lang.String[][] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.DateFormatSymbols.staticClass, "setZoneStrings", "([[Ljava/lang/String;)V", ref global::java.text.DateFormatSymbols._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.lang.String LocalPatternChars
{
get
{
return getLocalPatternChars();
}
set
{
setLocalPatternChars(value);
}
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual global::java.lang.String getLocalPatternChars()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.text.DateFormatSymbols.staticClass, "getLocalPatternChars", "()Ljava/lang/String;", ref global::java.text.DateFormatSymbols._m20) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual void setLocalPatternChars(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.text.DateFormatSymbols.staticClass, "setLocalPatternChars", "(Ljava/lang/String;)V", ref global::java.text.DateFormatSymbols._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m22;
public DateFormatSymbols() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.text.DateFormatSymbols._m22.native == global::System.IntPtr.Zero)
global::java.text.DateFormatSymbols._m22 = @__env.GetMethodIDNoThrow(global::java.text.DateFormatSymbols.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.text.DateFormatSymbols.staticClass, global::java.text.DateFormatSymbols._m22);
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m23;
public DateFormatSymbols(java.util.Locale arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.text.DateFormatSymbols._m23.native == global::System.IntPtr.Zero)
global::java.text.DateFormatSymbols._m23 = @__env.GetMethodIDNoThrow(global::java.text.DateFormatSymbols.staticClass, "<init>", "(Ljava/util/Locale;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.text.DateFormatSymbols.staticClass, global::java.text.DateFormatSymbols._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static DateFormatSymbols()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.text.DateFormatSymbols.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/text/DateFormatSymbols"));
}
}
}
| |
using Catel;
namespace Metaseed.MetaShell.Module
{
using System;
using System.Globalization;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.Modularity;
/// <summary>
/// Provides tracking of modules for the quickstart.
/// </summary>
/// <remarks>
/// This class is for demonstration purposes for the quickstart and not expected to be used in a real world application.
/// This class exports the interface for modules and the concrete type for the shell.
/// </remarks>
public class ModuleTracker : IModuleTracker
{
#region Fields
/// <summary>
/// The logger.
/// </summary>
private readonly ILoggerFacade logger;
/// <summary>
/// The module a tracking state.
/// </summary>
private readonly ModuleTrackingState moduleATrackingState;
/// <summary>
/// The module b tracking state.
/// </summary>
private readonly ModuleTrackingState moduleBTrackingState;
/// <summary>
/// The module c tracking state.
/// </summary>
private readonly ModuleTrackingState moduleCTrackingState;
/// <summary>
/// The module d tracking state.
/// </summary>
private readonly ModuleTrackingState moduleDTrackingState;
/// <summary>
/// The module e tracking state.
/// </summary>
private readonly ModuleTrackingState moduleETrackingState;
/// <summary>
/// The module f tracking state.
/// </summary>
private readonly ModuleTrackingState moduleFTrackingState;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ModuleTracker"/> class.
/// Initializes a new instance of the <see cref="ModuleTracker"/> class.
/// </summary>
/// <param name="logger">
/// The logger.
/// </param>
public ModuleTracker(ILoggerFacade logger)
{
if (logger == null)
{
throw new ArgumentNullException("logger");
}
this.logger = logger;
// These states are defined specifically for the desktop version of the quickstart.
moduleATrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleA, ExpectedDiscoveryMethod = DiscoveryMethod.ApplicationReference, ExpectedInitializationMode = InitializationMode.WhenAvailable, ExpectedDownloadTiming = DownloadTiming.WithApplication, ConfiguredDependencies = WellKnownModuleNames.ModuleD, };
moduleBTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleB, ExpectedDiscoveryMethod = DiscoveryMethod.DirectorySweep, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, };
moduleCTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleC, ExpectedDiscoveryMethod = DiscoveryMethod.ApplicationReference, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.WithApplication, };
moduleDTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleD, ExpectedDiscoveryMethod = DiscoveryMethod.DirectorySweep, ExpectedInitializationMode = InitializationMode.WhenAvailable, ExpectedDownloadTiming = DownloadTiming.InBackground, };
moduleETrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleE, ExpectedDiscoveryMethod = DiscoveryMethod.ConfigurationManifest, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, };
moduleFTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleF, ExpectedDiscoveryMethod = DiscoveryMethod.ConfigurationManifest, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, ConfiguredDependencies = WellKnownModuleNames.ModuleE, };
}
#endregion
#region Properties
/// <summary>
/// Gets the tracking state of module A.
/// </summary>
/// <value>A ModuleTrackingState.</value>
/// <remarks>
/// This is exposed as a specific property for data-binding purposes in the quickstart UI.
/// </remarks>
public ModuleTrackingState ModuleATrackingState
{
get { return moduleATrackingState; }
}
/// <summary>
/// Gets the tracking state of module B.
/// </summary>
/// <value>A ModuleTrackingState.</value>
/// <remarks>
/// This is exposed as a specific property for data-binding purposes in the quickstart UI.
/// </remarks>
public ModuleTrackingState ModuleBTrackingState
{
get { return moduleBTrackingState; }
}
/// <summary>
/// Gets the tracking state of module C.
/// </summary>
/// <value>A ModuleTrackingState.</value>
/// <remarks>
/// This is exposed as a specific property for data-binding purposes in the quickstart UI.
/// </remarks>
public ModuleTrackingState ModuleCTrackingState
{
get { return moduleCTrackingState; }
}
/// <summary>
/// Gets the tracking state of module D.
/// </summary>
/// <value>A ModuleTrackingState.</value>
/// <remarks>
/// This is exposed as a specific property for data-binding purposes in the quickstart UI.
/// </remarks>
public ModuleTrackingState ModuleDTrackingState
{
get { return moduleDTrackingState; }
}
/// <summary>
/// Gets the tracking state of module E.
/// </summary>
/// <value>A ModuleTrackingState.</value>
/// <remarks>
/// This is exposed as a specific property for data-binding purposes in the quickstart UI.
/// </remarks>
public ModuleTrackingState ModuleETrackingState
{
get { return moduleETrackingState; }
}
/// <summary>
/// Gets the tracking state of module F.
/// </summary>
/// <value>A ModuleTrackingState.</value>
/// <remarks>
/// This is exposed as a specific property for data-binding purposes in the quickstart UI.
/// </remarks>
public ModuleTrackingState ModuleFTrackingState
{
get { return moduleFTrackingState; }
}
#endregion
#region IModuleTracker Members
/// <summary>
/// Records the module is loading.
/// </summary>
/// <param name="moduleName">
/// The <see cref="WellKnownModuleNames">well-known name</see> of the module.
/// </param>
/// <param name="bytesReceived">
/// The number of bytes downloaded.
/// </param>
/// <param name="totalBytesToReceive">
/// The total number of bytes received.
/// </param>
public void RecordModuleDownloading(string moduleName, long bytesReceived, long totalBytesToReceive)
{
ModuleTrackingState moduleTrackingState = GetModuleTrackingState(moduleName);
if (moduleTrackingState != null)
{
moduleTrackingState.BytesReceived = bytesReceived;
moduleTrackingState.TotalBytesToReceive = totalBytesToReceive;
if (bytesReceived < totalBytesToReceive)
{
moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Downloading;
}
else
{
moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Downloaded;
}
}
logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ModuleIsLoadingProgress, moduleName, bytesReceived, totalBytesToReceive), Category.Debug, Priority.Low);
}
/// <summary>
/// Records the module has been constructed.
/// </summary>
/// <param name="moduleName">
/// The <see cref="WellKnownModuleNames">well-known name</see> of the module.
/// </param>
public void RecordModuleConstructed(string moduleName)
{
ModuleTrackingState moduleTrackingState = GetModuleTrackingState(moduleName);
if (moduleTrackingState != null)
{
moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Constructed;
}
logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ModuleConstructed, moduleName), Category.Debug, Priority.Low);
}
/// <summary>
/// Records the module has been initialized.
/// </summary>
/// <param name="moduleName">
/// The <see cref="WellKnownModuleNames">well-known name</see> of the module.
/// </param>
public void RecordModuleInitialized(string moduleName)
{
ModuleTrackingState moduleTrackingState = GetModuleTrackingState(moduleName);
if (moduleTrackingState != null)
{
moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Initialized;
}
logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ModuleIsInitialized, moduleName), Category.Debug, Priority.Low);
}
/// <summary>
/// Records the module is loaded.
/// </summary>
/// <param name="moduleName">
/// The <see cref="WellKnownModuleNames">well-known name</see> of the module.
/// </param>
public void RecordModuleLoaded(string moduleName)
{
logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ModuleLoaded, moduleName), Category.Debug, Priority.Low);
}
#endregion
// A helper to make updating specific property instances by name easier.
#region Methods
/// <summary>
/// The get module tracking state.
/// </summary>
/// <param name="moduleName">
/// The module name.
/// </param>
/// <returns>
/// </returns>
private ModuleTrackingState GetModuleTrackingState(string moduleName)
{
switch (moduleName)
{
case WellKnownModuleNames.ModuleA:
return ModuleATrackingState;
case WellKnownModuleNames.ModuleB:
return ModuleBTrackingState;
case WellKnownModuleNames.ModuleC:
return ModuleCTrackingState;
case WellKnownModuleNames.ModuleD:
return ModuleDTrackingState;
case WellKnownModuleNames.ModuleE:
return ModuleETrackingState;
case WellKnownModuleNames.ModuleF:
return ModuleFTrackingState;
default:
return null;
}
}
#endregion
}
}
| |
namespace SexyFishHorse.CitiesSkylines.Ragnarok.Configuration
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using ColossalFramework.UI;
using Infrastructure.UI;
using Infrastructure.UI.Configuration;
using Infrastructure.UI.Extensions;
using Logger;
using Logging;
using SexyFishHorse.CitiesSkylines.Ragnarok.Services;
public class OptionsPanelManager : IOptionsPanelManager
{
private const byte MaximumIntensityValue = byte.MaxValue;
private const byte MinimumIntensityValue = byte.MinValue;
private static readonly string[] AutoEvacuateValues =
{
"Disabled",
"Enabled - manual release",
"Enabled - auto release"
};
private readonly ILogger logger;
private readonly IDictionary<string, UISlider> maxIntensitySliders = new Dictionary<string, UISlider>();
public OptionsPanelManager(ILogger logger)
{
this.logger = logger;
logger.Info("OptionsPanelManager created");
}
public void ConfigureOptionsPanel(IStronglyTypedUIHelper uiHelper)
{
try
{
ConfigureGeneralGroup(uiHelper);
ConfigureDisableDisastersGroup(uiHelper);
ConfigureMaxIntensityGroup(uiHelper);
ConfigureAutoEvacuateGroup(uiHelper);
ConfigureProbabilityGroup(uiHelper);
var debuggingGroup = uiHelper.AddGroup("Debugging");
debuggingGroup.AddCheckBox(
"Enable logging",
ModConfig.Instance.GetSetting<bool>(SettingKeys.EnableLogging),
isChecked =>
{
ModConfig.Instance.SaveSetting(SettingKeys.EnableLogging, isChecked);
RagnarokLogger.Enabled = isChecked;
});
}
catch (Exception ex)
{
logger.LogException(ex);
throw;
}
}
private void AddAutoEvacuateBehaviourDropDown(IStronglyTypedUIHelper autoEvacuateGroup, string disasterName, string settingKey)
{
var dropDown = autoEvacuateGroup.AddDropDown(
disasterName,
AutoEvacuateValues,
ModConfig.Instance.GetSetting<int>(settingKey),
sel => SaveSetting(settingKey, sel));
dropDown.width = (int)Math.Round(dropDown.width * 1.4f);
}
private void AddEnabledDisasterCheckbox(IStronglyTypedUIHelper uiGroup, string label, string settingKey)
{
uiGroup.AddCheckBox(
label,
ModConfig.Instance.GetSetting<bool>(settingKey),
isChecked => SaveSetting(settingKey, isChecked));
}
private void AddMaxIntensitySlider(IStronglyTypedUIHelper group, string disasterName, string impactSettingKey)
{
var setting = ModConfig.Instance.GetSetting<byte>(impactSettingKey);
var slider =
group.AddSlider(
disasterName,
MinimumIntensityValue,
MaximumIntensityValue,
1,
setting,
val =>
{
ModConfig.Instance.SaveSetting(impactSettingKey, (byte)val);
UpdateMaxIntensityLabel(impactSettingKey, disasterName, val);
});
slider.width = (int)Math.Round(slider.width * 1.4);
var label = slider.GetLabel();
label.width = (int)Math.Round(label.width * 1.4);
if (maxIntensitySliders.ContainsKey(impactSettingKey))
{
maxIntensitySliders[impactSettingKey] = slider;
}
else
{
maxIntensitySliders.Add(impactSettingKey, slider);
}
UpdateMaxIntensityLabel(impactSettingKey, disasterName, setting);
}
private static void AddProbabilitySlider(IStronglyTypedUIHelper disasterGroup, string settingKey, DisasterInfo disasterInfo)
{
var probability = disasterInfo.m_finalRandomProbability;
if (ModConfig.Instance.HasSetting(settingKey))
{
probability = ModConfig.Instance.GetSetting<int>(settingKey);
}
var labelText = disasterInfo.name;
var slider = disasterGroup.AddSlider(
labelText,
0,
1000,
1,
probability,
newProbability =>
{
disasterInfo.m_finalRandomProbability = (int)newProbability;
ModConfig.Instance.SaveSetting(settingKey, (int)newProbability);
});
slider.width = (int)Math.Round(slider.width * 1.5f);
var label = slider.GetLabel();
label.width = (int)Math.Round(label.width * 1.5f);
}
private void ConfigureAutoEvacuateGroup(IStronglyTypedUIHelper uiHelper)
{
var group = uiHelper.AddGroup("Auto evacuate");
foreach (var disaster in SettingKeys.DisasterSettingKeys)
{
AddAutoEvacuateBehaviourDropDown(group, disaster.Key, disaster.Value.AutoEvacuate);
}
}
private void ConfigureDisableDisastersGroup(IStronglyTypedUIHelper uiHelper)
{
var group = uiHelper.AddGroup("Disable disasters");
group.AddCheckBox(
"Fires not caused by disasters",
ModConfig.Instance.GetSetting<bool>(SettingKeys.DisableNonDisasterFires),
OnDisableNonDisasterFiresChanged);
group.AddSpace(10);
foreach (var disableDisaster in SettingKeys.DisasterSettingKeys)
{
AddEnabledDisasterCheckbox(group, disableDisaster.Key, disableDisaster.Value.Disable);
}
group.AddSpace(10);
AddEnabledDisasterCheckbox(group, "Disable scenario disasters (really?)", SettingKeys.DisableScenarioDisasters);
}
private void ConfigureGeneralGroup(IStronglyTypedUIHelper uiHelper)
{
var generalGroup = uiHelper.AddGroup("General");
generalGroup.AddCheckBox(
"Auto focus on disaster",
ModConfig.Instance.GetSetting<bool>(SettingKeys.DisableAutofocusDisaster),
OnAutoFocusDisasterChanged);
generalGroup.AddCheckBox(
"Pause on disaster start",
ModConfig.Instance.GetSetting<bool>(SettingKeys.PauseOnDisasterStart),
isChecked => SaveSetting(SettingKeys.PauseOnDisasterStart, isChecked));
}
private void ConfigureMaxIntensityGroup(IStronglyTypedUIHelper uiHelper)
{
var group = uiHelper.AddGroup("Disable disasters over a given intensity");
group.AddLabel("Use the sliders to set the max intensity for a given disaster.\nSet to zero (0) to allow all intensities.");
foreach (var disaster in SettingKeys.DisasterSettingKeys)
{
AddMaxIntensitySlider(group, disaster.Key, disaster.Value.MaxIntensity);
}
}
private void ConfigureProbabilityGroup(IStronglyTypedUIHelper uiHelper)
{
var probabilityGroup = uiHelper.AddGroup("Disaster probabilities");
if (!GenericDisasterServices.GetDisasterInfos().Any())
{
probabilityGroup.AddLabel("You need to be in an active game or scenario to change these settings.");
return;
}
probabilityGroup.AddLabel(
"The sliders below indicate the risk of a certain type of disaster spawning.\n\n" +
"These are in relation to each other meaning that if two sliders are set equally\n" +
"then they have an equal chance of occurring.");
var disasterInfos = GenericDisasterServices.GetDisasterInfos().ToList();
foreach (var disasterInfo in disasterInfos)
{
var settingKey = string.Format("{0}Probability", disasterInfo.name.Replace(" ", string.Empty));
AddProbabilitySlider(probabilityGroup, settingKey, disasterInfo);
}
}
private void OnAutoFocusDisasterChanged(bool isChecked)
{
SaveSetting(SettingKeys.DisableAutofocusDisaster, isChecked);
GenericDisasterServices.UpdateAutoFollowDisaster(logger);
}
private void OnDisableNonDisasterFiresChanged(bool isChecked)
{
SaveSetting(SettingKeys.DisableNonDisasterFires, isChecked);
if (BuildingManager.exists)
{
BuildingManager.instance.m_firesDisabled = isChecked;
}
}
private void SaveSetting(string settingKey, object value)
{
logger.Info("Saving setting {0} with value {1}", settingKey, value);
ModConfig.Instance.SaveSetting(settingKey, value);
}
private void UpdateMaxIntensityLabel(string impactSettingKey, string disasterName, float value)
{
string intensity;
if (value < 1)
{
intensity = "Allow all";
}
else
{
intensity = (value / 10.0f).ToString("f1", CultureInfo.CurrentUICulture);
}
maxIntensitySliders[impactSettingKey].SetLabelText("{0} ({1})", disasterName, intensity);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Utilities;
using Signum.Engine.Maps;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Threading;
namespace Signum.Engine.Disconnected
{
public static class DisconnectedTools
{
public static void DropDatabase(DatabaseName databaseName)
{
Executor.ExecuteNonQuery(
@"ALTER DATABASE {0} SET single_user WITH ROLLBACK IMMEDIATE
DROP DATABASE {0}".FormatWith(databaseName));
}
public static void DropIfExists(DatabaseName databaseName)
{
string dropDatabase =
@"IF EXISTS(SELECT name FROM sys.databases WHERE name = '{0}')
BEGIN
ALTER DATABASE {0} SET single_user WITH ROLLBACK IMMEDIATE
DROP DATABASE {0}
END".FormatWith(databaseName);
Executor.ExecuteNonQuery(dropDatabase);
}
public static void CreateDatabase(DatabaseName databaseName, string databaseFile, string databaseLogFile)
{
string script = @"CREATE DATABASE {0} ON PRIMARY
( NAME = N'{0}_Data', FILENAME = N'{1}' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )
LOG ON
( NAME = N'{0}_Log', FILENAME = N'{2}' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB )".FormatWith(databaseName, databaseFile, databaseLogFile);
Executor.ExecuteNonQuery(script);
}
public static void BackupDatabase(DatabaseName databaseName, string backupFile)
{
Executor.ExecuteNonQuery(@"BACKUP DATABASE {0} TO DISK = '{1}'WITH FORMAT".FormatWith(databaseName, backupFile));
}
public static void RestoreDatabase(DatabaseName databaseName, string backupFile, string databaseFile, string databaseLogFile, bool replace = false)
{
DataTable dataTable = Executor.ExecuteDataTable("RESTORE FILELISTONLY FROM DISK ='{0}'".FormatWith(backupFile));
string logicalDatabaseFile = (string)dataTable.Rows.Cast<DataRow>().Single(a => (string)a["Type"] == "D")["LogicalName"];
string logicalDatabaseLogFile = (string)dataTable.Rows.Cast<DataRow>().Single(a => (string)a["Type"] == "L")["LogicalName"];
new SqlPreCommandSimple(
@"RESTORE DATABASE {0}
from DISK = '{1}'
WITH
MOVE '{2}' TO '{3}',
MOVE '{4}' TO '{5}'{6}".FormatWith(databaseName, backupFile,
logicalDatabaseFile, databaseFile,
logicalDatabaseLogFile, databaseLogFile, replace ? ",\r\nREPLACE" : "")).ExecuteNonQuery();
}
public static void DisableForeignKeys(ITable table)
{
Executor.ExecuteNonQuery("ALTER TABLE {0} NOCHECK CONSTRAINT all".FormatWith(table.Name));
}
public static void EnableForeignKeys(ITable table)
{
Executor.ExecuteNonQuery("ALTER TABLE {0} WITH CHECK CHECK CONSTRAINT all".FormatWith(table.Name));
}
public static void DeleteTable(ObjectName tableName)
{
Executor.ExecuteNonQuery("DELETE FROM {0}".FormatWith(tableName));
}
// TSQL Seed madness pseudo-code.
//
//int seed = 1;
//
//IDENT_CURRENT() return seed;
//
//DBCC CHECKIDENT() return empty()? null: seed;
//
//DBCC CHECKIDENT(newSeed) seed = newSeed;
//
//GetId()return empty() seed: seed++;
public static long? MaxIdInRange(ITable table, long seedMin, long seedMax)
{
Type type = table.PrimaryKey.Type;
var pb = Connector.Current.ParameterBuilder;
object? obj = Executor.ExecuteScalar("SELECT MAX(Id) FROM {0} WHERE @min <= Id AND Id < @max".FormatWith(table.Name), new List<DbParameter>
{
pb.CreateParameter("@min", seedMin, type),
pb.CreateParameter("@max", seedMax, type)
});
if (obj == null)
return null;
return Convert.ToInt64(obj);
}
public static SeedInfo GetSeedInfo(ITable table)
{
using (var tr = new Transaction())
{
string? message = null;
((SqlConnection)Transaction.CurrentConnection!).InfoMessage += (object sender, SqlInfoMessageEventArgs e) => { message = e.Message; };
Executor.ExecuteNonQuery("DBCC CHECKIDENT ('{0}', NORESEED)".FormatWith(table.Name));
if (message == null)
throw new InvalidOperationException("DBCC CHECKIDENT didn't write a message");
Match m = IdentityMessageRegex.Match(message);
if (!m.Success)
throw new InvalidOperationException("DBCC CHECKIDENT messege has invalid format");
SeedInfo result = new SeedInfo
{
Identity = SeedInfo.Parse(m.Groups["identity"].Value),
Column = SeedInfo.Parse(m.Groups["column"].Value),
};
return tr.Commit(result);
}
}
public static Regex IdentityMessageRegex = new Regex(@".*'(?<identity>(\d*|NULL))'.*'(?<column>(\d*|NULL))'");
static bool IsEmpty(ITable table)
{
return GetSeedInfo(table).Identity == null;
}
public static long GetNextId(ITable table)
{
var info = GetSeedInfo(table);
if (info.Identity.HasValue)
return info.Identity.Value + 1;
return (long)(decimal)Executor.ExecuteScalar("SELECT IDENT_CURRENT ('{0}') ".FormatWith(table.Name))!;
}
public static void SetNextId(ITable table, long nextId)
{
SetNextIdSync(table, nextId).ExecuteNonQuery();
}
public static SqlPreCommandSimple SetNextIdSync(ITable table, long nextId)
{
var pb = Connector.Current.ParameterBuilder;
return new SqlPreCommandSimple("DBCC CHECKIDENT ('{0}', RESEED, @seed)".FormatWith(table.Name), new List<DbParameter>
{
pb.CreateParameter("@seed", nextId, table.PrimaryKey.Type)
});
}
public static IDisposable MeasureTime(this CancellationToken token, Action<int> action)
{
token.ThrowIfCancellationRequested();
var t = PerfCounter.Ticks;
return new Disposable(() =>
{
var elapsed = (PerfCounter.Ticks - t) / PerfCounter.FrequencyMilliseconds;
action((int)elapsed);
});
}
public static string CleanMachineName(string machineName)
{
return Regex.Replace(machineName, "[^A-Z0-9_]", "_");
}
}
public struct SeedInfo
{
public int? Identity;
public int? Column;
internal static int? Parse(string num)
{
if (num == "NULL")
return null;
return int.Parse(num);
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Communications.Services
{
/// <summary>
/// A temp class to handle login response.
/// Should make use of UserProfileManager where possible.
/// </summary>
public class LoginResponse
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Hashtable loginFlagsHash;
private Hashtable globalTexturesHash;
private Hashtable loginError;
private Hashtable uiConfigHash;
private ArrayList loginFlags;
private ArrayList globalTextures;
private ArrayList eventCategories;
private ArrayList uiConfig;
private ArrayList classifiedCategories;
private ArrayList inventoryRoot;
private ArrayList initialOutfit;
private ArrayList agentInventory;
private ArrayList inventoryLibraryOwner;
private ArrayList inventoryLibRoot;
private ArrayList inventoryLibrary;
private ArrayList activeGestures;
private UserInfo userProfile;
private UUID agentID;
private UUID sessionID;
private UUID secureSessionID;
// Login Flags
private string dst;
private string stipendSinceLogin;
private string gendered;
private string everLoggedIn;
private string login;
private uint simPort;
private uint simHttpPort;
private string simAddress;
private string agentAccess;
private Int32 circuitCode;
private uint regionX;
private uint regionY;
// Login
private string firstname;
private string lastname;
// Global Textures
private string sunTexture;
private string cloudTexture;
private string moonTexture;
// Error Flags
private string errorReason;
private string errorMessage;
// Response
private XmlRpcResponse xmlRpcResponse;
// private XmlRpcResponse defaultXmlRpcResponse;
private string welcomeMessage;
private string startLocation;
private string allowFirstLife;
private string home;
private string seedCapability;
private string lookAt;
private string mapServerURI;
private BuddyList m_buddyList = null;
public LoginResponse()
{
loginFlags = new ArrayList();
globalTextures = new ArrayList();
eventCategories = new ArrayList();
uiConfig = new ArrayList();
classifiedCategories = new ArrayList();
loginError = new Hashtable();
uiConfigHash = new Hashtable();
// defaultXmlRpcResponse = new XmlRpcResponse();
userProfile = new UserInfo();
inventoryRoot = new ArrayList();
initialOutfit = new ArrayList();
agentInventory = new ArrayList();
inventoryLibrary = new ArrayList();
inventoryLibraryOwner = new ArrayList();
activeGestures = new ArrayList();
xmlRpcResponse = new XmlRpcResponse();
// defaultXmlRpcResponse = new XmlRpcResponse();
SetDefaultValues();
}
private void SetDefaultValues()
{
DST = TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now) ? "Y" : "N";
StipendSinceLogin = "N";
Gendered = "Y";
EverLoggedIn = "Y";
login = "false";
firstname = "Test";
lastname = "User";
agentAccess = "A";
startLocation = "last";
allowFirstLife = "Y";
SunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271";
CloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621";
MoonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621";
ErrorMessage = "The requested region is not available and no alternative login region could be found. (Grid down?)";
ErrorReason = "key";
welcomeMessage = "Welcome to InWorldz!";
seedCapability = String.Empty;
home = "{'region_handle':[r" + (1000*Constants.RegionSize).ToString() + ",r" + (1000*Constants.RegionSize).ToString() + "], 'position':[r" +
userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" +
userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" +
userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}";
lookAt = "[r0.99949799999999999756,r0.03166859999999999814,r0]";
RegionX = (uint) 255232;
RegionY = (uint) 254976;
// Classifieds;
AddClassifiedCategory((Int32) 1, "Shopping");
AddClassifiedCategory((Int32) 2, "Land Rental");
AddClassifiedCategory((Int32) 3, "Property Rental");
AddClassifiedCategory((Int32) 4, "Special Attraction");
AddClassifiedCategory((Int32) 5, "New Products");
AddClassifiedCategory((Int32) 6, "Employment");
AddClassifiedCategory((Int32) 7, "Wanted");
AddClassifiedCategory((Int32) 8, "Service");
AddClassifiedCategory((Int32) 9, "Personal");
SessionID = UUID.Random();
SecureSessionID = UUID.Random();
AgentID = UUID.Random();
Hashtable InitialOutfitHash = new Hashtable();
InitialOutfitHash["folder_name"] = "Nightclub Female";
InitialOutfitHash["gender"] = "female";
initialOutfit.Add(InitialOutfitHash);
}
#region Login Failure Methods
public XmlRpcResponse GenerateFailureResponse(string reason, string message, string login)
{
// Overwrite any default values;
xmlRpcResponse = new XmlRpcResponse();
// Ensure Login Failed message/reason;
ErrorMessage = message;
ErrorReason = reason;
loginError["reason"] = ErrorReason;
loginError["message"] = ErrorMessage;
loginError["login"] = login;
xmlRpcResponse.Value = loginError;
return (xmlRpcResponse);
}
public OSD GenerateFailureResponseLLSD(string reason, string message, string login)
{
OSDMap map = new OSDMap();
// Ensure Login Failed message/reason;
ErrorMessage = message;
ErrorReason = reason;
map["reason"] = OSD.FromString(ErrorReason);
map["message"] = OSD.FromString(ErrorMessage);
map["login"] = OSD.FromString(login);
return map;
}
public XmlRpcResponse CreateFailedResponse()
{
return (CreateLoginFailedResponse());
}
public OSD CreateFailedResponseLLSD()
{
return CreateLoginFailedResponseLLSD();
}
public XmlRpcResponse CreateLoginFailedResponse()
{
return
(GenerateFailureResponse("key",
"Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
"false"));
}
public XmlRpcResponse CreateViewerNotAllowedResponse()
{
return
(GenerateFailureResponse("key",
"The viewer you are using is not allowed to connect to the InWorldz grid. Please use a different viewer.",
"false"));
}
public OSD CreateLoginFailedResponseLLSD()
{
return GenerateFailureResponseLLSD(
"key",
"Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
"false");
}
/// <summary>
/// Response to indicate that login failed because the agent's inventory was not available.
/// </summary>
/// <returns></returns>
public XmlRpcResponse CreateLoginInventoryFailedResponse()
{
return GenerateFailureResponse(
"key",
"Unable to retrieve your inventory. (New user? Have you selected a starter avatar?)",
"false");
}
public XmlRpcResponse CreateAlreadyLoggedInResponse()
{
return
(GenerateFailureResponse("presence",
"You appear to be already logged in. " +
"If this is not the case please wait for your session to timeout. " +
"If this takes longer than a few minutes please contact the grid owner. " +
"Please wait 5 minutes if you are going to connect to a region nearby to the region you were at previously.",
"false"));
}
public OSD CreateAlreadyLoggedInResponseLLSD()
{
return GenerateFailureResponseLLSD(
"presence",
"You appear to be already logged in. " +
"If this is not the case please wait for your session to timeout. " +
"If this takes longer than a few minutes please contact the grid owner",
"false");
}
public XmlRpcResponse CreateLoginBlockedResponse()
{
return
(GenerateFailureResponse("presence",
"Logins are currently restricted. Please try again later",
"false"));
}
public OSD CreateLoginBlockedResponseLLSD()
{
return GenerateFailureResponseLLSD(
"presence",
"Logins are currently restricted. Please try again later",
"false");
}
public XmlRpcResponse CreateDeadRegionResponse()
{
return GenerateFailureResponse("key", this.ErrorMessage, "false");
}
public OSD CreateDeadRegionResponseLLSD()
{
return GenerateFailureResponseLLSD(
"key",
"The region you are attempting to log into is not responding. Please select another region and try again.",
"false");
}
public XmlRpcResponse CreateGridErrorResponse()
{
return
(GenerateFailureResponse("key",
"Error connecting to grid. Could not percieve credentials from login XML.",
"false"));
}
public OSD CreateGridErrorResponseLLSD()
{
return GenerateFailureResponseLLSD(
"key",
"Error connecting to grid. Could not perceive credentials from login XML.",
"false");
}
#endregion
public virtual XmlRpcResponse ToXmlRpcResponse()
{
try
{
Hashtable responseData = new Hashtable();
loginFlagsHash = new Hashtable();
loginFlagsHash["daylight_savings"] = DST;
loginFlagsHash["stipend_since_login"] = StipendSinceLogin;
loginFlagsHash["gendered"] = Gendered;
loginFlagsHash["ever_logged_in"] = EverLoggedIn;
loginFlags.Add(loginFlagsHash);
responseData["first_name"] = Firstname;
responseData["last_name"] = Lastname;
responseData["agent_access"] = agentAccess;
responseData["agent_access_max"] = agentAccess;
responseData["agent_region_access"] = agentAccess;
globalTexturesHash = new Hashtable();
globalTexturesHash["sun_texture_id"] = SunTexture;
globalTexturesHash["cloud_texture_id"] = CloudTexture;
globalTexturesHash["moon_texture_id"] = MoonTexture;
globalTextures.Add(globalTexturesHash);
// this.eventCategories.Add(this.eventCategoriesHash);
AddToUIConfig("allow_first_life", allowFirstLife);
uiConfig.Add(uiConfigHash);
responseData["sim_port"] = (Int32) SimPort;
responseData["sim_ip"] = SimAddress;
responseData["http_port"] = (Int32)SimHttpPort;
responseData["agent_id"] = AgentID.ToString();
responseData["session_id"] = SessionID.ToString();
responseData["secure_session_id"] = SecureSessionID.ToString();
responseData["circuit_code"] = CircuitCode;
responseData["seconds_since_epoch"] = (Int32) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
responseData["login-flags"] = loginFlags;
responseData["global-textures"] = globalTextures;
responseData["seed_capability"] = seedCapability;
// m_log.WarnFormat("[LOGIN]: >>> ToXmlRpcResponse UUID={0} SSID={1}", AgentID, SecureSessionID);
responseData["event_categories"] = eventCategories;
responseData["event_notifications"] = new ArrayList(); // todo
responseData["classified_categories"] = classifiedCategories;
responseData["ui-config"] = uiConfig;
if (agentInventory != null)
{
responseData["inventory-skeleton"] = agentInventory;
responseData["inventory-root"] = inventoryRoot;
}
responseData["inventory-skel-lib"] = inventoryLibrary;
responseData["inventory-lib-root"] = inventoryLibRoot;
responseData["gestures"] = activeGestures;
responseData["inventory-lib-owner"] = inventoryLibraryOwner;
responseData["initial-outfit"] = initialOutfit;
responseData["start_location"] = startLocation;
responseData["seed_capability"] = seedCapability;
responseData["home"] = home;
responseData["look_at"] = lookAt;
responseData["message"] = welcomeMessage;
responseData["region_x"] = (Int32)(RegionX * Constants.RegionSize);
responseData["region_y"] = (Int32)(RegionY * Constants.RegionSize);
responseData["map-server-url"] = MapServerURI;
responseData["max-agent-groups"] = Constants.MaxGroups.ToString();
if (m_buddyList != null)
{
responseData["buddy-list"] = m_buddyList.ToArray();
}
responseData["login"] = "true";
xmlRpcResponse.Value = responseData;
return (xmlRpcResponse);
}
catch (Exception e)
{
m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message);
return (GenerateFailureResponse("Internal Error", "Error generating Login Response", "false"));
}
}
public OSD ToLLSDResponse()
{
try
{
OSDMap map = new OSDMap();
map["first_name"] = OSD.FromString(Firstname);
map["last_name"] = OSD.FromString(Lastname);
map["agent_access"] = OSD.FromString(agentAccess);
map["sim_port"] = OSD.FromInteger(SimPort);
map["sim_ip"] = OSD.FromString(SimAddress);
map["agent_id"] = OSD.FromUUID(AgentID);
map["session_id"] = OSD.FromUUID(SessionID);
map["secure_session_id"] = OSD.FromUUID(SecureSessionID);
map["circuit_code"] = OSD.FromInteger(CircuitCode);
map["seconds_since_epoch"] = OSD.FromInteger((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
// m_log.WarnFormat("[LOGIN]: >>> ToLLSDResponse UUID={0} SSID={1}", AgentID, SecureSessionID);
#region Login Flags
OSDMap loginFlagsLLSD = new OSDMap();
loginFlagsLLSD["daylight_savings"] = OSD.FromString(DST);
loginFlagsLLSD["stipend_since_login"] = OSD.FromString(StipendSinceLogin);
loginFlagsLLSD["gendered"] = OSD.FromString(Gendered);
loginFlagsLLSD["ever_logged_in"] = OSD.FromString(EverLoggedIn);
map["login-flags"] = WrapOSDMap(loginFlagsLLSD);
#endregion Login Flags
#region Global Textures
OSDMap globalTexturesLLSD = new OSDMap();
globalTexturesLLSD["sun_texture_id"] = OSD.FromString(SunTexture);
globalTexturesLLSD["cloud_texture_id"] = OSD.FromString(CloudTexture);
globalTexturesLLSD["moon_texture_id"] = OSD.FromString(MoonTexture);
map["global-textures"] = WrapOSDMap(globalTexturesLLSD);
#endregion Global Textures
map["seed_capability"] = OSD.FromString(seedCapability);
map["event_categories"] = ArrayListToOSDArray(eventCategories);
//map["event_notifications"] = new OSDArray(); // todo
map["classified_categories"] = ArrayListToOSDArray(classifiedCategories);
#region UI Config
OSDMap uiConfigLLSD = new OSDMap();
uiConfigLLSD["allow_first_life"] = OSD.FromString(allowFirstLife);
map["ui-config"] = WrapOSDMap(uiConfigLLSD);
#endregion UI Config
#region Inventory
map["inventory-skeleton"] = ArrayListToOSDArray(agentInventory);
map["inventory-skel-lib"] = ArrayListToOSDArray(inventoryLibrary);
map["inventory-root"] = ArrayListToOSDArray(inventoryRoot); ;
map["inventory-lib-root"] = ArrayListToOSDArray(inventoryLibRoot);
map["inventory-lib-owner"] = ArrayListToOSDArray(inventoryLibraryOwner);
#endregion Inventory
map["gestures"] = ArrayListToOSDArray(activeGestures);
map["initial-outfit"] = ArrayListToOSDArray(initialOutfit);
map["start_location"] = OSD.FromString(startLocation);
map["seed_capability"] = OSD.FromString(seedCapability);
map["home"] = OSD.FromString(home);
map["look_at"] = OSD.FromString(lookAt);
map["message"] = OSD.FromString(welcomeMessage);
map["region_x"] = OSD.FromInteger(RegionX * Constants.RegionSize);
map["region_y"] = OSD.FromInteger(RegionY * Constants.RegionSize);
map["max-agent-groups"] = OSD.FromInteger(Constants.MaxGroups);
if (m_buddyList != null)
{
map["buddy-list"] = ArrayListToOSDArray(m_buddyList.ToArray());
}
map["login"] = OSD.FromString("true");
return map;
}
catch (Exception e)
{
m_log.Warn("[CLIENT]: LoginResponse: Error creating LLSD Response: " + e.Message);
return GenerateFailureResponseLLSD("Internal Error", "Error generating Login Response", "false");
}
}
public OSDArray ArrayListToOSDArray(ArrayList arrlst)
{
OSDArray llsdBack = new OSDArray();
foreach (Hashtable ht in arrlst)
{
OSDMap mp = new OSDMap();
foreach (DictionaryEntry deHt in ht)
{
mp.Add((string)deHt.Key, OSDString.FromObject(deHt.Value));
}
llsdBack.Add(mp);
}
return llsdBack;
}
private static OSDArray WrapOSDMap(OSDMap wrapMe)
{
OSDArray array = new OSDArray();
array.Add(wrapMe);
return array;
}
public void SetEventCategories(string category, string value)
{
// this.eventCategoriesHash[category] = value;
//TODO
}
public void AddToUIConfig(string itemName, string item)
{
uiConfigHash[itemName] = item;
}
public void AddClassifiedCategory(Int32 ID, string categoryName)
{
Hashtable hash = new Hashtable();
hash["category_name"] = categoryName;
hash["category_id"] = ID;
classifiedCategories.Add(hash);
// this.classifiedCategoriesHash.Clear();
}
#region Properties
public string Login
{
get { return login; }
set { login = value; }
}
public string DST
{
get { return dst; }
set { dst = value; }
}
public string StipendSinceLogin
{
get { return stipendSinceLogin; }
set { stipendSinceLogin = value; }
}
public string Gendered
{
get { return gendered; }
set { gendered = value; }
}
public string EverLoggedIn
{
get { return everLoggedIn; }
set { everLoggedIn = value; }
}
public uint SimPort
{
get { return simPort; }
set { simPort = value; }
}
public uint SimHttpPort
{
get { return simHttpPort; }
set { simHttpPort = value; }
}
public string SimAddress
{
get { return simAddress; }
set { simAddress = value; }
}
public UUID AgentID
{
get { return agentID; }
set { agentID = value; }
}
public UUID SessionID
{
get { return sessionID; }
set { sessionID = value; }
}
public UUID SecureSessionID
{
get { return secureSessionID; }
set { secureSessionID = value; }
}
public Int32 CircuitCode
{
get { return circuitCode; }
set { circuitCode = value; }
}
public uint RegionX
{
get { return regionX; }
set { regionX = value; }
}
public uint RegionY
{
get { return regionY; }
set { regionY = value; }
}
public string SunTexture
{
get { return sunTexture; }
set { sunTexture = value; }
}
public string CloudTexture
{
get { return cloudTexture; }
set { cloudTexture = value; }
}
public string MoonTexture
{
get { return moonTexture; }
set { moonTexture = value; }
}
public string Firstname
{
get { return firstname; }
set { firstname = value; }
}
public string Lastname
{
get { return lastname; }
set { lastname = value; }
}
public string AgentAccess
{
get { return agentAccess; }
set { agentAccess = value; }
}
public string StartLocation
{
get { return startLocation; }
set { startLocation = value; }
}
public string LookAt
{
get { return lookAt; }
set { lookAt = value; }
}
public string SeedCapability
{
get { return seedCapability; }
set { seedCapability = value; }
}
public string ErrorReason
{
get { return errorReason; }
set { errorReason = value; }
}
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}
public ArrayList InventoryRoot
{
get { return inventoryRoot; }
set { inventoryRoot = value; }
}
public ArrayList InventorySkeleton
{
get { return agentInventory; }
set { agentInventory = value; }
}
public ArrayList InventoryLibrary
{
get { return inventoryLibrary; }
set { inventoryLibrary = value; }
}
public ArrayList InventoryLibraryOwner
{
get { return inventoryLibraryOwner; }
set { inventoryLibraryOwner = value; }
}
public ArrayList InventoryLibRoot
{
get { return inventoryLibRoot; }
set { inventoryLibRoot = value; }
}
public ArrayList ActiveGestures
{
get { return activeGestures; }
set { activeGestures = value; }
}
public string Home
{
get { return home; }
set { home = value; }
}
public string Message
{
get { return welcomeMessage; }
set { welcomeMessage = value; }
}
public BuddyList BuddList
{
get { return m_buddyList; }
set { m_buddyList = value; }
}
public string MapServerURI
{
get { return mapServerURI; }
set { mapServerURI = value; }
}
#endregion
public class UserInfo
{
public string firstname;
public string lastname;
public ulong homeregionhandle;
public Vector3 homepos;
public Vector3 homelookat;
}
public class BuddyList
{
public List<BuddyInfo> Buddies = new List<BuddyInfo>();
public void AddNewBuddy(BuddyInfo buddy)
{
if (!Buddies.Contains(buddy))
{
Buddies.Add(buddy);
}
}
public ArrayList ToArray()
{
ArrayList buddyArray = new ArrayList();
foreach (BuddyInfo buddy in Buddies)
{
buddyArray.Add(buddy.ToHashTable());
}
return buddyArray;
}
public class BuddyInfo
{
public int BuddyRightsHave = 1;
public int BuddyRightsGiven = 1;
public UUID BuddyID;
public BuddyInfo(string buddyID)
{
BuddyID = new UUID(buddyID);
}
public BuddyInfo(UUID buddyID)
{
BuddyID = buddyID;
}
public Hashtable ToHashTable()
{
Hashtable hTable = new Hashtable();
hTable["buddy_rights_has"] = BuddyRightsHave;
hTable["buddy_rights_given"] = BuddyRightsGiven;
hTable["buddy_id"] = BuddyID.ToString();
return hTable;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Provides some basic access to some environment
** functionality.
**
**
============================================================*/
namespace System
{
using System.IO;
using System.Security;
using System.Resources;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Configuration.Assemblies;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
public enum EnvironmentVariableTarget
{
Process = 0,
User = 1,
Machine = 2,
}
internal static partial class Environment
{
// Assume the following constants include the terminating '\0' - use <, not <=
private const int MaxEnvVariableValueLength = 32767; // maximum length for environment variable name and value
// System environment variables are stored in the registry, and have
// a size restriction that is separate from both normal environment
// variables and registry value name lengths, according to MSDN.
// MSDN doesn't detail whether the name is limited to 1024, or whether
// that includes the contents of the environment variable.
private const int MaxSystemEnvVariableLength = 1024;
private const int MaxUserEnvVariableLength = 255;
private const int MaxMachineNameLength = 256;
// Looks up the resource string value for key.
//
// if you change this method's signature then you must change the code that calls it
// in excep.cpp and probably you will have to visit mscorlib.h to add the new signature
// as well as metasig.h to create the new signature type
internal static String GetResourceStringLocal(String key)
{
return SR.GetResourceString(key);
}
/*==================================TickCount===================================
**Action: Gets the number of ticks since the system was started.
**Returns: The number of ticks since the system was started.
**Arguments: None
**Exceptions: None
==============================================================================*/
public static extern int TickCount
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Terminates this process with the given exit code.
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void _Exit(int exitCode);
public static void Exit(int exitCode)
{
_Exit(exitCode);
}
public static extern int ExitCode
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
// Note: The CLR's Watson bucketization code looks at the caller of the FCALL method
// to assign blame for crashes. Don't mess with this, such as by making it call
// another managed helper method, unless you consult with some CLR Watson experts.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void FailFast(String message);
// This overload of FailFast will allow you to specify the exception object
// whose bucket details *could* be used when undergoing the failfast process.
// To be specific:
//
// 1) When invoked from within a managed EH clause (fault/finally/catch),
// if the exception object is preallocated, the runtime will try to find its buckets
// and use them. If the exception object is not preallocated, it will use the bucket
// details contained in the object (if any).
//
// 2) When invoked from outside the managed EH clauses (fault/finally/catch),
// if the exception object is preallocated, the runtime will use the callsite's
// IP for bucketing. If the exception object is not preallocated, it will use the bucket
// details contained in the object (if any).
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void FailFast(String message, Exception exception);
public static String ExpandEnvironmentVariables(String name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
{
return name;
}
int currentSize = 100;
StringBuilder blob = new StringBuilder(currentSize); // A somewhat reasonable default size
#if PLATFORM_UNIX // Win32Native.ExpandEnvironmentStrings isn't available
int lastPos = 0, pos;
while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0)
{
if (name[lastPos] == '%')
{
string key = name.Substring(lastPos + 1, pos - lastPos - 1);
string value = Environment.GetEnvironmentVariable(key);
if (value != null)
{
blob.Append(value);
lastPos = pos + 1;
continue;
}
}
blob.Append(name.Substring(lastPos, pos - lastPos));
lastPos = pos;
}
blob.Append(name.Substring(lastPos));
#else
int size;
blob.Length = 0;
size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
if (size == 0)
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
while (size > currentSize)
{
currentSize = size;
blob.Capacity = currentSize;
blob.Length = 0;
size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
if (size == 0)
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
#endif // PLATFORM_UNIX
return blob.ToString();
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern Int32 GetProcessorCount();
public static int ProcessorCount
{
get
{
return GetProcessorCount();
}
}
/*==============================GetCommandLineArgs==============================
**Action: Gets the command line and splits it appropriately to deal with whitespace,
** quotes, and escape characters.
**Returns: A string array containing your command line arguments.
**Arguments: None
**Exceptions: None.
==============================================================================*/
public static String[] GetCommandLineArgs()
{
/*
* There are multiple entry points to a hosted app.
* The host could use ::ExecuteAssembly() or ::CreateDelegate option
* ::ExecuteAssembly() -> In this particular case, the runtime invokes the main
method based on the arguments set by the host, and we return those arguments
*
* ::CreateDelegate() -> In this particular case, the host is asked to create a
* delegate based on the appDomain, assembly and methodDesc passed to it.
* which the caller uses to invoke the method. In this particular case we do not have
* any information on what arguments would be passed to the delegate.
* So our best bet is to simply use the commandLine that was used to invoke the process.
* in case it is present.
*/
if (s_CommandLineArgs != null)
return (string[])s_CommandLineArgs.Clone();
return GetCommandLineArgsNative();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String[] GetCommandLineArgsNative();
private static string[] s_CommandLineArgs = null;
private static void SetCommandLineArgs(string[] cmdLineArgs)
{
s_CommandLineArgs = cmdLineArgs;
}
private unsafe static char[] GetEnvironmentCharArray()
{
char[] block = null;
RuntimeHelpers.PrepareConstrainedRegions();
char* pStrings = null;
try
{
pStrings = Win32Native.GetEnvironmentStrings();
if (pStrings == null)
{
throw new OutOfMemoryException();
}
// Format for GetEnvironmentStrings is:
// [=HiddenVar=value\0]* [Variable=value\0]* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Search for terminating \0\0 (two unicode \0's).
char* p = pStrings;
while (!(*p == '\0' && *(p + 1) == '\0'))
p++;
int len = (int)(p - pStrings + 1);
block = new char[len];
fixed (char* pBlock = block)
string.wstrcpy(pBlock, pStrings, len);
}
finally
{
if (pStrings != null)
Win32Native.FreeEnvironmentStrings(pStrings);
}
return block;
}
/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
** platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine
{
get
{
#if PLATFORM_WINDOWS
return "\r\n";
#else
return "\n";
#endif // PLATFORM_WINDOWS
}
}
/*===================================Version====================================
**Action: Returns the COM+ version struct, describing the build number.
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
public static Version Version
{
get
{
// Previously this represented the File version of mscorlib.dll. Many other libraries in the framework and outside took dependencies on the first three parts of this version
// remaining constant throughout 4.x. From 4.0 to 4.5.2 this was fine since the file version only incremented the last part.Starting with 4.6 we switched to a file versioning
// scheme that matched the product version. In order to preserve compatibility with existing libraries, this needs to be hard-coded.
return new Version(4, 0, 30319, 42000);
}
}
#if !FEATURE_PAL
private static Lazy<bool> s_IsWindows8OrAbove = new Lazy<bool>(() =>
{
ulong conditionMask = Win32Native.VerSetConditionMask(0, Win32Native.VER_MAJORVERSION, Win32Native.VER_GREATER_EQUAL);
conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_MINORVERSION, Win32Native.VER_GREATER_EQUAL);
conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMAJOR, Win32Native.VER_GREATER_EQUAL);
conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMINOR, Win32Native.VER_GREATER_EQUAL);
// Windows 8 version is 6.2
var version = new Win32Native.OSVERSIONINFOEX { MajorVersion = 6, MinorVersion = 2, ServicePackMajor = 0, ServicePackMinor = 0 };
return Win32Native.VerifyVersionInfoW(version,
Win32Native.VER_MAJORVERSION | Win32Native.VER_MINORVERSION | Win32Native.VER_SERVICEPACKMAJOR | Win32Native.VER_SERVICEPACKMINOR,
conditionMask);
});
internal static bool IsWindows8OrAbove => s_IsWindows8OrAbove.Value;
#endif
#if FEATURE_COMINTEROP
// Does the current version of Windows have Windows Runtime suppport?
private static Lazy<bool> s_IsWinRTSupported = new Lazy<bool>(() =>
{
return WinRTSupported();
});
internal static bool IsWinRTSupported => s_IsWinRTSupported.Value;
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool WinRTSupported();
#endif // FEATURE_COMINTEROP
/*==================================StackTrace==================================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
public static String StackTrace
{
[MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts
get
{
return Internal.Runtime.Augments.EnvironmentAugments.StackTrace;
}
}
internal static String GetStackTrace(Exception e, bool needFileInfo)
{
// Note: Setting needFileInfo to true will start up COM and set our
// apartment state. Try to not call this when passing "true"
// before the EE's ExecuteMainMethod has had a chance to set up the
// apartment state. --
StackTrace st;
if (e == null)
st = new StackTrace(needFileInfo);
else
st = new StackTrace(e, needFileInfo);
// Do no include a trailing newline for backwards compatibility
return st.ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
}
public static extern bool HasShutdownStarted
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
internal static bool UserInteractive
{
get
{
return true;
}
}
public static int CurrentManagedThreadId
{
get
{
return Thread.CurrentThread.ManagedThreadId;
}
}
internal static extern int CurrentProcessorNumber
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// The upper bits of t_executionIdCache are the executionId. The lower bits of
// the t_executionIdCache are counting down to get it periodically refreshed.
// TODO: Consider flushing the executionIdCache on Wait operations or similar
// actions that are likely to result in changing the executing core
[ThreadStatic]
private static int t_executionIdCache;
private const int ExecutionIdCacheShift = 16;
private const int ExecutionIdCacheCountDownMask = (1 << ExecutionIdCacheShift) - 1;
private const int ExecutionIdRefreshRate = 5000;
private static int RefreshExecutionId()
{
int executionId = CurrentProcessorNumber;
// On Unix, CurrentProcessorNumber is implemented in terms of sched_getcpu, which
// doesn't exist on all platforms. On those it doesn't exist on, GetCurrentProcessorNumber
// returns -1. As a fallback in that case and to spread the threads across the buckets
// by default, we use the current managed thread ID as a proxy.
if (executionId < 0) executionId = Environment.CurrentManagedThreadId;
Debug.Assert(ExecutionIdRefreshRate <= ExecutionIdCacheCountDownMask);
// Mask with Int32.MaxValue to ensure the execution Id is not negative
t_executionIdCache = ((executionId << ExecutionIdCacheShift) & Int32.MaxValue) | ExecutionIdRefreshRate;
return executionId;
}
// Cached processor number used as a hint for which per-core stack to access. It is periodically
// refreshed to trail the actual thread core affinity.
internal static int CurrentExecutionId
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
int executionIdCache = t_executionIdCache--;
if ((executionIdCache & ExecutionIdCacheCountDownMask) == 0)
return RefreshExecutionId();
return (executionIdCache >> ExecutionIdCacheShift);
}
}
public static string GetEnvironmentVariable(string variable)
{
if (variable == null)
{
throw new ArgumentNullException(nameof(variable));
}
// separated from the EnvironmentVariableTarget overload to help with tree shaking in common case
return GetEnvironmentVariableCore(variable);
}
internal static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
{
if (variable == null)
{
throw new ArgumentNullException(nameof(variable));
}
ValidateTarget(target);
return GetEnvironmentVariableCore(variable, target);
}
public static void SetEnvironmentVariable(string variable, string value)
{
ValidateVariableAndValue(variable, ref value);
// separated from the EnvironmentVariableTarget overload to help with tree shaking in common case
SetEnvironmentVariableCore(variable, value);
}
internal static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
{
ValidateVariableAndValue(variable, ref value);
ValidateTarget(target);
SetEnvironmentVariableCore(variable, value, target);
}
private static void ValidateVariableAndValue(string variable, ref string value)
{
const int MaxEnvVariableValueLength = 32767;
if (variable == null)
{
throw new ArgumentNullException(nameof(variable));
}
if (variable.Length == 0)
{
throw new ArgumentException(SR.Argument_StringZeroLength, nameof(variable));
}
if (variable[0] == '\0')
{
throw new ArgumentException(SR.Argument_StringFirstCharIsZero, nameof(variable));
}
if (variable.Length >= MaxEnvVariableValueLength)
{
throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
}
if (variable.IndexOf('=') != -1)
{
throw new ArgumentException(SR.Argument_IllegalEnvVarName, nameof(variable));
}
if (string.IsNullOrEmpty(value) || value[0] == '\0')
{
// Explicitly null out value if it's empty
value = null;
}
else if (value.Length >= MaxEnvVariableValueLength)
{
throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(value));
}
}
private static void ValidateTarget(EnvironmentVariableTarget target)
{
if (target != EnvironmentVariableTarget.Process &&
target != EnvironmentVariableTarget.Machine &&
target != EnvironmentVariableTarget.User)
{
throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target));
}
}
private static string GetEnvironmentVariableCore(string variable)
{
StringBuilder sb = StringBuilderCache.Acquire(128); // A somewhat reasonable default size
int requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
if (requiredSize == 0 && Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND)
{
StringBuilderCache.Release(sb);
return null;
}
while (requiredSize > sb.Capacity)
{
sb.Capacity = requiredSize;
sb.Length = 0;
requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
}
return StringBuilderCache.GetStringAndRelease(sb);
}
private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
{
if (target == EnvironmentVariableTarget.Process)
return GetEnvironmentVariableCore(variable);
#if FEATURE_WIN32_REGISTRY
if (AppDomain.IsAppXModel())
#endif
{
return null;
}
#if FEATURE_WIN32_REGISTRY
RegistryKey baseKey;
string keyName;
if (target == EnvironmentVariableTarget.Machine)
{
baseKey = Registry.LocalMachine;
keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
}
else if (target == EnvironmentVariableTarget.User)
{
baseKey = Registry.CurrentUser;
keyName = "Environment";
}
else
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
{
return environmentKey?.GetValue(variable) as string;
}
#endif
}
internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables()
{
// Format for GetEnvironmentStrings is:
// (=HiddenVar=value\0 | Variable=value\0)* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Note the =HiddenVar's aren't always at the beginning.
// Copy strings out, parsing into pairs and inserting into the table.
// The first few environment variable entries start with an '='.
// The current working directory of every drive (except for those drives
// you haven't cd'ed into in your DOS window) are stored in the
// environment block (as =C:=pwd) and the program's exit code is
// as well (=ExitCode=00000000).
char[] block = GetEnvironmentCharArray();
for (int i = 0; i < block.Length; i++)
{
int startKey = i;
// Skip to key. On some old OS, the environment block can be corrupted.
// Some will not have '=', so we need to check for '\0'.
while (block[i] != '=' && block[i] != '\0')
i++;
if (block[i] == '\0')
continue;
// Skip over environment variables starting with '='
if (i - startKey == 0)
{
while (block[i] != 0)
i++;
continue;
}
string key = new string(block, startKey, i - startKey);
i++; // skip over '='
int startValue = i;
while (block[i] != 0)
i++; // Read to end of this entry
string value = new string(block, startValue, i - startValue); // skip over 0 handled by for loop's i++
yield return new KeyValuePair<string, string>(key, value);
}
}
internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables(EnvironmentVariableTarget target)
{
if (target == EnvironmentVariableTarget.Process)
return EnumerateEnvironmentVariables();
return EnumerateEnvironmentVariablesFromRegistry(target);
}
internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariablesFromRegistry(EnvironmentVariableTarget target)
{
#if FEATURE_WIN32_REGISTRY
if (AppDomain.IsAppXModel())
#endif
{
// Without registry support we have nothing to return
ValidateTarget(target);
yield break;
}
#if FEATURE_WIN32_REGISTRY
RegistryKey baseKey;
string keyName;
if (target == EnvironmentVariableTarget.Machine)
{
baseKey = Registry.LocalMachine;
keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
}
else if (target == EnvironmentVariableTarget.User)
{
baseKey = Registry.CurrentUser;
keyName = @"Environment";
}
else
{
throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
{
if (environmentKey != null)
{
foreach (string name in environmentKey.GetValueNames())
{
string value = environmentKey.GetValue(name, "").ToString();
yield return new KeyValuePair<string, string>(name, value);
}
}
}
#endif // FEATURE_WIN32_REGISTRY
}
private static void SetEnvironmentVariableCore(string variable, string value)
{
// explicitly null out value if is the empty string.
if (string.IsNullOrEmpty(value) || value[0] == '\0')
value = null;
if (!Win32Native.SetEnvironmentVariable(variable, value))
{
int errorCode = Marshal.GetLastWin32Error();
switch (errorCode)
{
case Win32Native.ERROR_ENVVAR_NOT_FOUND:
// Allow user to try to clear a environment variable
return;
case Win32Native.ERROR_FILENAME_EXCED_RANGE:
// The error message from Win32 is "The filename or extension is too long",
// which is not accurate.
throw new ArgumentException(SR.Format(SR.Argument_LongEnvVarValue));
default:
throw new ArgumentException(Interop.Kernel32.GetMessage(errorCode));
}
}
}
private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
{
if (target == EnvironmentVariableTarget.Process)
{
SetEnvironmentVariableCore(variable, value);
return;
}
#if FEATURE_WIN32_REGISTRY
if (AppDomain.IsAppXModel())
#endif
{
// other targets ignored
return;
}
#if FEATURE_WIN32_REGISTRY
// explicitly null out value if is the empty string.
if (string.IsNullOrEmpty(value) || value[0] == '\0')
value = null;
RegistryKey baseKey;
string keyName;
if (target == EnvironmentVariableTarget.Machine)
{
baseKey = Registry.LocalMachine;
keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
}
else if (target == EnvironmentVariableTarget.User)
{
// User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
const int MaxUserEnvVariableLength = 255;
if (variable.Length >= MaxUserEnvVariableLength)
{
throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
}
baseKey = Registry.CurrentUser;
keyName = "Environment";
}
else
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
{
if (environmentKey != null)
{
if (value == null)
{
environmentKey.DeleteValue(variable, throwOnMissingValue: false);
}
else
{
environmentKey.SetValue(variable, value);
}
}
}
// send a WM_SETTINGCHANGE message to all windows
IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST),
Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
if (r == IntPtr.Zero) Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
#endif // FEATURE_WIN32_REGISTRY
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* DoubleClick Bid Manager API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/bid-manager/'>DoubleClick Bid Manager API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20170705 (916)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/bid-manager/'>
* https://developers.google.com/bid-manager/</a>
* <tr><th>Discovery Name<td>doubleclickbidmanager
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using DoubleClick Bid Manager API can be found at
* <a href='https://developers.google.com/bid-manager/'>https://developers.google.com/bid-manager/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.DoubleClickBidManager.v1
{
/// <summary>The DoubleClickBidManager Service.</summary>
public class DoubleClickBidManagerService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public DoubleClickBidManagerService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public DoubleClickBidManagerService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
lineitems = new LineitemsResource(this);
queries = new QueriesResource(this);
reports = new ReportsResource(this);
sdf = new SdfResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "doubleclickbidmanager"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/doubleclickbidmanager/v1/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "doubleclickbidmanager/v1/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the DoubleClick Bid Manager API.</summary>
public class Scope
{
/// <summary>View and manage your reports in DoubleClick Bid Manager</summary>
public static string Doubleclickbidmanager = "https://www.googleapis.com/auth/doubleclickbidmanager";
}
private readonly LineitemsResource lineitems;
/// <summary>Gets the Lineitems resource.</summary>
public virtual LineitemsResource Lineitems
{
get { return lineitems; }
}
private readonly QueriesResource queries;
/// <summary>Gets the Queries resource.</summary>
public virtual QueriesResource Queries
{
get { return queries; }
}
private readonly ReportsResource reports;
/// <summary>Gets the Reports resource.</summary>
public virtual ReportsResource Reports
{
get { return reports; }
}
private readonly SdfResource sdf;
/// <summary>Gets the Sdf resource.</summary>
public virtual SdfResource Sdf
{
get { return sdf; }
}
}
///<summary>A base abstract class for DoubleClickBidManager requests.</summary>
public abstract class DoubleClickBidManagerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new DoubleClickBidManagerBaseServiceRequest instance.</summary>
protected DoubleClickBidManagerBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes DoubleClickBidManager parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "lineitems" collection of methods.</summary>
public class LineitemsResource
{
private const string Resource = "lineitems";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LineitemsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves line items in CSV format.</summary>
/// <param name="body">The body of the request.</param>
public virtual DownloadlineitemsRequest Downloadlineitems(Google.Apis.DoubleClickBidManager.v1.Data.DownloadLineItemsRequest body)
{
return new DownloadlineitemsRequest(service, body);
}
/// <summary>Retrieves line items in CSV format.</summary>
public class DownloadlineitemsRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.DownloadLineItemsResponse>
{
/// <summary>Constructs a new Downloadlineitems request.</summary>
public DownloadlineitemsRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.DownloadLineItemsRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.DoubleClickBidManager.v1.Data.DownloadLineItemsRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "downloadlineitems"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "lineitems/downloadlineitems"; }
}
/// <summary>Initializes Downloadlineitems parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Uploads line items in CSV format.</summary>
/// <param name="body">The body of the request.</param>
public virtual UploadlineitemsRequest Uploadlineitems(Google.Apis.DoubleClickBidManager.v1.Data.UploadLineItemsRequest body)
{
return new UploadlineitemsRequest(service, body);
}
/// <summary>Uploads line items in CSV format.</summary>
public class UploadlineitemsRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.UploadLineItemsResponse>
{
/// <summary>Constructs a new Uploadlineitems request.</summary>
public UploadlineitemsRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.UploadLineItemsRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.DoubleClickBidManager.v1.Data.UploadLineItemsRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "uploadlineitems"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "lineitems/uploadlineitems"; }
}
/// <summary>Initializes Uploadlineitems parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
/// <summary>The "queries" collection of methods.</summary>
public class QueriesResource
{
private const string Resource = "queries";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public QueriesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a query.</summary>
/// <param name="body">The body of the request.</param>
public virtual CreatequeryRequest Createquery(Google.Apis.DoubleClickBidManager.v1.Data.Query body)
{
return new CreatequeryRequest(service, body);
}
/// <summary>Creates a query.</summary>
public class CreatequeryRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.Query>
{
/// <summary>Constructs a new Createquery request.</summary>
public CreatequeryRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.Query body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.DoubleClickBidManager.v1.Data.Query Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "createquery"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "query"; }
}
/// <summary>Initializes Createquery parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Deletes a stored query as well as the associated stored reports.</summary>
/// <param name="queryId">Query ID to delete.</param>
public virtual DeletequeryRequest Deletequery(long queryId)
{
return new DeletequeryRequest(service, queryId);
}
/// <summary>Deletes a stored query as well as the associated stored reports.</summary>
public class DeletequeryRequest : DoubleClickBidManagerBaseServiceRequest<string>
{
/// <summary>Constructs a new Deletequery request.</summary>
public DeletequeryRequest(Google.Apis.Services.IClientService service, long queryId)
: base(service)
{
QueryId = queryId;
InitParameters();
}
/// <summary>Query ID to delete.</summary>
[Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long QueryId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "deletequery"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "query/{queryId}"; }
}
/// <summary>Initializes Deletequery parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"queryId", new Google.Apis.Discovery.Parameter
{
Name = "queryId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Retrieves a stored query.</summary>
/// <param name="queryId">Query ID to retrieve.</param>
public virtual GetqueryRequest Getquery(long queryId)
{
return new GetqueryRequest(service, queryId);
}
/// <summary>Retrieves a stored query.</summary>
public class GetqueryRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.Query>
{
/// <summary>Constructs a new Getquery request.</summary>
public GetqueryRequest(Google.Apis.Services.IClientService service, long queryId)
: base(service)
{
QueryId = queryId;
InitParameters();
}
/// <summary>Query ID to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long QueryId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getquery"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "query/{queryId}"; }
}
/// <summary>Initializes Getquery parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"queryId", new Google.Apis.Discovery.Parameter
{
Name = "queryId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Retrieves stored queries.</summary>
public virtual ListqueriesRequest Listqueries()
{
return new ListqueriesRequest(service);
}
/// <summary>Retrieves stored queries.</summary>
public class ListqueriesRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.ListQueriesResponse>
{
/// <summary>Constructs a new Listqueries request.</summary>
public ListqueriesRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "listqueries"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "queries"; }
}
/// <summary>Initializes Listqueries parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Runs a stored query to generate a report.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="queryId">Query ID to run.</param>
public virtual RunqueryRequest Runquery(Google.Apis.DoubleClickBidManager.v1.Data.RunQueryRequest body, long queryId)
{
return new RunqueryRequest(service, body, queryId);
}
/// <summary>Runs a stored query to generate a report.</summary>
public class RunqueryRequest : DoubleClickBidManagerBaseServiceRequest<string>
{
/// <summary>Constructs a new Runquery request.</summary>
public RunqueryRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.RunQueryRequest body, long queryId)
: base(service)
{
QueryId = queryId;
Body = body;
InitParameters();
}
/// <summary>Query ID to run.</summary>
[Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long QueryId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.DoubleClickBidManager.v1.Data.RunQueryRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "runquery"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "query/{queryId}"; }
}
/// <summary>Initializes Runquery parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"queryId", new Google.Apis.Discovery.Parameter
{
Name = "queryId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "reports" collection of methods.</summary>
public class ReportsResource
{
private const string Resource = "reports";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ReportsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves stored reports.</summary>
/// <param name="queryId">Query ID with which the reports are associated.</param>
public virtual ListreportsRequest Listreports(long queryId)
{
return new ListreportsRequest(service, queryId);
}
/// <summary>Retrieves stored reports.</summary>
public class ListreportsRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.ListReportsResponse>
{
/// <summary>Constructs a new Listreports request.</summary>
public ListreportsRequest(Google.Apis.Services.IClientService service, long queryId)
: base(service)
{
QueryId = queryId;
InitParameters();
}
/// <summary>Query ID with which the reports are associated.</summary>
[Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long QueryId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "listreports"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "queries/{queryId}/reports"; }
}
/// <summary>Initializes Listreports parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"queryId", new Google.Apis.Discovery.Parameter
{
Name = "queryId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "sdf" collection of methods.</summary>
public class SdfResource
{
private const string Resource = "sdf";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SdfResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves entities in SDF format.</summary>
/// <param name="body">The body of the request.</param>
public virtual DownloadRequest Download(Google.Apis.DoubleClickBidManager.v1.Data.DownloadRequest body)
{
return new DownloadRequest(service, body);
}
/// <summary>Retrieves entities in SDF format.</summary>
public class DownloadRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.DownloadResponse>
{
/// <summary>Constructs a new Download request.</summary>
public DownloadRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.DownloadRequest body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.DoubleClickBidManager.v1.Data.DownloadRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "download"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "sdf/download"; }
}
/// <summary>Initializes Download parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.DoubleClickBidManager.v1.Data
{
/// <summary>Request to fetch stored line items.</summary>
public class DownloadLineItemsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>File specification (column names, types, order) in which the line items will be returned. Default
/// to EWF.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fileSpec")]
public virtual string FileSpec { get; set; }
/// <summary>Ids of the specified filter type used to filter line items to fetch. If omitted, all the line items
/// will be returned.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("filterIds")]
public virtual System.Collections.Generic.IList<System.Nullable<long>> FilterIds { get; set; }
/// <summary>Filter type used to filter line items to fetch.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("filterType")]
public virtual string FilterType { get; set; }
/// <summary>Format in which the line items will be returned. Default to CSV.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Download line items response.</summary>
public class DownloadLineItemsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Retrieved line items in CSV format. For more information about file formats, see Entity Write File
/// Format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lineItems")]
public virtual string LineItems { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request to fetch stored insertion orders, line items, TrueView ad groups and ads.</summary>
public class DownloadRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>File types that will be returned.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fileTypes")]
public virtual System.Collections.Generic.IList<string> FileTypes { get; set; }
/// <summary>The IDs of the specified filter type. This is used to filter entities to fetch. At least one ID
/// must be specified. Only one ID is allowed for the ADVERTISER_ID filter type. For INSERTION_ORDER_ID or
/// LINE_ITEM_ID filter types, all IDs must be from the same Advertiser.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("filterIds")]
public virtual System.Collections.Generic.IList<System.Nullable<long>> FilterIds { get; set; }
/// <summary>Filter type used to filter line items to fetch.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("filterType")]
public virtual string FilterType { get; set; }
/// <summary>SDF Version (column names, types, order) in which the entities will be returned. Default to
/// 3.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Download response.</summary>
public class DownloadResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Retrieved ad groups in SDF format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("adGroups")]
public virtual string AdGroups { get; set; }
/// <summary>Retrieved ads in SDF format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ads")]
public virtual string Ads { get; set; }
/// <summary>Retrieved insertion orders in SDF format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("insertionOrders")]
public virtual string InsertionOrders { get; set; }
/// <summary>Retrieved line items in SDF format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lineItems")]
public virtual string LineItems { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Filter used to match traffic data in your report.</summary>
public class FilterPair : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Filter type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>Filter value.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>List queries response.</summary>
public class ListQueriesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Identifies what kind of resource this is. Value: the fixed string
/// "doubleclickbidmanager#listQueriesResponse".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Retrieved queries.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queries")]
public virtual System.Collections.Generic.IList<Query> Queries { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>List reports response.</summary>
public class ListReportsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Identifies what kind of resource this is. Value: the fixed string
/// "doubleclickbidmanager#listReportsResponse".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Retrieved reports.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reports")]
public virtual System.Collections.Generic.IList<Report> Reports { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Parameters of a query or report.</summary>
public class Parameters : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Filters used to match traffic data in your report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("filters")]
public virtual System.Collections.Generic.IList<FilterPair> Filters { get; set; }
/// <summary>Data is grouped by the filters listed in this field.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("groupBys")]
public virtual System.Collections.Generic.IList<string> GroupBys { get; set; }
/// <summary>Whether to include data from Invite Media.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("includeInviteData")]
public virtual System.Nullable<bool> IncludeInviteData { get; set; }
/// <summary>Metrics to include as columns in your report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metrics")]
public virtual System.Collections.Generic.IList<string> Metrics { get; set; }
/// <summary>Report type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a query.</summary>
public class Query : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Identifies what kind of resource this is. Value: the fixed string
/// "doubleclickbidmanager#query".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Query metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual QueryMetadata Metadata { get; set; }
/// <summary>Query parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("params")]
public virtual Parameters Params__ { get; set; }
/// <summary>Query ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryId")]
public virtual System.Nullable<long> QueryId { get; set; }
/// <summary>The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if
/// metadata.dataRange is CUSTOM_DATES and ignored otherwise.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")]
public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; }
/// <summary>The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required
/// if metadata.dataRange is CUSTOM_DATES and ignored otherwise.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")]
public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; }
/// <summary>Information on how often and when to run a query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("schedule")]
public virtual QuerySchedule Schedule { get; set; }
/// <summary>Canonical timezone code for report data time. Defaults to America/New_York.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timezoneCode")]
public virtual string TimezoneCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Query metadata.</summary>
public class QueryMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Range of report data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dataRange")]
public virtual string DataRange { get; set; }
/// <summary>Format of the generated report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>The path to the location in Google Cloud Storage where the latest report is stored.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("googleCloudStoragePathForLatestReport")]
public virtual string GoogleCloudStoragePathForLatestReport { get; set; }
/// <summary>The path in Google Drive for the latest report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("googleDrivePathForLatestReport")]
public virtual string GoogleDrivePathForLatestReport { get; set; }
/// <summary>The time when the latest report started to run.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("latestReportRunTimeMs")]
public virtual System.Nullable<long> LatestReportRunTimeMs { get; set; }
/// <summary>Locale of the generated reports. Valid values are cs CZECH de GERMAN en ENGLISH es SPANISH fr
/// FRENCH it ITALIAN ja JAPANESE ko KOREAN pl POLISH pt-BR BRAZILIAN_PORTUGUESE ru RUSSIAN tr TURKISH uk
/// UKRAINIAN zh-CN CHINA_CHINESE zh-TW TAIWAN_CHINESE
///
/// An locale string not in the list above will generate reports in English.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locale")]
public virtual string Locale { get; set; }
/// <summary>Number of reports that have been generated for the query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportCount")]
public virtual System.Nullable<int> ReportCount { get; set; }
/// <summary>Whether the latest report is currently running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("running")]
public virtual System.Nullable<bool> Running { get; set; }
/// <summary>Whether to send an email notification when a report is ready. Default to false.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sendNotification")]
public virtual System.Nullable<bool> SendNotification { get; set; }
/// <summary>List of email addresses which are sent email notifications when the report is finished. Separate
/// from sendNotification.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("shareEmailAddress")]
public virtual System.Collections.Generic.IList<string> ShareEmailAddress { get; set; }
/// <summary>Query title. It is used to name the reports generated from this query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Information on how frequently and when to run a query.</summary>
public class QuerySchedule : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Datetime to periodically run the query until.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTimeMs")]
public virtual System.Nullable<long> EndTimeMs { get; set; }
/// <summary>How often the query is run.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("frequency")]
public virtual string Frequency { get; set; }
/// <summary>Time of day at which a new report will be generated, represented as minutes past midnight. Range is
/// 0 to 1439. Only applies to scheduled reports.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextRunMinuteOfDay")]
public virtual System.Nullable<int> NextRunMinuteOfDay { get; set; }
/// <summary>Canonical timezone code for report generation time. Defaults to America/New_York.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextRunTimezoneCode")]
public virtual string NextRunTimezoneCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a report.</summary>
public class Report : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Key used to identify a report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual ReportKey Key { get; set; }
/// <summary>Report metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual ReportMetadata Metadata { get; set; }
/// <summary>Report parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("params")]
public virtual Parameters Params__ { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An explanation of a report failure.</summary>
public class ReportFailure : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Error code that shows why the report was not created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorCode")]
public virtual string ErrorCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Key used to identify a report.</summary>
public class ReportKey : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Query ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("queryId")]
public virtual System.Nullable<long> QueryId { get; set; }
/// <summary>Report ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportId")]
public virtual System.Nullable<long> ReportId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Report metadata.</summary>
public class ReportMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The path to the location in Google Cloud Storage where the report is stored.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("googleCloudStoragePath")]
public virtual string GoogleCloudStoragePath { get; set; }
/// <summary>The ending time for the data that is shown in the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")]
public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; }
/// <summary>The starting time for the data that is shown in the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")]
public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; }
/// <summary>Report status.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("status")]
public virtual ReportStatus Status { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Report status.</summary>
public class ReportStatus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If the report failed, this records the cause.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("failure")]
public virtual ReportFailure Failure { get; set; }
/// <summary>The time when this report either completed successfully or failed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("finishTimeMs")]
public virtual System.Nullable<long> FinishTimeMs { get; set; }
/// <summary>The file type of the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>The state of the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the upload status of a row in the request.</summary>
public class RowStatus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Whether the stored entity is changed as a result of upload.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("changed")]
public virtual System.Nullable<bool> Changed { get; set; }
/// <summary>Entity Id.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityId")]
public virtual System.Nullable<long> EntityId { get; set; }
/// <summary>Entity name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entityName")]
public virtual string EntityName { get; set; }
/// <summary>Reasons why the entity can't be uploaded.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errors")]
public virtual System.Collections.Generic.IList<string> Errors { get; set; }
/// <summary>Whether the entity is persisted.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("persisted")]
public virtual System.Nullable<bool> Persisted { get; set; }
/// <summary>Row number.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rowNumber")]
public virtual System.Nullable<int> RowNumber { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request to run a stored query to generate a report.</summary>
public class RunQueryRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Report data range used to generate the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dataRange")]
public virtual string DataRange { get; set; }
/// <summary>The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if
/// dataRange is CUSTOM_DATES and ignored otherwise.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")]
public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; }
/// <summary>The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required
/// if dataRange is CUSTOM_DATES and ignored otherwise.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")]
public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; }
/// <summary>Canonical timezone code for report data time. Defaults to America/New_York.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timezoneCode")]
public virtual string TimezoneCode { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request to upload line items.</summary>
public class UploadLineItemsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Set to true to get upload status without actually persisting the line items.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dryRun")]
public virtual System.Nullable<bool> DryRun { get; set; }
/// <summary>Format the line items are in. Default to CSV.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>Line items in CSV to upload. Refer to Entity Write File Format for more information on file
/// format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lineItems")]
public virtual string LineItems { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Upload line items response.</summary>
public class UploadLineItemsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Status of upload.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uploadStatus")]
public virtual UploadStatus UploadStatus { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the status of upload.</summary>
public class UploadStatus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Reasons why upload can't be completed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errors")]
public virtual System.Collections.Generic.IList<string> Errors { get; set; }
/// <summary>Per-row upload status.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rowStatus")]
public virtual System.Collections.Generic.IList<RowStatus> RowStatus { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using NationalInstruments.UI;
namespace TASKView.lib
{
public enum MoteFlags
{
MF_SAVED = 0x01, //!< bit to signify if node was autodiscovered
MF_DIRTY = 0x02, //!< bit to signify node has been altered
MF_PLOT = 0x04, //!< bit to enable plotting of node
}
#region MoteInfo class
/**
* The MoteInfo structure contains all meta data for a given node.
*
* @author Martin Turon
* @version 2004/4/13 mturon Initial version
*
* $Id: classMoteInfo.cs,v 1.12 2004/05/04 03:32:30 mturon Exp $
*/
public class MoteInfo
{
// ===================== CLASS DATA ==========================
public const ushort MF_NO_PARENT = 0xFFFF;
// ==================== INSTANCE DATA ========================
// The nodeid is actually the index for the Dictionary of motes
public ushort m_nodeid;
// Core information updated from the database every refresh
public ushort m_parent; //!< id of parent (0xffff = none)
public ushort m_epoch; //!< last epoch recorded
public string m_time; //!< time of last result recorded
// Static information stored in the task_mote_info table
public int m_x;
public int m_y;
public int m_z;
public byte[] m_calib; //!< calibration words for mote
// Client side annotations
public string m_name; //!< full name of mote
public Color m_color; //!< charting color for this node
public ScatterPlot[] m_plot; //!< number of plot, 0 if none
public MoteFlags m_flags;
// ======================= METHODS ===========================
public MoteInfo()
{
m_parent = MF_NO_PARENT;
m_color = Color.DarkGray;
m_plot = new ScatterPlot[3]{null, null, null};
}
} // class MoteInfo
#endregion
#region MoteTable class
/**
* A table to store static client information for all motes.
* Note: Always index the MoteTable with nodeid as ushort type.
*
* @author Martin Turon
* @version 2004/4/13 mturon Initial version
*/
public class MoteTable : SortedList
{
// ===================== CLASS DATA ==========================
private static Color[] m_colors;
// ======================= METHODS ===========================
public MoteTable()
{
// Assign the color table
InitColors(
0x7F0000FF, 0x7F00FF00, 0x7FFFFF00,
0x7F00FFFF, 0x7FFF0000, 0x7FFF00FF,
0x7FFF8080, 0x7F80FF80, 0x7F8080FF,
0x7FFFFF80, 0x7F80FFFF, 0x7FFF80FF,
0x7FCC4080, 0x7F40CC80, 0x7F4080CC,
0x7FCCCC40, 0x7F40CCCC, 0x7FCC40CC);
// Always initialize with a Gateway.
MoteInfo gatewayInfo = new MoteInfo();
gatewayInfo.m_nodeid = 0;
gatewayInfo.m_parent = 0;
gatewayInfo.m_name = "Gateway";
Add(gatewayInfo.m_nodeid, gatewayInfo);
}
/** Assign the array of default mote plotting colors. */
private void InitColors(params int[] colors)
{
int i = 0;
m_colors = new Color[colors.Length];
foreach (int color in colors)
{
m_colors[i++] = Color.FromArgb(color);
}
}
/** Attach this DataGrid to the current database. */
public void Load()
{
OdbcManager db = theOdbcManager.Instance;
db.Connect();
DataSet dSet = db.CreateDataSet(db.GetMoteInfoCommand());
db.Disconnect();
this.Clear();
if (null == dSet) return;
MoteInfo moteInfo;
foreach (DataRow dRow in dSet.Tables[0].Rows)
{
ushort nodeid = Convert.ToUInt16(dRow["mote_id"].ToString());
bool exists = this.ContainsKey(nodeid);
if (!exists)
{
moteInfo = new MoteInfo();
moteInfo.m_nodeid = nodeid;
moteInfo.m_name = "[S]";
byte[] nameBytes = (byte[])dRow["moteinfo"];
for (int i = 0; i < nameBytes.Length; i++)
{
char c = Convert.ToChar(nameBytes[i]);
if (c == 0) break;
moteInfo.m_name += c;
}
}
else
{
moteInfo = (MoteInfo)this[nodeid];
moteInfo.m_name = "[S]" + moteInfo.m_name;
}
moteInfo.m_x = Convert.ToInt32(dRow["x_coord"].ToString());
moteInfo.m_y = Convert.ToInt32(dRow["y_coord"].ToString());
moteInfo.m_z = Convert.ToInt32(dRow["z_coord"].ToString());
moteInfo.m_color = m_colors[nodeid % m_colors.Length];
moteInfo.m_flags = MoteFlags.MF_SAVED;
//moteInfo.m_calib = (byte[])dRow["calib"];
if (!exists) Add(nodeid, moteInfo);
}
Update();
}
public void Update()
{
OdbcManager db = theOdbcManager.Instance;
db.Connect();
DataSet dSet = db.CreateDataSet(db.GetLastResultCommand());
db.Disconnect();
try
{
foreach (DataRow dRow in dSet.Tables[0].Rows)
{
try
{
string nodenum = dRow["nodeid"].ToString();
if ("" == nodenum) continue; // Ignore null nodes
ushort nodeid = Convert.ToUInt16(nodenum);
//if (0 == nodeid) continue; // Ignore gateway
MoteInfo moteInfo;
if (this.ContainsKey(nodeid))
{
// Update the mote with latest parent, epoch, and result time
moteInfo = (MoteInfo)this[nodeid];
// Stuff name until casting of byte[] to string works.
moteInfo.m_name = "[R]" + moteInfo.m_name;
}
else
{
// This mote is reporting data, but isn't saved yet.
moteInfo = new MoteInfo();
moteInfo.m_nodeid = nodeid;
moteInfo.m_name = "[N] Node " + nodeid;
moteInfo.m_flags = 0;
/// TODO: testing only...
theOdbcManager.Instance.ErrorLog("\nFixed position for node " + nodeid);
moteInfo.m_x = 10;
moteInfo.m_y = 10;
Add(nodeid, moteInfo);
}
// Common update for both new and existing nodes.
moteInfo.m_parent = Convert.ToUInt16(dRow["parent"].ToString());
moteInfo.m_epoch = Convert.ToUInt16(dRow["epoch"].ToString());
moteInfo.m_time = dRow["result_time"].ToString();
}
catch (Exception ex)
{
theOdbcManager.Instance.ErrorLog("\n" + ex.ToString());
}
}
}
catch (Exception ex)
{
theOdbcManager.Instance.ErrorLog("\n" + ex.ToString());
}
}
} // class MoteTable
#endregion
#region theMoteTable singleton class
/**
* Singleton version of MoteTable
*
* @version 2004/4/13 mturon Initial version
*/
public sealed class theMoteTable : MoteTable
{
/** The internal singular instance of the OdbcManager. */
private static readonly theMoteTable instance = new theMoteTable();
private theMoteTable() {}
/** The read-only Instance property returns the one and only instance. */
public static theMoteTable Instance
{
get { return instance; }
}
} // class theMoteTable
#endregion
} // namespace TASKView.lib
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Gateway Provider Payment Method Type
///<para>SObject Name: GtwyProvPaymentMethodType</para>
///<para>Custom Object: False</para>
///</summary>
public class SfGtwyProvPaymentMethodType : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "GtwyProvPaymentMethodType"; }
}
///<summary>
/// Gateway Provider Payment Method Type ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Name
/// <para>Name: DeveloperName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "developerName")]
public string DeveloperName { get; set; }
///<summary>
/// Master Language
/// <para>Name: Language</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "language")]
public string Language { get; set; }
///<summary>
/// Label
/// <para>Name: MasterLabel</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "masterLabel")]
public string MasterLabel { get; set; }
///<summary>
/// Namespace Prefix
/// <para>Name: NamespacePrefix</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "namespacePrefix")]
[Updateable(false), Createable(false)]
public string NamespacePrefix { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Last Viewed Date
/// <para>Name: LastViewedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastViewedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastViewedDate { get; set; }
///<summary>
/// Payment Gateway Provider ID
/// <para>Name: PaymentGatewayProviderId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "paymentGatewayProviderId")]
public string PaymentGatewayProviderId { get; set; }
///<summary>
/// ReferenceTo: PaymentGatewayProvider
/// <para>RelationshipName: PaymentGatewayProvider</para>
///</summary>
[JsonProperty(PropertyName = "paymentGatewayProvider")]
[Updateable(false), Createable(false)]
public SfPaymentGatewayProvider PaymentGatewayProvider { get; set; }
///<summary>
/// Comments
/// <para>Name: Comments</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "comments")]
public string Comments { get; set; }
///<summary>
/// Payment Method Type
/// <para>Name: PaymentMethodType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "paymentMethodType")]
public string PaymentMethodType { get; set; }
///<summary>
/// Gateway Provider Payment Method Type
/// <para>Name: GtwyProviderPaymentMethodType</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gtwyProviderPaymentMethodType")]
public string GtwyProviderPaymentMethodType { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Data;
namespace Serenity.Data
{
public abstract partial class Field : IFieldWithJoinInfo
{
private string autoTextKey;
internal LocalText caption;
internal string expression;
private RowFieldsBase fields;
internal FieldFlags flags;
private string foreignTable;
private string foreignField;
internal int index;
internal Join join;
internal string joinAlias;
internal string name;
internal string origin;
internal string propertyName;
internal HashSet<string> referencedAliases;
private readonly int size;
private readonly FieldType type;
internal object defaultValue;
internal SelectLevel minSelectLevel;
internal int naturalOrder;
internal string textualField;
private Criteria criteria;
protected Field(ICollection<Field> fields, FieldType type, string name, LocalText caption, int size, FieldFlags flags)
{
this.name = name;
expression = "T0." + name;
this.size = size;
this.flags = flags;
this.type = type;
index = -1;
minSelectLevel = SelectLevel.Default;
naturalOrder = 0;
this.caption = caption;
if (fields != null)
fields.Add(this);
}
public RowFieldsBase Fields
{
get { return fields; }
internal set { fields = value; }
}
public int Index
{
get { return index; }
internal set { index = value; }
}
public string Name
{
get { return name; }
}
public FieldType Type
{
get { return type; }
}
public LocalText Caption
{
get { return caption; }
set { caption = value; }
}
public object DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; }
}
public HashSet<string> ReferencedAliases
{
get
{
return referencedAliases;
}
set
{
referencedAliases = value;
}
}
public string Title
{
get
{
if (ReferenceEquals(null, caption))
{
if (autoTextKey == null)
autoTextKey = "Db." + this.Fields.LocalTextPrefix + "." + (propertyName ?? name);
return LocalText.TryGet(autoTextKey) ?? (propertyName ?? name);
}
else
return caption.ToString();
}
}
public int Size
{
get { return size; }
}
public int Scale { get; set; }
public FieldFlags Flags
{
get { return flags; }
set { flags = value; }
}
public string PropertyName
{
get { return propertyName; }
set { propertyName = value; }
}
public object[] CustomAttributes { get; set; }
protected Exception JsonUnexpectedToken(JsonReader reader)
{
throw new JsonSerializationException("Unexpected token when deserializing row: " + reader.TokenType);
}
public void CopyNoAssignment(Row source, Row target)
{
Copy(source, target);
target.ClearAssignment(this);
}
public string Expression
{
get { return expression; }
set
{
value = value.TrimToNull();
if (expression != value)
{
expression = value;
referencedAliases = null;
joinAlias = null;
origin = null;
join = null;
if (value != null)
{
if (String.Compare(expression, "T0." + name, StringComparison.OrdinalIgnoreCase) == 0)
{
flags ^= FieldFlags.Calculated;
flags ^= FieldFlags.Foreign;
expression = "T0." + name;
return;
}
var aliases = JoinAliasLocator.Locate(value);
if (aliases != null && aliases.Count > 0)
{
referencedAliases = aliases;
if (aliases.Count == 1)
{
var enumerator = aliases.GetEnumerator();
enumerator.MoveNext();
var theJoin = enumerator.Current;
if (theJoin.ToLowerInvariant() == "t0")
flags = (FieldFlags)(flags ^ FieldFlags.Foreign) | FieldFlags.Calculated;
else
{
flags = flags | FieldFlags.Foreign;
var split = expression.Split('.');
if (split.Length == 2 &&
split[0] == theJoin &&
SqlSyntax.IsValidIdentifier(split[1]))
{
joinAlias = theJoin;
origin = split[1];
}
else
flags = flags | FieldFlags.Calculated;
}
}
else
flags = flags | FieldFlags.Calculated | FieldFlags.Foreign;
}
}
else
{
expression = "T0." + name;
flags ^= FieldFlags.Calculated;
flags ^= FieldFlags.Foreign;
}
}
}
}
public string JoinAlias
{
get { return joinAlias; }
}
public Join Join
{
get
{
if (join == null &&
joinAlias != null)
{
Join theJoin;
if (fields.Joins.TryGetValue(joinAlias, out theJoin))
join = theJoin;
}
return join;
}
}
public string Origin
{
get { return origin; }
}
public string ForeignTable
{
get { return foreignTable; }
set { foreignTable = value.TrimToNull(); }
}
public string ForeignField
{
get { return foreignField; }
set { foreignField = value.TrimToNull(); }
}
public Join ForeignJoinAlias
{
get; set;
}
public SelectLevel MinSelectLevel
{
get { return minSelectLevel; }
set { minSelectLevel = value; }
}
public int NaturalOrder
{
get { return naturalOrder; }
set { naturalOrder = value; }
}
public string TextualField
{
get { return textualField; }
set { textualField = value; }
}
public LeftJoin ForeignJoin(Int32? foreignIndex = null)
{
if (ForeignTable.IsNullOrEmpty())
throw new ArgumentNullException("ForeignTable");
string foreignJoin;
if (foreignIndex == null)
{
foreignJoin = Name;
if (foreignJoin.EndsWith("Id", StringComparison.Ordinal))
foreignJoin = foreignJoin.Substring(0, foreignJoin.Length - 2);
else if (foreignJoin.EndsWith("_ID", StringComparison.OrdinalIgnoreCase))
foreignJoin = foreignJoin.Substring(0, foreignJoin.Length - 3);
foreignJoin = "j" + foreignJoin;
}
else
{
foreignJoin = foreignIndex.Value.TableAlias();
}
var joinKeyField = ForeignField ?? Name;
var sourceAlias = "T0";
var sourceKeyField = Name;
var join = new LeftJoin(this.Fields.Joins, ForeignTable, foreignJoin,
new Criteria(foreignJoin, joinKeyField) == new Criteria(sourceAlias, sourceKeyField));
this.ForeignJoinAlias = join;
return join;
}
protected internal virtual void OnRowInitialization()
{
}
protected void CheckUnassignedRead(Row row)
{
if (row == null)
throw new ArgumentNullException("row");
if (!row.tracking)
return;
if (!row.trackWithChecks)
return;
if (row.IsAssigned(this))
return;
if (!this.GetIsNull(row))
return;
throw new InvalidOperationException(String.Format(
"{0} field on {1} is read before assigned a value!", this.Name, row.GetType().Name));
}
public abstract void ValueToJson(JsonWriter writer, Row row, JsonSerializer serializer);
public abstract void ValueFromJson(JsonReader reader, Row row, JsonSerializer serializer);
public abstract void Copy(Row source, Row target);
public abstract void GetFromReader(IDataReader reader, int index, Row row);
public abstract Type ValueType { get; }
public abstract object ConvertValue(object source, IFormatProvider provider);
public abstract int IndexCompare(Row row1, Row row2);
public abstract object AsObject(Row row);
public abstract void AsObject(Row row, object value);
protected abstract bool GetIsNull(Row row);
public bool IsNull(Row row)
{
CheckUnassignedRead(row);
return GetIsNull(row);
}
public Criteria Criteria
{
get
{
if (!Object.ReferenceEquals(criteria, null))
return criteria;
criteria = new Criteria(this);
return criteria;
}
}
IDictionary<string, Join> IFieldWithJoinInfo.Joins
{
get { return Fields.Joins; }
}
public override string ToString()
{
return this.Expression;
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using PactNet.Models;
namespace PactNet.Core
{
internal class PactCoreHost<T> : IPactCoreHost where T : IPactCoreHostConfig
{
protected readonly Process _process;
private readonly IPactCoreHostConfig _config;
public PactCoreHost(T config)
{
_config = config;
var expectedPackage = string.Empty;
#if USE_NET4X
var pactCoreDir = $"{Constants.BuildDirectory}{Path.DirectorySeparatorChar}"; //OS specific version will be appended
pactCoreDir += "pact-win32";
expectedPackage = "PactNet.Windows";
#else
var pactCoreDir = $"{Constants.BuildDirectory}{Path.DirectorySeparatorChar}"; //OS specific version will be appended
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
{
pactCoreDir += "pact-win32";
expectedPackage = "PactNet.Windows";
}
else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
{
pactCoreDir += "pact-osx";
expectedPackage = "PactNet.OSX";
}
else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux) &&
System.Runtime.InteropServices.RuntimeInformation.OSArchitecture == System.Runtime.InteropServices.Architecture.X86)
{
pactCoreDir += "pact-linux-x86";
expectedPackage = "PactNet.Linux.x86";
}
else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux) &&
System.Runtime.InteropServices.RuntimeInformation.OSArchitecture == System.Runtime.InteropServices.Architecture.X64)
{
pactCoreDir += "pact-linux-x86_64";
expectedPackage = "PactNet.Linux.x64";
}
else
{
throw new PactFailureException("Sorry your current OS platform or architecture is not supported");
}
#endif
if (!Directory.Exists(pactCoreDir))
{
throw new PactFailureException($"Please install the relevant platform and architecture specific PactNet dependency from Nuget. Based on your current setup you should install '{expectedPackage}'.");
//TODO: Fall back to using the locally installed ruby and packaged assets
}
var configPath = $"{pactCoreDir}{Path.DirectorySeparatorChar}config.json";
var platformConfig = JsonConvert.DeserializeObject<PlatformCoreConfig>(File.ReadAllText(configPath));
var startInfo = new ProcessStartInfo
{
#if USE_NET4X
WindowStyle = ProcessWindowStyle.Hidden,
#endif
FileName = ReplaceConfigParams(platformConfig.FileName, pactCoreDir, _config.Script),
Arguments = $"{ReplaceConfigParams(platformConfig.Arguments, pactCoreDir, _config.Script)} {_config.Arguments}",
UseShellExecute = false,
RedirectStandardInput = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
if (platformConfig.Environment != null)
{
foreach (var envVar in platformConfig.Environment)
{
var value = ReplaceConfigParams(envVar.Value, pactCoreDir, _config.Script);
#if USE_NET4X
startInfo.EnvironmentVariables[envVar.Key] = value;
#else
startInfo.Environment[envVar.Key] = value;
#endif
}
}
if(config.Environment != null)
{
foreach (var envVar in config.Environment)
{
#if USE_NET4X
startInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
#else
startInfo.Environment[envVar.Key] = envVar.Value;
#endif
}
}
_process = new Process
{
StartInfo = startInfo
};
#if USE_NET4X
AppDomain.CurrentDomain.DomainUnload += (o, e) => Stop();
#else
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += context => Stop();
#endif
}
public void Start()
{
_process.OutputDataReceived += WriteLineToOutput;
_process.ErrorDataReceived += WriteLineToOutput;
var success = _process.Start();
if (!success)
{
throw new PactFailureException("Could not start the Pact Core Host");
}
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
if (_config.WaitForExit)
{
_process.WaitForExit();
if (_process.ExitCode != 0)
{
throw new PactFailureException("Pact verification failed. See output for details. \nIf the output is empty please provide a custom config.Outputters (IOutput) for your test framework, as we couldn't write to the console.");
}
}
}
public void Stop()
{
bool hasExited;
try
{
hasExited = _process.HasExited;
}
catch (InvalidOperationException)
{
hasExited = true;
}
if (!hasExited)
{
try
{
_process.OutputDataReceived -= WriteLineToOutput;
_process.ErrorDataReceived -= WriteLineToOutput;
_process.CancelOutputRead();
_process.CancelErrorRead();
_process.Kill();
_process.Dispose();
}
catch (Exception)
{
throw new PactFailureException("Could not terminate the Pact Core Host, please manually kill the 'Ruby interpreter' process");
}
}
}
private void WriteLineToOutput(object sender, DataReceivedEventArgs eventArgs)
{
if (eventArgs.Data != null)
{
WriteToOutputters(Regex.Replace(eventArgs.Data, @"\e\[(\d+;)*(\d+)?[ABCDHJKfmsu]", ""));
}
}
private void WriteToOutputters(string line)
{
if (_config.Outputters != null && _config.Outputters.Any())
{
foreach (var output in _config.Outputters)
{
output.WriteLine(line);
}
}
}
private string ReplaceConfigParams(string input, string pactCoreDir, string script)
{
return !string.IsNullOrEmpty(input) ?
input.Replace("{pactCoreDir}", pactCoreDir).Replace("{script}", script) :
string.Empty;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using Microsoft.Extensions.Primitives;
namespace Microsoft.Net.Http.Headers
{
/// <summary>
/// Represents a byte range in a Range header value.
/// <para>
/// The <see cref="RangeItemHeaderValue"/> class provides support for a byte range in a <c>Range</c> as defined
/// in <see href="https://tools.ietf.org/html/rfc2616">RFC 2616</see>.
/// </para>
/// </summary>
public class RangeItemHeaderValue
{
private readonly long? _from;
private readonly long? _to;
/// <summary>
/// Initializes a new instance of the <see cref="RangeItemHeaderValue"/> class.
/// </summary>
/// <param name="from">The position at which to start sending data.</param>
/// <param name="to">The position at which to stop sending data.</param>
public RangeItemHeaderValue(long? from, long? to)
{
if (!from.HasValue && !to.HasValue)
{
throw new ArgumentException("Invalid header range.");
}
if (from.HasValue && (from.GetValueOrDefault() < 0))
{
throw new ArgumentOutOfRangeException(nameof(from));
}
if (to.HasValue && (to.GetValueOrDefault() < 0))
{
throw new ArgumentOutOfRangeException(nameof(to));
}
if (from.HasValue && to.HasValue && (from.GetValueOrDefault() > to.GetValueOrDefault()))
{
throw new ArgumentOutOfRangeException(nameof(from));
}
_from = from;
_to = to;
}
/// <summary>
/// Gets the position at which to start sending data.
/// </summary>
public long? From
{
get { return _from; }
}
/// <summary>
/// Gets the position at which to stop sending data.
/// </summary>
public long? To
{
get { return _to; }
}
/// <inheritdoc />
public override string ToString()
{
if (!_from.HasValue)
{
return "-" + _to.GetValueOrDefault().ToString(NumberFormatInfo.InvariantInfo);
}
else if (!_to.HasValue)
{
return _from.GetValueOrDefault().ToString(NumberFormatInfo.InvariantInfo) + "-";
}
return _from.GetValueOrDefault().ToString(NumberFormatInfo.InvariantInfo) + "-" +
_to.GetValueOrDefault().ToString(NumberFormatInfo.InvariantInfo);
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is RangeItemHeaderValue other && ((_from == other._from) && (_to == other._to));
}
/// <inheritdoc />
public override int GetHashCode()
{
if (!_from.HasValue)
{
return _to.GetValueOrDefault().GetHashCode();
}
else if (!_to.HasValue)
{
return _from.GetValueOrDefault().GetHashCode();
}
return _from.GetValueOrDefault().GetHashCode() ^ _to.GetValueOrDefault().GetHashCode();
}
// Returns the length of a range list. E.g. "1-2, 3-4, 5-6" adds 3 ranges to 'rangeCollection'. Note that empty
// list segments are allowed, e.g. ",1-2, , 3-4,,".
internal static int GetRangeItemListLength(
StringSegment input,
int startIndex,
ICollection<RangeItemHeaderValue> rangeCollection)
{
Contract.Requires(startIndex >= 0);
Contract.Ensures((Contract.Result<int>() == 0) || (rangeCollection.Count > 0),
"If we can parse the string, then we expect to have at least one range item.");
if ((StringSegment.IsNullOrEmpty(input)) || (startIndex >= input.Length))
{
return 0;
}
// Empty segments are allowed, so skip all delimiter-only segments (e.g. ", ,").
var current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out var separatorFound);
// It's OK if we didn't find leading separator characters. Ignore 'separatorFound'.
if (current == input.Length)
{
return 0;
}
while (true)
{
var rangeLength = GetRangeItemLength(input, current, out var range);
if (rangeLength == 0)
{
return 0;
}
rangeCollection!.Add(range!);
current = current + rangeLength;
current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound);
// If the string is not consumed, we must have a delimiter, otherwise the string is not a valid
// range list.
if ((current < input.Length) && !separatorFound)
{
return 0;
}
if (current == input.Length)
{
return current - startIndex;
}
}
}
internal static int GetRangeItemLength(StringSegment input, int startIndex, out RangeItemHeaderValue? parsedValue)
{
Contract.Requires(startIndex >= 0);
// This parser parses number ranges: e.g. '1-2', '1-', '-2'.
parsedValue = null;
if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespaces. If not, we'll return 0.
var current = startIndex;
// Try parse the first value of a value pair.
var fromStartIndex = current;
var fromLength = HttpRuleParser.GetNumberLength(input, current, false);
if (fromLength > HttpRuleParser.MaxInt64Digits)
{
return 0;
}
current = current + fromLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// After the first value, the '-' character must follow.
if ((current == input.Length) || (input[current] != '-'))
{
// We need a '-' character otherwise this can't be a valid range.
return 0;
}
current++; // skip the '-' character
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
var toStartIndex = current;
var toLength = 0;
// If we didn't reach the end of the string, try parse the second value of the range.
if (current < input.Length)
{
toLength = HttpRuleParser.GetNumberLength(input, current, false);
if (toLength > HttpRuleParser.MaxInt64Digits)
{
return 0;
}
current = current + toLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
if ((fromLength == 0) && (toLength == 0))
{
return 0; // At least one value must be provided in order to be a valid range.
}
// Try convert first value to int64
long from = 0;
if ((fromLength > 0) && !HeaderUtilities.TryParseNonNegativeInt64(input.Subsegment(fromStartIndex, fromLength), out from))
{
return 0;
}
// Try convert second value to int64
long to = 0;
if ((toLength > 0) && !HeaderUtilities.TryParseNonNegativeInt64(input.Subsegment(toStartIndex, toLength), out to))
{
return 0;
}
// 'from' must not be greater than 'to'
if ((fromLength > 0) && (toLength > 0) && (from > to))
{
return 0;
}
parsedValue = new RangeItemHeaderValue((fromLength == 0 ? (long?)null : (long?)from),
(toLength == 0 ? (long?)null : (long?)to));
return current - startIndex;
}
}
}
| |
/*
* 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 Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Data;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.AssetService
{
/// <summary>
/// A de-duplicating asset service.
/// </summary>
public class XAssetService : XAssetServiceBase, IAssetService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected static XAssetService m_RootInstance;
public XAssetService(IConfigSource config) : this(config, "AssetService") {}
public XAssetService(IConfigSource config, string configName) : base(config, configName)
{
if (m_RootInstance == null)
{
m_RootInstance = this;
if (m_AssetLoader != null)
{
IConfig assetConfig = config.Configs[configName];
if (assetConfig == null)
throw new Exception("No AssetService configuration");
string loaderArgs = assetConfig.GetString("AssetLoaderArgs", String.Empty);
bool assetLoaderEnabled = assetConfig.GetBoolean("AssetLoaderEnabled", true);
if (assetLoaderEnabled && !HasChainedAssetService)
{
m_log.DebugFormat("[XASSET SERVICE]: Loading default asset set from {0}", loaderArgs);
m_AssetLoader.ForEachDefaultXmlAsset(
loaderArgs,
a =>
{
AssetBase existingAsset = Get(a.ID);
// AssetMetadata existingMetadata = GetMetadata(a.ID);
if (existingAsset == null || Util.SHA1Hash(existingAsset.Data) != Util.SHA1Hash(a.Data))
{
// m_log.DebugFormat("[ASSET]: Storing {0} {1}", a.Name, a.ID);
Store(a);
}
});
}
m_log.Debug("[XASSET SERVICE]: Local asset service enabled");
}
}
}
public virtual AssetBase Get(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset for {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
{
m_log.WarnFormat("[XASSET SERVICE]: Could not parse requested asset id {0}", id);
return null;
}
try
{
AssetBase asset = m_Database.GetAsset(assetID);
if (asset != null)
{
return asset;
}
else if (HasChainedAssetService)
{
asset = m_ChainedAssetService.Get(id);
if (asset != null)
MigrateFromChainedService(asset);
return asset;
}
return null;
}
catch (Exception e)
{
m_log.ErrorFormat("[XASSET SERVICE]: Exception getting asset {0} {1}", assetID, e);
return null;
}
}
public virtual AssetBase GetCached(string id)
{
return Get(id);
}
public virtual AssetMetadata GetMetadata(string id)
{
// m_log.DebugFormat("[XASSET SERVICE]: Get asset metadata for {0}", id);
AssetBase asset = Get(id);
if (asset != null)
return asset.Metadata;
else
return null;
}
public virtual byte[] GetData(string id)
{
// m_log.DebugFormat("[XASSET SERVICE]: Get asset data for {0}", id);
AssetBase asset = Get(id);
if (asset != null)
return asset.Data;
else
return null;
}
public virtual bool Get(string id, Object sender, AssetRetrieved handler)
{
//m_log.DebugFormat("[XASSET SERVICE]: Get asset async {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
AssetBase asset = Get(id);
//m_log.DebugFormat("[XASSET SERVICE]: Got asset {0}", asset);
handler(id, sender, asset);
return true;
}
public virtual string Store(AssetBase asset)
{
if (!m_Database.ExistsAsset(asset.FullID))
{
// m_log.DebugFormat(
// "[XASSET SERVICE]: Storing asset {0} {1}, bytes {2}", asset.Name, asset.FullID, asset.Data.Length);
m_Database.StoreAsset(asset);
}
// else
// {
// m_log.DebugFormat(
// "[XASSET SERVICE]: Not storing asset {0} {1}, bytes {2} as it already exists", asset.Name, asset.FullID, asset.Data.Length);
// }
return asset.ID;
}
public bool UpdateContent(string id, byte[] data)
{
return false;
}
public virtual bool Delete(string id)
{
// m_log.DebugFormat("[XASSET SERVICE]: Deleting asset {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
if (HasChainedAssetService)
m_ChainedAssetService.Delete(id);
return m_Database.Delete(id);
}
private void MigrateFromChainedService(AssetBase asset)
{
Store(asset);
m_ChainedAssetService.Delete(asset.ID);
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
namespace Oranikle.DesignBase.UI.Docking
{
internal class VS2005DockPaneStrip : DockPaneStripBase
{
private class TabVS2005 : Tab
{
public TabVS2005(IDockContent content)
: base(content)
{
}
private int m_tabX;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
private int m_maxWidth;
public int MaxWidth
{
get { return m_maxWidth; }
set { m_maxWidth = value; }
}
private bool m_flag;
protected internal bool Flag
{
get { return m_flag; }
set { m_flag = value; }
}
}
protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2005(content);
}
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image0, m_image1;
public InertButton(Bitmap image0, Bitmap image1)
: base()
{
m_image0 = image0;
m_image1 = image1;
}
private int m_imageCategory = 0;
public int ImageCategory
{
get { return m_imageCategory; }
set
{
if (m_imageCategory == value)
return;
m_imageCategory = value;
Invalidate();
}
}
public override Bitmap Image
{
get { return ImageCategory == 0 ? m_image0 : m_image1; }
}
}
#region consts
private const int _ToolWindowStripGapTop = 0;
private const int _ToolWindowStripGapBottom = 1;
private const int _ToolWindowStripGapLeft = 0;
private const int _ToolWindowStripGapRight = 0;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 3;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 2;
private const int _ToolWindowImageGapRight = 0;
private const int _ToolWindowTextGapRight = 3;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentStripGapTop = 0;
private const int _DocumentStripGapBottom = 1;
private const int _DocumentTabMaxWidth = 300;
private const int _DocumentButtonGapTop = 4;
private const int _DocumentButtonGapBottom = 4;
private const int _DocumentButtonGapBetween = 0;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 3;
private const int _DocumentTabGapLeft = 3;
private const int _DocumentTabGapRight = 3;
private const int _DocumentIconGapBottom = 2;
private const int _DocumentIconGapLeft = 8;
private const int _DocumentIconGapRight = 0;
private const int _DocumentIconHeight = 16;
private const int _DocumentIconWidth = 16;
private const int _DocumentTextGapRight = 3;
#endregion
private static Bitmap _imageButtonClose;
private static Bitmap ImageButtonClose
{
get
{
if (_imageButtonClose == null)
_imageButtonClose = Resources.DockPane_Close;
return _imageButtonClose;
}
}
private InertButton m_buttonClose;
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private static Bitmap _imageButtonWindowList;
private static Bitmap ImageButtonWindowList
{
get
{
if (_imageButtonWindowList == null)
_imageButtonWindowList = Resources.DockPane_Option;
return _imageButtonWindowList;
}
}
private static Bitmap _imageButtonWindowListOverflow;
private static Bitmap ImageButtonWindowListOverflow
{
get
{
if (_imageButtonWindowListOverflow == null)
_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow;
return _imageButtonWindowListOverflow;
}
}
private InertButton m_buttonWindowList;
private InertButton ButtonWindowList
{
get
{
if (m_buttonWindowList == null)
{
m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow);
m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect);
m_buttonWindowList.Click += new EventHandler(WindowList_Click);
Controls.Add(m_buttonWindowList);
}
return m_buttonWindowList;
}
}
private static GraphicsPath GraphicsPath
{
get { return VS2005AutoHideStrip.GraphicsPath; }
}
private IContainer m_components;
private ToolTip m_toolTip;
private IContainer Components
{
get { return m_components; }
}
#region Customizable Properties
private static int ToolWindowStripGapTop
{
get { return _ToolWindowStripGapTop; }
}
private static int ToolWindowStripGapBottom
{
get { return _ToolWindowStripGapBottom; }
}
private static int ToolWindowStripGapLeft
{
get { return _ToolWindowStripGapLeft; }
}
private static int ToolWindowStripGapRight
{
get { return _ToolWindowStripGapRight; }
}
private static int ToolWindowImageHeight
{
get { return _ToolWindowImageHeight; }
}
private static int ToolWindowImageWidth
{
get { return _ToolWindowImageWidth; }
}
private static int ToolWindowImageGapTop
{
get { return _ToolWindowImageGapTop; }
}
private static int ToolWindowImageGapBottom
{
get { return _ToolWindowImageGapBottom; }
}
private static int ToolWindowImageGapLeft
{
get { return _ToolWindowImageGapLeft; }
}
private static int ToolWindowImageGapRight
{
get { return _ToolWindowImageGapRight; }
}
private static int ToolWindowTextGapRight
{
get { return _ToolWindowTextGapRight; }
}
private static int ToolWindowTabSeperatorGapTop
{
get { return _ToolWindowTabSeperatorGapTop; }
}
private static int ToolWindowTabSeperatorGapBottom
{
get { return _ToolWindowTabSeperatorGapBottom; }
}
private static string _toolTipClose;
private static string ToolTipClose
{
get
{
if (_toolTipClose == null)
_toolTipClose = Strings.DockPaneStrip_ToolTipClose;
return _toolTipClose;
}
}
private static string _toolTipSelect;
private static string ToolTipSelect
{
get
{
if (_toolTipSelect == null)
_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList;
return _toolTipSelect;
}
}
private TextFormatFlags ToolWindowTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
else
return textFormat;
}
}
private static int DocumentStripGapTop
{
get { return _DocumentStripGapTop; }
}
private static int DocumentStripGapBottom
{
get { return _DocumentStripGapBottom; }
}
private TextFormatFlags DocumentTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter |
TextFormatFlags.HorizontalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft;
else
return textFormat;
}
}
private static int DocumentTabMaxWidth
{
get { return _DocumentTabMaxWidth; }
}
private static int DocumentButtonGapTop
{
get { return _DocumentButtonGapTop; }
}
private static int DocumentButtonGapBottom
{
get { return _DocumentButtonGapBottom; }
}
private static int DocumentButtonGapBetween
{
get { return _DocumentButtonGapBetween; }
}
private static int DocumentButtonGapRight
{
get { return _DocumentButtonGapRight; }
}
private static int DocumentTabGapTop
{
get { return _DocumentTabGapTop; }
}
private static int DocumentTabGapLeft
{
get { return _DocumentTabGapLeft; }
}
private static int DocumentTabGapRight
{
get { return _DocumentTabGapRight; }
}
private static int DocumentIconGapBottom
{
get { return _DocumentIconGapBottom; }
}
private static int DocumentIconGapLeft
{
get { return _DocumentIconGapLeft; }
}
private static int DocumentIconGapRight
{
get { return _DocumentIconGapRight; }
}
private static int DocumentIconWidth
{
get { return _DocumentIconWidth; }
}
private static int DocumentIconHeight
{
get { return _DocumentIconHeight; }
}
private static int DocumentTextGapRight
{
get { return _DocumentTextGapRight; }
}
private static Pen PenToolWindowTabBorder
{
get { return SystemPens.GrayText; }
}
private static Pen PenDocumentTabActiveBorder
{
get { return SystemPens.ControlDarkDark; }
}
private static Pen PenDocumentTabInactiveBorder
{
get { return SystemPens.GrayText; }
}
#endregion
public VS2005DockPaneStrip(DockPane pane) : base(pane)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
SuspendLayout();
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_selectMenu = new ContextMenuStrip(Components);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Components.Dispose();
if (m_boldFont != null)
{
m_boldFont.Dispose();
m_boldFont = null;
}
}
base.Dispose (disposing);
}
private static Font TextFont
{
get { return SystemInformation.MenuFont; }
}
private Font m_font;
private Font m_boldFont;
private Font BoldFont
{
get
{
if (IsDisposed)
return null;
if (m_boldFont == null)
{
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
else if (m_font != TextFont)
{
m_boldFont.Dispose();
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
return m_boldFont;
}
}
private int m_startDisplayingTab = 0;
private int StartDisplayingTab
{
get { return m_startDisplayingTab; }
set
{
m_startDisplayingTab = value;
Invalidate();
}
}
private int m_endDisplayingTab = 0;
private int EndDisplayingTab
{
get { return m_endDisplayingTab; }
set { m_endDisplayingTab = value; }
}
private int m_firstDisplayingTab = 0;
private int FirstDisplayingTab
{
get { return m_firstDisplayingTab; }
set { m_firstDisplayingTab = value; }
}
private bool m_documentTabsOverflow = false;
private bool DocumentTabsOverflow
{
set
{
if (m_documentTabsOverflow == value)
return;
m_documentTabsOverflow = value;
if (value)
ButtonWindowList.ImageCategory = 1;
else
ButtonWindowList.ImageCategory = 0;
}
}
protected internal override int MeasureHeight()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return MeasureHeight_ToolWindow();
else
return MeasureHeight_Document();
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
return 0;
int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom)
+ ToolWindowStripGapTop + ToolWindowStripGapBottom;
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(TextFont.Height + DocumentTabGapTop,
ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom)
+ DocumentStripGapBottom + DocumentStripGapTop;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rect = TabsRectangle;
if (Appearance == DockPane.AppearanceStyle.Document)
{
rect.X -= DocumentTabGapLeft;
// Add these values back in so that the DockStrip color is drawn
// beneath the close button and window list button.
rect.Width += DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width;
// It is possible depending on the DockPanel DocumentStyle to have
// a Document without a DockStrip.
if (rect.Width > 0 && rect.Height > 0)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode))
{
e.Graphics.FillRectangle(brush, rect);
}
}
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode))
{
e.Graphics.FillRectangle(brush, rect);
}
}
base.OnPaint (e);
CalculateTabs();
if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null)
{
if (EnsureDocumentTabVisible(DockPane.ActiveContent, false))
CalculateTabs();
}
DrawTabStrip(e.Graphics);
}
protected override void OnRefreshChanges()
{
SetInertButtons();
Invalidate();
}
protected internal override GraphicsPath GetOutline(int index)
{
if (Appearance == DockPane.AppearanceStyle.Document)
return GetOutline_Document(index);
else
return GetOutline_ToolWindow(index);
}
private GraphicsPath GetOutline_Document(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.X -= rectTab.Height / 2;
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true);
path.AddPath(pathTab, true);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top);
}
else
{
path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom);
path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom);
path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
}
return path;
}
private GraphicsPath GetOutline_ToolWindow(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
int y = rectTab.Top;
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true);
path.AddPath(pathTab, true);
path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top);
return path;
}
private void CalculateTabs()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
CalculateTabs_ToolWindow();
else
CalculateTabs_Document();
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (TabVS2005 tab in Tabs)
{
tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = totalWidth / countTabs;
int remainedTabs = countTabs;
for (anyWidthWithinAverage=true; anyWidthWithinAverage && remainedTabs>0;)
{
anyWidthWithinAverage = false;
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs--;
}
}
if (remainedTabs != 0)
averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs;
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth --;
}
else
tab.TabWidth = averageWidth;
}
}
// Set the X position of the tabs
int x = rectTabStrip.X + ToolWindowStripGapLeft;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index)
{
bool overflow = false;
TabVS2005 tab = Tabs[index] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(index);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
if (x + width < rectTabStrip.Right || index == StartDisplayingTab)
{
tab.TabX = x;
tab.TabWidth = width;
EndDisplayingTab = index;
}
else
{
tab.TabX = 0;
tab.TabWidth = 0;
overflow = true;
}
x += width;
return overflow;
}
/// <summary>
/// Calculate which tabs are displayed and in what order.
/// </summary>
private void CalculateTabs_Document()
{
if (m_startDisplayingTab >= Tabs.Count)
m_startDisplayingTab = 0;
Rectangle rectTabStrip = TabsRectangle;
int x = rectTabStrip.X + rectTabStrip.Height / 2;
bool overflow = false;
// Originally all new documents that were considered overflow
// (not enough pane strip space to show all tabs) were added to
// the far left (assuming not right to left) and the tabs on the
// right were dropped from view. If StartDisplayingTab is not 0
// then we are dealing with making sure a specific tab is kept in focus.
if (m_startDisplayingTab > 0)
{
int tempX = x;
TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
// Add the active tab and tabs to the left
for (int i = StartDisplayingTab; i >= 0; i--)
CalculateDocumentTab(rectTabStrip, ref tempX, i);
// Store which tab is the first one displayed so that it
// will be drawn correctly (without part of the tab cut off)
FirstDisplayingTab = EndDisplayingTab;
tempX = x; // Reset X location because we are starting over
// Start with the first tab displayed - name is a little misleading.
// Loop through each tab and set its location. If there is not enough
// room for all of them overflow will be returned.
for (int i = EndDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i);
// If not all tabs are shown then we have an overflow.
if (FirstDisplayingTab != 0)
overflow = true;
}
else
{
for (int i = StartDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
for (int i = 0; i < StartDisplayingTab; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
FirstDisplayingTab = StartDisplayingTab;
}
if (!overflow)
{
m_startDisplayingTab = 0;
FirstDisplayingTab = 0;
x = rectTabStrip.X + rectTabStrip.Height / 2;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
DocumentTabsOverflow = overflow;
}
protected internal override void EnsureTabVisible(IDockContent content)
{
if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content))
return;
CalculateTabs();
EnsureDocumentTabVisible(content, true);
}
private bool EnsureDocumentTabVisible(IDockContent content, bool repaint)
{
int index = Tabs.IndexOf(content);
TabVS2005 tab = Tabs[index] as TabVS2005;
if (tab.TabWidth != 0)
return false;
StartDisplayingTab = index;
if (repaint)
Invalidate();
return true;
}
private int GetMaxTabWidth(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetMaxTabWidth_ToolWindow(index);
else
return GetMaxTabWidth_Document(index);
}
private int GetMaxTabWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont);
return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft
+ ToolWindowImageGapRight + ToolWindowTextGapRight;
}
private int GetMaxTabWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
int height = GetTabRectangle_Document(index).Height;
Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
if (DockPane.DockPanel.ShowDocumentIcon)
return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight;
else
return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight;
}
private void DrawTabStrip(Graphics g)
{
if (Appearance == DockPane.AppearanceStyle.Document)
DrawTabStrip_Document(g);
else
DrawTabStrip_ToolWindow(g);
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Draw the tabs
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
TabVS2005 tabActive = null;
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
for (int i=0; i<count; i++)
{
rectTab = GetTabRectangle(i);
if (Tabs[i].Content == DockPane.ActiveContent)
{
tabActive = Tabs[i] as TabVS2005;
continue;
}
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, Tabs[i] as TabVS2005, rectTab);
}
g.SetClip(rectTabStrip);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1,
rectTabStrip.Right, rectTabStrip.Top + 1);
else
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1,
rectTabStrip.Right, rectTabStrip.Bottom - 1);
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
if (tabActive != null)
{
rectTab = GetTabRectangle(Tabs.IndexOf(tabActive));
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, tabActive, rectTab);
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
Rectangle rectTabStrip = TabStripRectangle;
g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top,
rectTabStrip.Right, rectTabStrip.Top);
for (int i=0; i<Tabs.Count; i++)
DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i));
}
private Rectangle GetTabRectangle(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabRectangle_ToolWindow(index);
else
return GetTabRectangle_Document(index);
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)Tabs[index];
Rectangle rect = new Rectangle();
rect.X = tab.TabX;
rect.Width = tab.TabWidth;
rect.Height = rectTabStrip.Height - DocumentTabGapTop;
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
rect.Y = rectTabStrip.Y + DocumentStripGapBottom;
else
rect.Y = rectTabStrip.Y + DocumentTabGapTop;
return rect;
}
private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
DrawTab_ToolWindow(g, tab, rect);
else
DrawTab_Document(g, tab, rect);
}
private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen);
else
return GetTabOutline_Document(tab, rtlTransform, toScreen, false);
}
private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen)
{
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false);
return GraphicsPath;
}
private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full)
{
int curveSize = 6;
GraphicsPath.Reset();
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
// Draws the full angle piece for active content (or first tab)
if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
// Draws the partial angle for non-active content
else
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
else
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top);
GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90);
}
else
{
// Draws the top horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top);
// Draws the rounded corner oppposite the angled side
GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90);
}
}
if (Tabs.IndexOf(tab) != EndDisplayingTab &&
(Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent)
&& !full)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom);
}
}
}
else
{
// Draw the vertical line opposite the angled side
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top);
else
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom);
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top);
else
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom);
}
}
return GraphicsPath;
}
private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect)
{
Rectangle rectIcon = new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight,
ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft -
ToolWindowImageGapRight - ToolWindowTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path);
g.DrawPath(PenToolWindowTabBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path);
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1)
{
Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop);
Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom);
g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2));
}
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
if (rectTab.Contains(rectIcon))
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (tab.TabWidth == 0)
return;
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight,
DocumentIconWidth, DocumentIconHeight);
Rectangle rectText = rectIcon;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += rectIcon.Width + DocumentIconGapRight;
rectText.Y = rect.Y;
rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft -
DocumentIconGapRight - DocumentTextGapRight;
rectText.Height = rect.Height;
}
else
rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
Rectangle rectBack = DrawHelper.RtlTransform(this, rect);
rectBack.Width += rect.X;
rectBack.X = 0;
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path);
g.DrawPath(PenDocumentTabActiveBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor;
if (DockPane.IsActiveDocumentPane)
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat);
else
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path);
g.DrawPath(PenDocumentTabInactiveBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon)
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private Rectangle TabStripRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.Document)
return TabStripRectangle_Document;
else
return TabStripRectangle_ToolWindow;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return TabStripRectangle;
Rectangle rectWindow = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width +
2 * DocumentButtonGapBetween;
return new Rectangle(x, y, width, height);
}
}
private ContextMenuStrip m_selectMenu;
private ContextMenuStrip SelectMenu
{
get { return m_selectMenu; }
}
private void WindowList_Click(object sender, EventArgs e)
{
int x = 0;
int y = ButtonWindowList.Location.Y + ButtonWindowList.Height;
SelectMenu.Items.Clear();
foreach (TabVS2005 tab in Tabs)
{
IDockContent content = tab.Content;
ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap());
item.Tag = tab.Content;
item.Click += new EventHandler(ContextMenuItem_Click);
}
SelectMenu.Show(ButtonWindowList, x, y);
}
private void ContextMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
IDockContent content = (IDockContent)item.Tag;
DockPane.ActiveContent = content;
}
}
private void SetInertButtons()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
{
if (m_buttonClose != null)
m_buttonClose.Left = -m_buttonClose.Width;
if (m_buttonWindowList != null)
m_buttonWindowList.Left = -m_buttonWindowList.Width;
}
else
{
bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton;
ButtonClose.Enabled = showCloseButton;
ButtonClose.Visible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible;
ButtonClose.RefreshChanges();
ButtonWindowList.RefreshChanges();
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
if (Appearance != DockPane.AppearanceStyle.Document)
{
base.OnLayout(levent);
return;
}
Rectangle rectTabStrip = TabStripRectangle;
// Set position and size of the buttons
int buttonWidth = ButtonClose.Image.Width;
int buttonHeight = ButtonClose.Image.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft
- DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
// If the close button is not visible draw the window list button overtop.
// Otherwise it is drawn to the left of the close button.
if (ButtonClose.Visible)
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
OnRefreshChanges();
base.OnLayout (levent);
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
}
protected internal override int HitTest(Point ptMouse)
{
Rectangle rectTabStrip = TabsRectangle;
if (!TabsRectangle.Contains(ptMouse))
return -1;
foreach (Tab tab in Tabs)
{
GraphicsPath path = GetTabOutline(tab, true, false);
if (path.IsVisible(ptMouse))
return Tabs.IndexOf(tab);
}
return -1;
}
protected override void OnMouseHover(EventArgs e)
{
int index = HitTest(PointToClient(Control.MousePosition));
string toolTip = string.Empty;
base.OnMouseHover(e);
if (index != -1)
{
TabVS2005 tab = Tabs[index] as TabVS2005;
if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText))
toolTip = tab.Content.DockHandler.ToolTipText;
else if (tab.MaxWidth > tab.TabWidth)
toolTip = tab.Content.DockHandler.TabText;
}
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
// requires further tracking of mouse hover behavior,
ResetMouseEventArgs();
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Automation;
using System.Windows.Input;
using Microsoft.TestSccPackage;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.SharedProject;
using TestUtilities.UI;
using Keyboard = TestUtilities.UI.Keyboard;
using Mouse = TestUtilities.UI.Mouse;
using MessageBoxButton = TestUtilities.MessageBoxButton;
namespace Microsoft.VisualStudioTools.SharedProjectTests
{
[TestClass]
public class SourceControl : SharedProjectTest
{
private static Regex _pathRegex = new Regex(@"\{path:([^}]*)\}");
private const string VSQUERYRENAMEFILEFLAGS_NoFlags = "VSQUERYRENAMEFILEFLAGS_NoFlags";
private const string VSQUERYRENAMEFILEFLAGS_Directory = "VSQUERYRENAMEFILEFLAGS_Directory";
private const string VSRENAMEFILEFLAGS_NoFlags = "VSRENAMEFILEFLAGS_NoFlags";
private const string VSRENAMEFILEFLAGS_Directory = "VSRENAMEFILEFLAGS_Directory";
/// <summary>
/// https://nodejstools.codeplex.com/workitem/194
///
/// Verifies that we deliver the right set of track events to the source
/// when we move a folder with a file in it.
///
/// The right set of events are based upon matching the same events the C#
/// project system delivers. Those can be using the TestSccPackage with a
/// C# project. Once enables in Tools->Options->Source Control you can get
/// the list of events from Tools->Show Scc Track Document Events.
/// </summary>
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
// Currently Fails: https://pytools.codeplex.com/workitem/2609
public void MoveFolderWithItem()
{
using (var app = new VisualStudioApp())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
ExpectSourceControl();
foreach (var projectType in ProjectTypes)
{
var testDef = new ProjectDefinition("SourceControl", projectType,
PropertyGroup(
Property("SccProjectName", "HelloWorld"),
Property("SccLocalPath", "LocalPath"),
Property("SccAuxPath", "AuxPath"),
Property("SccProvider", "TestProvider")
),
ItemGroup(
Folder("Fob"),
Folder("Fob\\Oar"),
Compile("Program"),
Compile("Fob\\Oar\\Quox")
)
);
using (var solution = testDef.Generate())
{
TestSccProvider.DocumentEvents.Clear();
var project = app.OpenProject(solution.Filename);
var window = app.OpenSolutionExplorer();
var folder = window.WaitForItem("Solution 'SourceControl' (1 project)", "SourceControl", "Fob", "Oar");
var point = folder.GetClickablePoint();
Mouse.MoveTo(point);
Mouse.Down(MouseButton.Left);
var destFolder = window.WaitForItem("Solution 'SourceControl' (1 project)", "SourceControl");
Mouse.MoveTo(destFolder.GetClickablePoint());
Mouse.Up(MouseButton.Left);
window.AssertFileExists(Path.GetDirectoryName(solution.Filename), "Solution 'SourceControl' (1 project)", "SourceControl", "Oar", "Quox" + projectType.CodeExtension);
var projectDir = Path.GetDirectoryName(project.FullName);
AssertDocumentEvents(projectDir,
OnQueryRenameFiles(projectType.Code("Fob\\Oar\\Quox"), projectType.Code("Oar\\Quox"), VSQUERYRENAMEFILEFLAGS_NoFlags),
OnQueryRenameFiles("Fob\\Oar\\", "Oar", VSQUERYRENAMEFILEFLAGS_Directory),
OnAfterRenameFiles(projectType.Code("Fob\\Oar\\Quox"), projectType.Code("Oar\\Quox"), VSRENAMEFILEFLAGS_NoFlags),
OnAfterRenameFiles("Fob\\Oar\\", "Oar", VSRENAMEFILEFLAGS_Directory)
);
}
}
}
}
[Ignore]
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
public void AddNewItem()
{
using (var app = new VisualStudioApp())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
foreach (var projectType in ProjectTypes)
{
var testDef = SourceControlProject(projectType);
using (var solution = testDef.Generate())
{
TestSccProvider.DocumentEvents.Clear();
var project = app.OpenProject(solution.Filename);
var fileName = "NewFile" + projectType.CodeExtension;
using (var newItem = NewItemDialog.FromDte(app))
{
newItem.FileName = fileName;
newItem.OK();
}
System.Threading.Thread.Sleep(250);
Assert.IsNotNull(project.ProjectItems.Item(fileName));
AssertDocumentEvents(Path.GetDirectoryName(project.FullName),
OnQueryAddFiles(fileName),
OnAfterAddFilesEx(fileName)
);
}
}
}
}
public void AddExistingItem()
{
using (var app = new VisualStudioApp())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
foreach (var projectType in ProjectTypes)
{
var testDef = SourceControlProject(projectType);
using (var solution = testDef.Generate())
{
TestSccProvider.DocumentEvents.Clear();
var project = app.OpenProject(solution.Filename);
var fileName = projectType.Code(@"ExcludedFile");
using (var newItem = AddExistingItemDialog.FromDte(app))
{
newItem.FileName = fileName;
newItem.OK();
}
System.Threading.Thread.Sleep(250);
Assert.IsNotNull(project.ProjectItems.Item(fileName));
AssertDocumentEvents(Path.GetDirectoryName(project.FullName),
OnQueryAddFiles(fileName),
OnAfterAddFilesEx(fileName)
);
}
}
}
}
[Ignore]
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
public void IncludeInProject()
{
using (var app = new VisualStudioApp())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
foreach (var projectType in ProjectTypes)
{
var testDef = SourceControlProject(projectType);
using (var solution = testDef.Generate().ToVs())
{
TestSccProvider.DocumentEvents.Clear();
var project = app.OpenProject(solution.SolutionFilename);
var window = app.OpenSolutionExplorer();
var fileName = projectType.Code(@"ExcludedFile");
// Try to select the file. If it throws, it is likely the issue was that we weren't showing all files.
try
{
window.WaitForChildOfProject(project, fileName).Select();
}
catch (Exception)
{
// Show all files so we can see the excluded item if we previously couldn't
solution.ExecuteCommand("Project.ShowAllFiles");
window.WaitForChildOfProject(project, fileName).Select();
}
solution.ExecuteCommand("Project.IncludeInProject");
System.Threading.Thread.Sleep(250);
AssertDocumentEvents(Path.GetDirectoryName(project.FullName),
OnQueryAddFiles(fileName),
OnAfterAddFilesEx(fileName)
);
}
}
}
}
[Ignore]
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
public void RemoveItem()
{
using (var app = new VisualStudioApp())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
foreach (var projectType in ProjectTypes)
{
var testDef = SourceControlProject(projectType);
using (var solution = testDef.Generate())
{
TestSccProvider.DocumentEvents.Clear();
var project = app.OpenProject(solution.Filename);
var window = app.OpenSolutionExplorer();
var fileName = "Program" + projectType.CodeExtension;
var program = window.WaitForChildOfProject(project, fileName);
program.Select();
Keyboard.Type(Key.Delete);
app.WaitForDialog();
VisualStudioApp.CheckMessageBox(MessageBoxButton.Ok, "will be deleted permanently");
app.WaitForDialogDismissed();
window.WaitForChildOfProjectRemoved(project, fileName);
var projectDir = Path.GetDirectoryName(project.FullName);
AssertDocumentEvents(projectDir,
OnQueryRemoveFiles(fileName),
OnAfterRemoveFiles(fileName)
);
}
}
}
}
/// <summary>
/// Verify we get called w/ a project which does have source control enabled.
/// </summary>
[Ignore]
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
public void BasicSourceControl()
{
using (var app = new VisualStudioApp())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
ExpectSourceControl();
foreach (var projectType in ProjectTypes)
{
var testDef = SourceControlProject(projectType);
using (var solution = testDef.Generate())
{
var project = app.OpenProject(solution.Filename);
Assert.AreEqual(1, TestSccProvider.LoadedProjects.Count);
TestSccProvider.ExpectedAuxPath = null;
TestSccProvider.ExpectedLocalPath = null;
TestSccProvider.ExpectedProvider = null;
TestSccProvider.ExpectedProjectName = null;
TestSccProvider.LoadedProjects.First().SccProject.SetSccLocation(
"NewProjectName",
"NewAuxPath",
"NewLocalPath",
"NewProvider"
);
app.Dte.Solution.Close();
Assert.AreEqual(0, TestSccProvider.LoadedProjects.Count);
if (TestSccProvider.Failures.Count != 0)
{
Assert.Fail(String.Join(Environment.NewLine, TestSccProvider.Failures));
}
app.SelectSourceControlProvider("None");
}
}
}
}
/// <summary>
/// Verify the glyph change APIs update the glyphs appropriately
/// </summary>
[Ignore]
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
public void SourceControlGlyphChanged()
{
using (var app = new VisualStudioApp())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
foreach (var projectType in ProjectTypes)
{
var testDef = SourceControlProject(projectType);
using (var solution = testDef.Generate())
{
var project = app.OpenProject(solution.Filename);
Assert.AreEqual(1, TestSccProvider.LoadedProjects.Count);
var sccProject = TestSccProvider.LoadedProjects.First();
Microsoft.TestSccPackage.FileInfo fileInfo = null;
foreach (var curFile in sccProject.Files)
{
if (curFile.Key.EndsWith("Program" + projectType.CodeExtension))
{
fileInfo = curFile.Value;
break;
}
}
Assert.IsNotNull(fileInfo);
fileInfo.GlyphChanged(VsStateIcon.STATEICON_CHECKEDOUTEXCLUSIVEOTHER);
var programPy = project.ProjectItems.Item("Program" + projectType.CodeExtension);
Assert.AreEqual(programPy.Properties.Item("SourceControlStatus").Value, "CHECKEDOUTEXCLUSIVEOTHER");
fileInfo.StateIcon = VsStateIcon.STATEICON_READONLY;
sccProject.AllGlyphsChanged();
Assert.AreEqual(programPy.Properties.Item("SourceControlStatus").Value, "READONLY");
app.Dte.Solution.Close();
Assert.AreEqual(0, TestSccProvider.LoadedProjects.Count);
if (TestSccProvider.Failures.Count != 0)
{
Assert.Fail(String.Join(Environment.NewLine, TestSccProvider.Failures));
}
app.SelectSourceControlProvider("None");
}
}
}
}
/// <summary>
/// Verify we don't get called for a project which doesn't have source control enabled.
/// </summary>
[Ignore]
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
public void SourceControlNoControl()
{
using (var app = new VisualStudioApp())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
DontExpectSourceControl();
foreach (var projectType in ProjectTypes)
{
var testDef = NoSourceControlProject(projectType);
using (var solution = testDef.Generate())
{
var project = app.OpenProject(solution.Filename);
Assert.AreEqual(0, TestSccProvider.LoadedProjects.Count);
app.Dte.Solution.Close();
Assert.AreEqual(0, TestSccProvider.LoadedProjects.Count);
if (TestSccProvider.Failures.Count != 0)
{
Assert.Fail(String.Join(Environment.NewLine, TestSccProvider.Failures));
}
app.SelectSourceControlProvider("None");
}
}
}
}
/// <summary>
/// Verify non-member items don't get reported as source control files
///
/// https://pytools.codeplex.com/workitem/1417
/// </summary>
[Ignore]
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
public void SourceControlExcludedFilesNotPresent()
{
using (var app = new VisualStudioApp())
{
foreach (var projectType in ProjectTypes)
{
using (var solution = SourceControlProject(projectType).Generate())
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
var project = app.OpenProject(solution.Filename);
Assert.AreEqual(1, TestSccProvider.LoadedProjects.Count);
var sccProject = TestSccProvider.LoadedProjects.First();
foreach (var curFile in sccProject.Files)
{
Assert.IsFalse(curFile.Key.EndsWith("ExcludedFile" + projectType.CodeExtension), "found excluded file");
}
}
}
app.Dte.Solution.Close();
app.SelectSourceControlProvider("None");
}
}
/// <summary>
/// Verify we get called w/ a project which does have source control enabled.
/// </summary>
[Ignore]
[TestMethod, Priority(0), TestCategory("Core")]
[HostType("VSTestHost")]
public void SourceControlRenameFolder()
{
using (var app = new VisualStudioApp())
{
foreach (var projectType in ProjectTypes)
{
// close any projects before switching source control...
app.Dte.Solution.Close();
app.SelectSourceControlProvider("Test Source Provider");
TestSccProvider.DocumentEvents.Clear();
using (var solution = SourceControlProject(projectType).Generate())
{
try
{
var project = app.OpenProject(solution.Filename);
project.ProjectItems.Item("TestFolder").Name = "Renamed";
AssertDocumentEvents(Path.GetDirectoryName(project.FullName),
OnQueryRenameFiles("TestFolder\\", "Renamed\\", VSQUERYRENAMEFILEFLAGS_Directory),
OnAfterRenameFiles("TestFolder\\", "Renamed", VSRENAMEFILEFLAGS_Directory)
);
app.Dte.Solution.Close();
}
finally
{
app.SelectSourceControlProvider("None");
}
}
}
}
}
#region Helper Methods
/// <summary>
/// Creates the document event string for OnQueryRemoveFiles that matches the output of
/// the TestSccProvider.
/// </summary>
private static string OnQueryRemoveFiles(string source)
{
return "OnQueryRemoveFiles " +
ToPath(source);
}
/// <summary>
/// Creates the document event string for OnAfterRemoveFiles that matches the output of
/// the TestSccProvider.
/// </summary>
private static string OnAfterRemoveFiles(string source)
{
return "OnAfterRemoveFiles " +
ToPath(source);
}
/// <summary>
/// Creates the document event string for OnQueryRenameFiles that matches the output of
/// the TestSccProvider.
/// </summary>
private static string OnQueryRenameFiles(string source, string dest, string flags)
{
return "OnQueryRenameFiles " +
ToPath(source) +
" " +
ToPath(dest) +
" " +
flags;
}
/// <summary>
/// Creates the document event strin g for OnQueryRenameFiles that matches the output
/// of the TestSccProvider.
/// </summary>
private static string OnAfterRenameFiles(string source, string dest, string flags)
{
return "OnAfterRenameFiles " +
ToPath(source) +
" " +
ToPath(dest) +
" " +
flags;
}
/// <summary>
/// Creates the document event string for OnQueryAddFiles that matches the output of
/// the TestSccProvider.
/// </summary>
private static string OnQueryAddFiles(string source)
{
return "OnQueryAddFiles " +
ToPath(source);
}
/// <summary>
/// Creates the document event strin g for OnAfterAddFilesEx that matches the output
/// of the TestSccProvider.
/// </summary>
private static string OnAfterAddFilesEx(string source)
{
return "OnAfterAddFilesEx " +
ToPath(source);
}
/// <summary>
/// Converts a path into the path regex which will be used in
/// AssertDocumentEvents to combine the path here w/ a Path.Combine
/// to the project path.
/// </summary>
private static string ToPath(string path)
{
var res = "{path:" + path + "}";
Debug.Assert(_pathRegex.IsMatch(res));
return res;
}
public static string ToFormatString(string format, string projectDir)
{
foreach (Match match in _pathRegex.Matches(format))
{
format = format.Replace(match.Value, Path.Combine(projectDir, match.Groups[1].Value));
}
return format;
}
/// <summary>
/// Asserts that the specified set of document events was received from the TestSccProvider
/// </summary>
private static void AssertDocumentEvents(string projectDir, params string[] events)
{
events = events.Select(str => ToFormatString(str, projectDir)).ToArray();
var expected = String.Join(
Environment.NewLine,
events
);
string actual = String.Join(
Environment.NewLine,
TestSccProvider.DocumentEvents
);
if (expected != actual)
{
StringBuilder msg = new StringBuilder();
msg.AppendLine();
if (TestSccProvider.DocumentEvents.Count != events.Length)
{
msg.AppendFormat("Got {0}, expected {1} items", TestSccProvider.DocumentEvents.Count, events.Length);
msg.AppendLine();
}
for (int i = 0; i < TestSccProvider.DocumentEvents.Count && i < events.Length; i++)
{
if (TestSccProvider.DocumentEvents[i] != events[i])
{
msg.AppendFormat("Event {0} differs:", i);
msg.AppendLine();
msg.AppendFormat(" Expected: {0}", events[i]);
msg.AppendLine();
msg.AppendFormat(" Actual : {0}", TestSccProvider.DocumentEvents[i]);
}
else
{
msg.AppendFormat("Event {0} matches", i);
}
msg.AppendLine();
}
Assert.AreEqual(expected, actual, msg.ToString());
}
}
private static void ExpectSourceControl()
{
TestSccProvider.ExpectedAuxPath = "AuxPath";
TestSccProvider.ExpectedLocalPath = "LocalPath";
TestSccProvider.ExpectedProvider = "TestProvider";
TestSccProvider.ExpectedProjectName = "HelloWorld";
}
private static void DontExpectSourceControl()
{
TestSccProvider.ExpectedAuxPath = null;
TestSccProvider.ExpectedLocalPath = null;
TestSccProvider.ExpectedProvider = null;
TestSccProvider.ExpectedProjectName = null;
}
private static ProjectDefinition SourceControlProject(ProjectType projectType)
{
return new ProjectDefinition("SourceControl", projectType,
PropertyGroup(
Property("SccProjectName", "HelloWorld"),
Property("SccLocalPath", "LocalPath"),
Property("SccAuxPath", "AuxPath"),
Property("SccProvider", "TestProvider")
),
ItemGroup(
Folder("TestFolder"),
Compile("Program"),
Compile("TestFolder\\SubItem"),
Compile("ExcludedFile", isExcluded: true)
)
);
}
private static ProjectDefinition NoSourceControlProject(ProjectType projectType)
{
return new ProjectDefinition("NoSourceControl", projectType,
ItemGroup(
Compile("Program")
)
);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using SIL.Code;
using SIL.Extensions;
using SIL.IO;
using SIL.Reporting;
namespace SIL.Windows.Forms.ImageToolbox.ImageGallery
{
/// <summary>
/// Finds and searches all the ImagesCollections on the machine.
/// While we have now standardized on location of collections and where they must be on disk,
/// this is backwards-compatible so that people who have previous versions of the Art Of Reading
/// collection do not need to upgrade that.
/// </summary>
public class ImageCollectionManager
{
public IEnumerable<ImageCollection> Collections => _collections;
// For testing.
internal static string ImageCollectionsFolder { get; set; }
private readonly List<ImageCollection> _collections;
private IEnumerable<ImageCollection> EnabledCollections => Collections.Where(c => c.Enabled);
private string _searchLanguage;
private bool _indicesLoaded;
/// <summary>
/// Factory method that finds and loads any available image collections
/// </summary>
public static ImageCollectionManager FromStandardLocations(string searchLanguageId = "en")
{
var manager = new ImageCollectionManager(searchLanguageId);
manager.FindAndLoadCollections();
if (manager.Collections.Any())
return manager;
return null;
}
internal ImageCollectionManager(string searchLanguageId)
{
// Windows: typically C:\ProgramData\SIL\ImageCollections.
// Linux: typically /usr/share/SIL/ImageCollections
// (This is not the typical place for a Linux package to install things
// and CamelCase is not a standard way to name folders.
// Typically each package would make its own folder at the root of /user/share.
// Then something like sil-image-collection might plausibly be part of each
// folder name.
// But that will require a whole different strategy for finding them, possibly
// something like an environment variable, or we could search the whole
// of /user/share for folders starting with sil-image-collection. Let's wait and see whether anyone
// actually wants to do this and doesn't find the current proposal satisfactory.)
//unit tests can override this
ImageCollectionsFolder =
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
.CombineForPath("SIL", "ImageCollections");
_searchLanguage = searchLanguageId;
_collections = new List<ImageCollection>();
}
/// <summary>
/// Language ids that can be selected for searching
/// </summary>
public IEnumerable<string> IndexLanguageIds
{
get { return Collections.SelectMany(c => c.IndexLanguages).Distinct(); }
}
/// <summary>
/// After construction, need to call this to locate and begin loading the indices.
/// This launches threads that do the actual loading. The key data is c# locked
/// so that if you try to do a search before they are done, should at least get
/// a partial match. (Enhance: we could give a way to wait for them to be done).
/// </summary>
/// <param name="explicitFoldersForUnitTests">normally you shold omit this. Unit tests cnn specify for unit tests.</param>
public void FindAndLoadCollections(IEnumerable<string> explicitFoldersForUnitTests = null)
{
List<string> collectionFolders = new List<string>();
if(explicitFoldersForUnitTests != null)
{
collectionFolders.AddRange(explicitFoldersForUnitTests);
}
else
{
if(Directory.Exists(ImageCollectionsFolder))
{
collectionFolders.AddRange(
Directory.GetDirectories(ImageCollectionsFolder)
.Where(dir => !string.IsNullOrEmpty(LookForIndex(dir))));
}
// if there was no collection that looks like Art Of Reading in the SIL/ImageCollections, look in the old location used prior to Art Of Reading 3.3
if(!collectionFolders.Any(path => path.Contains("Art") && path.Contains("Reading")))
{
var aorPath = TryToGetLegacyArtOfReadingPath();
if(!string.IsNullOrEmpty(aorPath))
{
collectionFolders.Add(aorPath);
}
}
}
_collections.AddRange(collectionFolders.Select(f => new ImageCollection(f)));
// Load the index information asynchronously so as not to delay displaying
// the parent dialog.
var indexLoadingThread = new Thread(() =>
{
foreach(var c in Collections)
{
try
{
c.LoadIndex(_searchLanguage);
}
catch(Exception e)
{
// This is not worth localizing. It should be very rare to have a problem in an
// image collection that has been distributed, and pretty easy for us to get a hold
// of it and see the real problem.
ErrorReport.NotifyUserOfProblem($"There was a problem loading the {c.Name} collection, so some images may not be findable. The problem was:{Environment.NewLine}{e.Message}.");
}
}
_indicesLoaded = true;
});
indexLoadingThread.Name = "Index Loading Thread";
indexLoadingThread.Start();
}
/// <summary>
/// Get images that exactly match one or more search terms.
/// </summary>
public IEnumerable<string> GetMatchingImages(string searchTerms, bool limitToThoseActuallyAvailable,
out bool foundExactMatches)
{
foundExactMatches = false;
// On a dev machine, the index loading feels instantaneous with AOR,
// but if the user were on a super slow computer, and entered a query quickly, he would
// get a spinning cursor until they are done.
const int kMaxSecondsToWaitForIndexLoading = 20;
var whenToGiveUp = DateTime.Now.AddSeconds(kMaxSecondsToWaitForIndexLoading);
while(!_indicesLoaded && DateTime.Now < whenToGiveUp)
{
Thread.Sleep(10);
}
// If still not done, give up and return no results.
if(!_indicesLoaded)
{
return new string[]{};
}
searchTerms = GetCleanedUpSearchString(searchTerms.ToLowerInvariant());
var searchTermArray = searchTerms.SplitTrimmed(' ');
var result = new List<string>();
foreach (var collection in EnabledCollections)
{
var matchingImages = collection.GetMatchingImages(searchTermArray);
if (matchingImages.Any())
{
result.AddRange(matchingImages);
foundExactMatches = true;
}
}
if (!foundExactMatches)
{
foreach (var collection in EnabledCollections)
{
result.AddRange(collection.GetApproximateMatchingImages(searchTermArray));
}
}
var finalResult = limitToThoseActuallyAvailable ? result.Where(File.Exists) : result;
#if DEBUG
if (limitToThoseActuallyAvailable)
{
System.Diagnostics.Debug.Assert(result.Count == finalResult.Count(), "All of the images in the index should exist");
}
#endif
return finalResult;
}
/// <summary>
/// Load the index again, this time for the a different language id
/// </summary>
public void ChangeSearchLanguageAndReloadIndex(string searchLanguageId)
{
_searchLanguage = searchLanguageId;
foreach (var c in Collections)
{
c.LoadIndex(_searchLanguage);
}
}
/// <summary>
/// Include the given collection in searches
/// </summary>
/// <remarks>Not obvious that we need this on this class in addition to ImageCollection, except it's convenient for unit tests</remarks>
internal void SetCollectionEnabledStatus(string folderPath, bool enabled)
{
var c = GetExistingCollectionFromPath(folderPath);
if (c == null)
{
return; // we don't have it, so it's enabled-ness is meaningless
}
c.Enabled = enabled;
}
/// <summary>
/// Include the given collection in searches
/// </summary>
/// <remarks>Not obvious that we need this on this class in addition to ImageCollection, except it's convenient for unit tests</remarks>
internal bool IsCollectionEnabled(string folderPath)
{
var c = GetExistingCollectionFromPath(folderPath);
Guard.AgainstNull(c, "collection wasn't found in the ImageCollectionManager" + folderPath);
return c.Enabled;
}
private static string TryToGetLegacyArtOfReadingPath()
{
// TryToGetLegacyArtOfReadingImagesPath is some legacy code that works but gives us the image folder, rather
// than the root of the collection folder that it makes more sense to work with. So we just wrap it and
// return the parent of the Images folder.
var p = TryToGetLegacyArtOfReadingImagesPath();
if (p != null)
p = Path.GetDirectoryName(p);
return p;
}
private static string TryToGetLegacyArtOfReadingImagesPath()
{
const string kImages = "Images";
var distributedWithApp = FileLocationUtilities.GetDirectoryDistributedWithApplication(true, "Art Of Reading", kImages);
if (!string.IsNullOrEmpty(distributedWithApp) && Directory.Exists(distributedWithApp))
return distributedWithApp;
//look for it in a hard-coded location
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
var unixPaths = new[]
{
@"/usr/share/ArtOfReading/images", // new package location (standard LSB/FHS location)
@"/usr/share/SIL/ArtOfReading/images", // old (lost) package location
@"/var/share/ArtOfReading/images" // obsolete test location (?)
};
foreach (var path in unixPaths)
{
if (Directory.Exists(path))
return path;
}
}
else
{
//look for the folder created by the ArtOfReadingFree installer before 3.3, the first version to put it in the ImageCollections folder.
var aorInstallerTarget =
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
.CombineForPath("SIL", "Art Of Reading", kImages);
//the rest of these are for before we had an installer for AOR
var appData =
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
.CombineForPath("Art Of Reading", kImages);
var appDataNoSpace =
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
.CombineForPath("ArtOfReading", kImages);
var winPaths = new[]
{
aorInstallerTarget, @"c:\art of reading\images", @"c:/ArtOfReading/images", appData, appDataNoSpace
};
foreach (var path in winPaths)
{
if (Directory.Exists(path))
return path;
}
}
return null;
}
internal static string GetCleanedUpSearchString(string searchTerms)
{
searchTerms = searchTerms.Replace(",", " ");
searchTerms = searchTerms.Replace(";", " ");
searchTerms = searchTerms.Replace("-", string.Empty);
searchTerms = searchTerms.Replace(".", string.Empty);
searchTerms = searchTerms.Replace("(", string.Empty);
return searchTerms.Replace(")", string.Empty);
}
private ImageCollection GetExistingCollectionFromPath(string folderPath)
=> Collections.FirstOrDefault(c => c.FolderPath == folderPath);
private static string LookForIndex(string directory)
{
if (String.IsNullOrEmpty(directory) || !Directory.Exists(directory))
return null;
// It's somewhat arbitrary what order we use here, but making it alphabetical makes it more
// predictable, since the order returned by EnumerateFiles is not guaranteed.
// One thing that is important is that in versions of AOR that have both
// ArtOfReadingMultilingualIndex.txt and index.txt, the former must be found first.
return Directory.EnumerateFiles(directory, "*ndex.txt")
.Where(x => x.ToLowerInvariant().EndsWith("index.txt"))
// no way to enumerate [iI]ndex.txt on Linux, and we need both
.OrderBy(x => x.ToLowerInvariant())
.FirstOrDefault();
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using MS.Internal.KnownBoxes;
using System.ComponentModel;
namespace System.Windows.Controls
{
/// <summary>
/// Service class that provides the system implementation for displaying ToolTips.
/// </summary>
public static class ToolTipService
{
#region Attached Properties
/// <summary>
/// The DependencyProperty for the ToolTip property.
/// </summary>
public static readonly DependencyProperty ToolTipProperty =
DependencyProperty.RegisterAttached(
"ToolTip", // Name
typeof(object), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata((object) null));
/// <summary>
/// Gets the value of the ToolTip property on the specified object.
/// </summary>
/// <param name="element">The object on which to query the ToolTip property.</param>
/// <returns>The value of the ToolTip property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static object GetToolTip(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return element.GetValue(ToolTipProperty);
}
/// <summary>
/// Sets the ToolTip property on the specified object.
/// </summary>
/// <param name="element">The object on which to set the ToolTip property.</param>
/// <param name="value">
/// The value of the ToolTip property. If the value is of type ToolTip, then
/// that is the ToolTip that will be used (without any modification). If the value
/// is of any other type, then that value will be used as the content for a ToolTip
/// provided by this service, and the other attached properties of this service
/// will be used to configure the ToolTip.
/// </param>
public static void SetToolTip(DependencyObject element, object value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ToolTipProperty, value);
}
/// <summary>
/// The DependencyProperty for the HorizontalOffset property.
/// </summary>
public static readonly DependencyProperty HorizontalOffsetProperty =
DependencyProperty.RegisterAttached("HorizontalOffset", // Name
typeof(double), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(0d)); // Default Value
/// <summary>
/// Gets the value of the HorizontalOffset property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[TypeConverter(typeof(LengthConverter))]
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static double GetHorizontalOffset(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (double)element.GetValue(HorizontalOffsetProperty);
}
/// <summary>
/// Sets the value of the HorizontalOffset property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetHorizontalOffset(DependencyObject element, double value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(HorizontalOffsetProperty, value);
}
/// <summary>
/// The DependencyProperty for the VerticalOffset property.
/// </summary>
public static readonly DependencyProperty VerticalOffsetProperty =
DependencyProperty.RegisterAttached("VerticalOffset", // Name
typeof(double), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(0d)); // Default Value
/// <summary>
/// Gets the value of the VerticalOffset property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[TypeConverter(typeof(LengthConverter))]
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static double GetVerticalOffset(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (double)element.GetValue(VerticalOffsetProperty);
}
/// <summary>
/// Sets the value of the VerticalOffset property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetVerticalOffset(DependencyObject element, double value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(VerticalOffsetProperty, value);
}
/// <summary>
/// The DependencyProperty for HasDropShadow
/// </summary>
public static readonly DependencyProperty HasDropShadowProperty =
DependencyProperty.RegisterAttached("HasDropShadow", // Name
typeof(bool), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); // Default Value
/// <summary>
/// Gets the value of the HasDropShadow property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static bool GetHasDropShadow(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool)element.GetValue(HasDropShadowProperty);
}
/// <summary>
/// Sets the value of the HasDropShadow property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetHasDropShadow(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(HasDropShadowProperty, BooleanBoxes.Box(value));
}
/// <summary>
/// The DependencyProperty for the PlacementTarget property.
/// </summary>
public static readonly DependencyProperty PlacementTargetProperty =
DependencyProperty.RegisterAttached("PlacementTarget", // Name
typeof(UIElement), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata((UIElement)null)); // Default Value
/// <summary>
/// Gets the value of the PlacementTarget property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static UIElement GetPlacementTarget(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (UIElement)element.GetValue(PlacementTargetProperty);
}
/// <summary>
/// Sets the value of the PlacementTarget property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetPlacementTarget(DependencyObject element, UIElement value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(PlacementTargetProperty, value);
}
/// <summary>
/// The DependencyProperty for the PlacementRectangle property.
/// </summary>
public static readonly DependencyProperty PlacementRectangleProperty =
DependencyProperty.RegisterAttached("PlacementRectangle", // Name
typeof(Rect), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(Rect.Empty)); // Default Value
/// <summary>
/// Gets the value of the PlacementRectangle property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static Rect GetPlacementRectangle(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (Rect)element.GetValue(PlacementRectangleProperty);
}
/// <summary>
/// Sets the value of the PlacementRectangle property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetPlacementRectangle(DependencyObject element, Rect value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(PlacementRectangleProperty, value);
}
/// <summary>
/// The DependencyProperty for the Placement property.
/// </summary>
public static readonly DependencyProperty PlacementProperty =
DependencyProperty.RegisterAttached("Placement", // Name
typeof(PlacementMode), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(PlacementMode.Mouse)); // Default Value
/// <summary>
/// Gets the value of the Placement property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static PlacementMode GetPlacement(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (PlacementMode)element.GetValue(PlacementProperty);
}
/// <summary>
/// Sets the value of the Placement property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetPlacement(DependencyObject element, PlacementMode value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(PlacementProperty, value);
}
/// <summary>
/// The DependencyProperty for the ShowOnDisabled property.
/// </summary>
public static readonly DependencyProperty ShowOnDisabledProperty =
DependencyProperty.RegisterAttached("ShowOnDisabled", // Name
typeof(bool), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); // Default Value
/// <summary>
/// Gets the value of the ShowOnDisabled property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static bool GetShowOnDisabled(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool)element.GetValue(ShowOnDisabledProperty);
}
/// <summary>
/// Sets the value of the ShowOnDisabled property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetShowOnDisabled(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ShowOnDisabledProperty, BooleanBoxes.Box(value));
}
/// <summary>
/// Read-only Key Token for the IsOpen property.
/// </summary>
private static readonly DependencyPropertyKey IsOpenPropertyKey =
DependencyProperty.RegisterAttachedReadOnly("IsOpen", // Name
typeof(bool), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); // Default Value
/// <summary>
/// The DependencyProperty for the IsOpen property.
/// </summary>
public static readonly DependencyProperty IsOpenProperty = IsOpenPropertyKey.DependencyProperty;
/// <summary>
/// Gets the value of the IsOpen property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static bool GetIsOpen(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool)element.GetValue(IsOpenProperty);
}
/// <summary>
/// Sets the value of the IsOpen property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
private static void SetIsOpen(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsOpenPropertyKey, BooleanBoxes.Box(value));
}
/// <summary>
/// The DependencyProperty for the IsEnabled property.
/// </summary>
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached("IsEnabled", // Name
typeof(bool), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(BooleanBoxes.TrueBox)); // Default Value
/// <summary>
/// Gets the value of the IsEnabled property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static bool GetIsEnabled(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool)element.GetValue(IsEnabledProperty);
}
/// <summary>
/// Sets the value of the IsEnabled property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetIsEnabled(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsEnabledProperty, BooleanBoxes.Box(value));
}
private static bool PositiveValueValidation(object o)
{
return ((int)o) >= 0;
}
/// <summary>
/// The DependencyProperty for the ShowDuration property.
/// </summary>
public static readonly DependencyProperty ShowDurationProperty =
DependencyProperty.RegisterAttached("ShowDuration", // Name
typeof(int), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(5000), // Default Value
new ValidateValueCallback(PositiveValueValidation)); // Value validation
/// <summary>
/// Gets the value of the ShowDuration property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static int GetShowDuration(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (int)element.GetValue(ShowDurationProperty);
}
/// <summary>
/// Sets the value of the ShowDuration property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetShowDuration(DependencyObject element, int value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ShowDurationProperty, value);
}
/// <summary>
/// The DependencyProperty for the InitialShowDelay property.
/// </summary>
public static readonly DependencyProperty InitialShowDelayProperty =
DependencyProperty.RegisterAttached("InitialShowDelay", // Name
typeof(int), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(SystemParameters.MouseHoverTimeMilliseconds), // Default Value
new ValidateValueCallback(PositiveValueValidation)); // Value validation
/// <summary>
/// Gets the value of the InitialShowDelay property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static int GetInitialShowDelay(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (int)element.GetValue(InitialShowDelayProperty);
}
/// <summary>
/// Sets the value of the InitialShowDelay property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetInitialShowDelay(DependencyObject element, int value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(InitialShowDelayProperty, value);
}
/// <summary>
/// The DependencyProperty for the BetweenShowDelay property.
/// </summary>
public static readonly DependencyProperty BetweenShowDelayProperty =
DependencyProperty.RegisterAttached("BetweenShowDelay", // Name
typeof(int), // Type
typeof(ToolTipService), // Owner
new FrameworkPropertyMetadata(100), // Default Value
new ValidateValueCallback(PositiveValueValidation)); // Value validation
/// <summary>
/// Gets the value of the BetweenShowDelay property.
/// </summary>
/// <param name="element">The object on which to query the property.</param>
/// <returns>The value of the property.</returns>
[AttachedPropertyBrowsableForType(typeof(DependencyObject))]
public static int GetBetweenShowDelay(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (int)element.GetValue(BetweenShowDelayProperty);
}
/// <summary>
/// Sets the value of the BetweenShowDelay property.
/// </summary>
/// <param name="element">The object on which to set the value.</param>
/// <param name="value">The desired value of the property.</param>
public static void SetBetweenShowDelay(DependencyObject element, int value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(BetweenShowDelayProperty, value);
}
#endregion
#region Events
/// <summary>
/// The event raised when a ToolTip is going to be shown on an element.
///
/// Mark the event as handled if manually showing a ToolTip.
///
/// Replacing the value of the ToolTip property is allowed
/// (example: for delay-loading). Do not mark the event as handled
/// in this case if the system is to show the ToolTip.
/// </summary>
public static readonly RoutedEvent ToolTipOpeningEvent =
EventManager.RegisterRoutedEvent("ToolTipOpening",
RoutingStrategy.Direct,
typeof(ToolTipEventHandler),
typeof(ToolTipService));
/// <summary>
/// Adds a handler for the ToolTipOpening attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddToolTipOpeningHandler(DependencyObject element, ToolTipEventHandler handler)
{
UIElement.AddHandler(element, ToolTipOpeningEvent, handler);
}
/// <summary>
/// Removes a handler for the ToolTipOpening attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveToolTipOpeningHandler(DependencyObject element, ToolTipEventHandler handler)
{
UIElement.RemoveHandler(element, ToolTipOpeningEvent, handler);
}
/// <summary>
/// The event raised when a ToolTip on an element that was shown
/// should now be hidden.
/// </summary>
public static readonly RoutedEvent ToolTipClosingEvent =
EventManager.RegisterRoutedEvent("ToolTipClosing",
RoutingStrategy.Direct,
typeof(ToolTipEventHandler),
typeof(ToolTipService));
/// <summary>
/// Adds a handler for the ToolTipClosing attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddToolTipClosingHandler(DependencyObject element, ToolTipEventHandler handler)
{
UIElement.AddHandler(element, ToolTipClosingEvent, handler);
}
/// <summary>
/// Removes a handler for the ToolTipClosing attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveToolTipClosingHandler(DependencyObject element, ToolTipEventHandler handler)
{
UIElement.RemoveHandler(element, ToolTipClosingEvent, handler);
}
#endregion
#region Implementation
internal static readonly RoutedEvent FindToolTipEvent =
EventManager.RegisterRoutedEvent("FindToolTip",
RoutingStrategy.Bubble,
typeof(FindToolTipEventHandler),
typeof(ToolTipService));
static ToolTipService()
{
EventManager.RegisterClassHandler(typeof(UIElement), FindToolTipEvent, new FindToolTipEventHandler(OnFindToolTip));
EventManager.RegisterClassHandler(typeof(ContentElement), FindToolTipEvent, new FindToolTipEventHandler(OnFindToolTip));
EventManager.RegisterClassHandler(typeof(UIElement3D), FindToolTipEvent, new FindToolTipEventHandler(OnFindToolTip));
}
private static void OnFindToolTip(object sender, FindToolTipEventArgs e)
{
if (e.TargetElement == null)
{
DependencyObject o = sender as DependencyObject;
if (o != null)
{
if (PopupControlService.Current.StopLookingForToolTip(o))
{
// Stop looking
e.Handled = true;
e.KeepCurrentActive = true;
}
else
{
if (ToolTipIsEnabled(o))
{
// Store for later
e.TargetElement = o;
e.Handled = true;
}
}
}
}
}
private static bool ToolTipIsEnabled(DependencyObject o)
{
if ((GetToolTip(o) != null) && GetIsEnabled(o))
{
if (PopupControlService.IsElementEnabled(o) || GetShowOnDisabled(o))
{
return true;
}
}
return false;
}
#endregion
}
/// <summary>
/// The callback type for the events when a ToolTip should open or close.
/// </summary>
public delegate void ToolTipEventHandler(object sender, ToolTipEventArgs e);
/// <summary>
/// Event arguments for the events when a ToolTip should open or close.
/// </summary>
public sealed class ToolTipEventArgs : RoutedEventArgs
{
/// <summary>
/// Called internally to create opening or closing event arguments.
/// </summary>
/// <param name="opening">Whether this is the opening or closing event.</param>
internal ToolTipEventArgs(bool opening)
{
if (opening)
{
RoutedEvent = ToolTipService.ToolTipOpeningEvent;
}
else
{
RoutedEvent = ToolTipService.ToolTipClosingEvent;
}
}
/// <summary>
/// Invokes the event handler.
/// </summary>
/// <param name="genericHandler">The delegate to call.</param>
/// <param name="genericTarget">The target of the event.</param>
protected override void InvokeEventHandler(Delegate genericHandler, object genericTarget)
{
ToolTipEventHandler handler = (ToolTipEventHandler)genericHandler;
handler(genericTarget, this);
}
}
internal delegate void FindToolTipEventHandler(object sender, FindToolTipEventArgs e);
internal sealed class FindToolTipEventArgs : RoutedEventArgs
{
internal FindToolTipEventArgs()
{
RoutedEvent = ToolTipService.FindToolTipEvent;
}
internal DependencyObject TargetElement
{
get { return _targetElement; }
set { _targetElement = value; }
}
internal bool KeepCurrentActive
{
get { return _keepCurrentActive; }
set { _keepCurrentActive = value; }
}
/// <summary>
/// Invokes the event handler.
/// </summary>
/// <param name="genericHandler">The delegate to call.</param>
/// <param name="genericTarget">The target of the event.</param>
protected override void InvokeEventHandler(Delegate genericHandler, object genericTarget)
{
FindToolTipEventHandler handler = (FindToolTipEventHandler)genericHandler;
handler(genericTarget, this);
}
private DependencyObject _targetElement;
private bool _keepCurrentActive;
}
}
| |
namespace XenAdmin.SettingsPanels
{
partial class WlbMetricWeightingPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WlbMetricWeightingPage));
this.labelBlurb = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.decentGroupBox1 = new XenAdmin.Controls.DecentGroupBox();
this.panel1 = new System.Windows.Forms.Panel();
this.labelMoreImportant = new System.Windows.Forms.Label();
this.labelLessImportant = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.labelCPU = new System.Windows.Forms.Label();
this.trackbarDiskWritePriority = new System.Windows.Forms.TrackBar();
this.trackbarDiskReadPriority = new System.Windows.Forms.TrackBar();
this.trackbarNetWritePriority = new System.Windows.Forms.TrackBar();
this.trackbarNetReadPriority = new System.Windows.Forms.TrackBar();
this.trackbarMemoryPriority = new System.Windows.Forms.TrackBar();
this.trackbarCPUPriority = new System.Windows.Forms.TrackBar();
this.tableLayoutPanel1.SuspendLayout();
this.decentGroupBox1.SuspendLayout();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trackbarDiskWritePriority)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarDiskReadPriority)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarNetWritePriority)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarNetReadPriority)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarMemoryPriority)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarCPUPriority)).BeginInit();
this.SuspendLayout();
//
// labelBlurb
//
resources.ApplyResources(this.labelBlurb, "labelBlurb");
this.labelBlurb.Name = "labelBlurb";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.decentGroupBox1, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelBlurb, 0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// decentGroupBox1
//
resources.ApplyResources(this.decentGroupBox1, "decentGroupBox1");
this.decentGroupBox1.Controls.Add(this.panel1);
this.decentGroupBox1.Controls.Add(this.label11);
this.decentGroupBox1.Controls.Add(this.label10);
this.decentGroupBox1.Controls.Add(this.label3);
this.decentGroupBox1.Controls.Add(this.label2);
this.decentGroupBox1.Controls.Add(this.label1);
this.decentGroupBox1.Controls.Add(this.labelCPU);
this.decentGroupBox1.Controls.Add(this.trackbarDiskWritePriority);
this.decentGroupBox1.Controls.Add(this.trackbarDiskReadPriority);
this.decentGroupBox1.Controls.Add(this.trackbarNetWritePriority);
this.decentGroupBox1.Controls.Add(this.trackbarNetReadPriority);
this.decentGroupBox1.Controls.Add(this.trackbarMemoryPriority);
this.decentGroupBox1.Controls.Add(this.trackbarCPUPriority);
this.decentGroupBox1.Name = "decentGroupBox1";
this.decentGroupBox1.TabStop = false;
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Controls.Add(this.labelMoreImportant);
this.panel1.Controls.Add(this.labelLessImportant);
this.panel1.Name = "panel1";
//
// labelMoreImportant
//
resources.ApplyResources(this.labelMoreImportant, "labelMoreImportant");
this.labelMoreImportant.BackColor = System.Drawing.Color.Transparent;
this.labelMoreImportant.Name = "labelMoreImportant";
//
// labelLessImportant
//
resources.ApplyResources(this.labelLessImportant, "labelLessImportant");
this.labelLessImportant.BackColor = System.Drawing.Color.Transparent;
this.labelLessImportant.Name = "labelLessImportant";
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.ForeColor = System.Drawing.SystemColors.ControlText;
this.label11.Name = "label11";
//
// label10
//
resources.ApplyResources(this.label10, "label10");
this.label10.ForeColor = System.Drawing.SystemColors.ControlText;
this.label10.Name = "label10";
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.ForeColor = System.Drawing.SystemColors.ControlText;
this.label3.Name = "label3";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.label2.Name = "label2";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.label1.Name = "label1";
//
// labelCPU
//
resources.ApplyResources(this.labelCPU, "labelCPU");
this.labelCPU.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelCPU.Name = "labelCPU";
//
// trackbarDiskWritePriority
//
resources.ApplyResources(this.trackbarDiskWritePriority, "trackbarDiskWritePriority");
this.trackbarDiskWritePriority.BackColor = System.Drawing.SystemColors.Window;
this.trackbarDiskWritePriority.LargeChange = 1;
this.trackbarDiskWritePriority.Name = "trackbarDiskWritePriority";
this.trackbarDiskWritePriority.TickFrequency = 5;
this.trackbarDiskWritePriority.TickStyle = System.Windows.Forms.TickStyle.Both;
this.trackbarDiskWritePriority.ValueChanged += new System.EventHandler(this.trackbarValueChanged);
//
// trackbarDiskReadPriority
//
resources.ApplyResources(this.trackbarDiskReadPriority, "trackbarDiskReadPriority");
this.trackbarDiskReadPriority.BackColor = System.Drawing.SystemColors.Window;
this.trackbarDiskReadPriority.LargeChange = 1;
this.trackbarDiskReadPriority.Name = "trackbarDiskReadPriority";
this.trackbarDiskReadPriority.TickFrequency = 5;
this.trackbarDiskReadPriority.TickStyle = System.Windows.Forms.TickStyle.Both;
this.trackbarDiskReadPriority.ValueChanged += new System.EventHandler(this.trackbarValueChanged);
//
// trackbarNetWritePriority
//
resources.ApplyResources(this.trackbarNetWritePriority, "trackbarNetWritePriority");
this.trackbarNetWritePriority.BackColor = System.Drawing.SystemColors.Window;
this.trackbarNetWritePriority.LargeChange = 1;
this.trackbarNetWritePriority.Name = "trackbarNetWritePriority";
this.trackbarNetWritePriority.TickFrequency = 5;
this.trackbarNetWritePriority.TickStyle = System.Windows.Forms.TickStyle.Both;
this.trackbarNetWritePriority.ValueChanged += new System.EventHandler(this.trackbarValueChanged);
//
// trackbarNetReadPriority
//
resources.ApplyResources(this.trackbarNetReadPriority, "trackbarNetReadPriority");
this.trackbarNetReadPriority.BackColor = System.Drawing.SystemColors.Window;
this.trackbarNetReadPriority.LargeChange = 1;
this.trackbarNetReadPriority.Name = "trackbarNetReadPriority";
this.trackbarNetReadPriority.TickFrequency = 5;
this.trackbarNetReadPriority.TickStyle = System.Windows.Forms.TickStyle.Both;
this.trackbarNetReadPriority.ValueChanged += new System.EventHandler(this.trackbarValueChanged);
//
// trackbarMemoryPriority
//
resources.ApplyResources(this.trackbarMemoryPriority, "trackbarMemoryPriority");
this.trackbarMemoryPriority.BackColor = System.Drawing.SystemColors.Window;
this.trackbarMemoryPriority.LargeChange = 1;
this.trackbarMemoryPriority.Name = "trackbarMemoryPriority";
this.trackbarMemoryPriority.TickFrequency = 5;
this.trackbarMemoryPriority.TickStyle = System.Windows.Forms.TickStyle.Both;
this.trackbarMemoryPriority.ValueChanged += new System.EventHandler(this.trackbarValueChanged);
//
// trackbarCPUPriority
//
resources.ApplyResources(this.trackbarCPUPriority, "trackbarCPUPriority");
this.trackbarCPUPriority.BackColor = System.Drawing.SystemColors.Window;
this.trackbarCPUPriority.LargeChange = 1;
this.trackbarCPUPriority.Name = "trackbarCPUPriority";
this.trackbarCPUPriority.TickFrequency = 5;
this.trackbarCPUPriority.TickStyle = System.Windows.Forms.TickStyle.Both;
this.trackbarCPUPriority.ValueChanged += new System.EventHandler(this.trackbarValueChanged);
//
// WlbMetricWeightingPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Window;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "WlbMetricWeightingPage";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.decentGroupBox1.ResumeLayout(false);
this.decentGroupBox1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.trackbarDiskWritePriority)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarDiskReadPriority)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarNetWritePriority)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarNetReadPriority)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarMemoryPriority)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackbarCPUPriority)).EndInit();
this.ResumeLayout(false);
}
#endregion
private XenAdmin.Controls.DecentGroupBox decentGroupBox1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label labelMoreImportant;
private System.Windows.Forms.Label labelLessImportant;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label labelCPU;
private System.Windows.Forms.TrackBar trackbarDiskWritePriority;
private System.Windows.Forms.TrackBar trackbarDiskReadPriority;
private System.Windows.Forms.TrackBar trackbarNetWritePriority;
private System.Windows.Forms.TrackBar trackbarNetReadPriority;
private System.Windows.Forms.TrackBar trackbarMemoryPriority;
private System.Windows.Forms.TrackBar trackbarCPUPriority;
private System.Windows.Forms.Label labelBlurb;
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Xml;
using Umbraco.Web.Routing;
using umbraco;
using System.Linq;
using umbraco.BusinessLogic;
using umbraco.presentation.preview;
using GlobalSettings = umbraco.GlobalSettings;
namespace Umbraco.Web.PublishedCache.XmlPublishedCache
{
internal class PublishedContentCache : IPublishedContentCache
{
#region Routes cache
private readonly RoutesCache _routesCache = new RoutesCache(!UnitTesting);
// for INTERNAL, UNIT TESTS use ONLY
internal RoutesCache RoutesCache { get { return _routesCache; } }
// for INTERNAL, UNIT TESTS use ONLY
internal static bool UnitTesting = false;
public virtual IPublishedContent GetByRoute(UmbracoContext umbracoContext, bool preview, string route, bool? hideTopLevelNode = null)
{
if (route == null) throw new ArgumentNullException("route");
// try to get from cache if not previewing
var contentId = preview ? 0 : _routesCache.GetNodeId(route);
// if found id in cache then get corresponding content
// and clear cache if not found - for whatever reason
IPublishedContent content = null;
if (contentId > 0)
{
content = GetById(umbracoContext, preview, contentId);
if (content == null)
_routesCache.ClearNode(contentId);
}
// still have nothing? actually determine the id
hideTopLevelNode = hideTopLevelNode ?? GlobalSettings.HideTopLevelNodeFromPath; // default = settings
content = content ?? DetermineIdByRoute(umbracoContext, preview, route, hideTopLevelNode.Value);
// cache if we have a content and not previewing
if (content != null && !preview)
{
var domainRootNodeId = route.StartsWith("/") ? -1 : int.Parse(route.Substring(0, route.IndexOf('/')));
var iscanon = !UnitTesting && !DomainHelper.ExistsDomainInPath(DomainHelper.GetAllDomains(false), content.Path, domainRootNodeId);
// and only if this is the canonical url (the one GetUrl would return)
if (iscanon)
_routesCache.Store(contentId, route);
}
return content;
}
public virtual string GetRouteById(UmbracoContext umbracoContext, bool preview, int contentId)
{
// try to get from cache if not previewing
var route = preview ? null : _routesCache.GetRoute(contentId);
// if found in cache then return
if (route != null)
return route;
// else actually determine the route
route = DetermineRouteById(umbracoContext, preview, contentId);
// cache if we have a route and not previewing
if (route != null && !preview)
_routesCache.Store(contentId, route);
return route;
}
IPublishedContent DetermineIdByRoute(UmbracoContext umbracoContext, bool preview, string route, bool hideTopLevelNode)
{
if (route == null) throw new ArgumentNullException("route");
//the route always needs to be lower case because we only store the urlName attribute in lower case
route = route.ToLowerInvariant();
var pos = route.IndexOf('/');
var path = pos == 0 ? route : route.Substring(pos);
var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos));
IEnumerable<XPathVariable> vars;
var xpath = CreateXpathQuery(startNodeId, path, hideTopLevelNode, out vars);
//check if we can find the node in our xml cache
var content = GetSingleByXPath(umbracoContext, preview, xpath, vars == null ? null : vars.ToArray());
// if hideTopLevelNodePath is true then for url /foo we looked for /*/foo
// but maybe that was the url of a non-default top-level node, so we also
// have to look for /foo (see note in ApplyHideTopLevelNodeFromPath).
if (content == null && hideTopLevelNode && path.Length > 1 && path.IndexOf('/', 1) < 0)
{
xpath = CreateXpathQuery(startNodeId, path, false, out vars);
content = GetSingleByXPath(umbracoContext, preview, xpath, vars == null ? null : vars.ToArray());
}
return content;
}
string DetermineRouteById(UmbracoContext umbracoContext, bool preview, int contentId)
{
var node = GetById(umbracoContext, preview, contentId);
if (node == null)
return null;
// walk up from that node until we hit a node with a domain,
// or we reach the content root, collecting urls in the way
var pathParts = new List<string>();
var n = node;
var hasDomains = DomainHelper.NodeHasDomains(n.Id);
while (!hasDomains && n != null) // n is null at root
{
// get the url
var urlName = n.UrlName;
pathParts.Add(urlName);
// move to parent node
n = n.Parent;
hasDomains = n != null && DomainHelper.NodeHasDomains(n.Id);
}
// no domain, respect HideTopLevelNodeFromPath for legacy purposes
if (!hasDomains && global::umbraco.GlobalSettings.HideTopLevelNodeFromPath)
ApplyHideTopLevelNodeFromPath(umbracoContext, node, pathParts);
// assemble the route
pathParts.Reverse();
var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc
var route = (n == null ? "" : n.Id.ToString(CultureInfo.InvariantCulture)) + path;
return route;
}
static void ApplyHideTopLevelNodeFromPath(UmbracoContext umbracoContext, IPublishedContent node, IList<string> pathParts)
{
// in theory if hideTopLevelNodeFromPath is true, then there should be only once
// top-level node, or else domains should be assigned. but for backward compatibility
// we add this check - we look for the document matching "/" and if it's not us, then
// we do not hide the top level path
// it has to be taken care of in GetByRoute too so if
// "/foo" fails (looking for "/*/foo") we try also "/foo".
// this does not make much sense anyway esp. if both "/foo/" and "/bar/foo" exist, but
// that's the way it works pre-4.10 and we try to be backward compat for the time being
if (node.Parent == null)
{
var rootNode = umbracoContext.ContentCache.GetByRoute("/", true);
if (rootNode == null)
throw new Exception("Failed to get node at /.");
if (rootNode.Id == node.Id) // remove only if we're the default node
pathParts.RemoveAt(pathParts.Count - 1);
}
else
{
pathParts.RemoveAt(pathParts.Count - 1);
}
}
#endregion
#region XPath Strings
class XPathStringsDefinition
{
public int Version { get; private set; }
public static string Root { get { return "/root"; } }
public string RootDocuments { get; private set; }
public string DescendantDocumentById { get; private set; }
public string ChildDocumentByUrlName { get; private set; }
public string ChildDocumentByUrlNameVar { get; private set; }
public string RootDocumentWithLowestSortOrder { get; private set; }
public XPathStringsDefinition(int version)
{
Version = version;
switch (version)
{
// legacy XML schema
case 0:
RootDocuments = "/root/node";
DescendantDocumentById = "//node [@id={0}]";
ChildDocumentByUrlName = "/node [@urlName='{0}']";
ChildDocumentByUrlNameVar = "/node [@urlName=${0}]";
RootDocumentWithLowestSortOrder = "/root/node [not(@sortOrder > ../node/@sortOrder)][1]";
break;
// default XML schema as of 4.10
case 1:
RootDocuments = "/root/* [@isDoc]";
DescendantDocumentById = "//* [@isDoc and @id={0}]";
ChildDocumentByUrlName = "/* [@isDoc and @urlName='{0}']";
ChildDocumentByUrlNameVar = "/* [@isDoc and @urlName=${0}]";
RootDocumentWithLowestSortOrder = "/root/* [@isDoc and not(@sortOrder > ../* [@isDoc]/@sortOrder)][1]";
break;
default:
throw new Exception(string.Format("Unsupported Xml schema version '{0}').", version));
}
}
}
static XPathStringsDefinition _xPathStringsValue;
static XPathStringsDefinition XPathStrings
{
get
{
// in theory XPathStrings should be a static variable that
// we should initialize in a static ctor - but then test cases
// that switch schemas fail - so cache and refresh when needed,
// ie never when running the actual site
var version = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? 0 : 1;
if (_xPathStringsValue == null || _xPathStringsValue.Version != version)
_xPathStringsValue = new XPathStringsDefinition(version);
return _xPathStringsValue;
}
}
#endregion
#region Converters
private static IPublishedContent ConvertToDocument(XmlNode xmlNode, bool isPreviewing)
{
return xmlNode == null
? null
: (new XmlPublishedContent(xmlNode, isPreviewing)).CreateModel();
}
private static IEnumerable<IPublishedContent> ConvertToDocuments(XmlNodeList xmlNodes, bool isPreviewing)
{
return xmlNodes.Cast<XmlNode>()
.Select(xmlNode => (new XmlPublishedContent(xmlNode, isPreviewing)).CreateModel());
}
#endregion
#region Getters
public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId)
{
return ConvertToDocument(GetXml(umbracoContext, preview).GetElementById(nodeId.ToString(CultureInfo.InvariantCulture)), preview);
}
public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview)
{
return ConvertToDocuments(GetXml(umbracoContext, preview).SelectNodes(XPathStrings.RootDocuments), preview);
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
if (string.IsNullOrWhiteSpace(xpath)) return null;
var xml = GetXml(umbracoContext, preview);
var node = vars == null
? xml.SelectSingleNode(xpath)
: xml.SelectSingleNode(xpath, vars);
return ConvertToDocument(node, preview);
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
var xml = GetXml(umbracoContext, preview);
var node = vars == null
? xml.SelectSingleNode(xpath)
: xml.SelectSingleNode(xpath, vars);
return ConvertToDocument(node, preview);
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
if (string.IsNullOrWhiteSpace(xpath)) return Enumerable.Empty<IPublishedContent>();
var xml = GetXml(umbracoContext, preview);
var nodes = vars == null
? xml.SelectNodes(xpath)
: xml.SelectNodes(xpath, vars);
return ConvertToDocuments(nodes, preview);
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
var xml = GetXml(umbracoContext, preview);
var nodes = vars == null
? xml.SelectNodes(xpath)
: xml.SelectNodes(xpath, vars);
return ConvertToDocuments(nodes, preview);
}
public virtual bool HasContent(UmbracoContext umbracoContext, bool preview)
{
var xml = GetXml(umbracoContext, preview);
if (xml == null)
return false;
var node = xml.SelectSingleNode(XPathStrings.RootDocuments);
return node != null;
}
public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview)
{
var xml = GetXml(umbracoContext, preview);
return xml.CreateNavigator();
}
public virtual bool XPathNavigatorIsNavigable { get { return false; } }
#endregion
#region Legacy Xml
static readonly ConditionalWeakTable<UmbracoContext, PreviewContent> PreviewContentCache
= new ConditionalWeakTable<UmbracoContext, PreviewContent>();
private Func<UmbracoContext, bool, XmlDocument> _xmlDelegate;
/// <summary>
/// Gets/sets the delegate used to retrieve the Xml content, generally the setter is only used for unit tests
/// and by default if it is not set will use the standard delegate which ONLY works when in the context an Http Request
/// </summary>
/// <remarks>
/// If not defined, we will use the standard delegate which ONLY works when in the context an Http Request
/// mostly because the 'content' object heavily relies on HttpContext, SQL connections and a bunch of other stuff
/// that when run inside of a unit test fails.
/// </remarks>
internal Func<UmbracoContext, bool, XmlDocument> GetXmlDelegate
{
get
{
return _xmlDelegate ?? (_xmlDelegate = (context, preview) =>
{
if (preview)
{
var previewContent = PreviewContentCache.GetOrCreateValue(context); // will use the ctor with no parameters
previewContent.EnsureInitialized(context.UmbracoUser, StateHelper.Cookies.Preview.GetValue(), true, () =>
{
if (previewContent.ValidPreviewSet)
previewContent.LoadPreviewset();
});
if (previewContent.ValidPreviewSet)
return previewContent.XmlContent;
}
return content.Instance.XmlContent;
});
}
set
{
_xmlDelegate = value;
}
}
internal XmlDocument GetXml(UmbracoContext umbracoContext, bool preview)
{
return GetXmlDelegate(umbracoContext, preview);
}
#endregion
#region XPathQuery
static readonly char[] SlashChar = new[] { '/' };
protected string CreateXpathQuery(int startNodeId, string path, bool hideTopLevelNodeFromPath, out IEnumerable<XPathVariable> vars)
{
string xpath;
vars = null;
if (path == string.Empty || path == "/")
{
// if url is empty
if (startNodeId > 0)
{
// if in a domain then use the root node of the domain
xpath = string.Format(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId);
}
else
{
// if not in a domain - what is the default page?
// let's say it is the first one in the tree, if any -- order by sortOrder
// but!
// umbraco does not consistently guarantee that sortOrder starts with 0
// so the one that we want is the one with the smallest sortOrder
// read http://stackoverflow.com/questions/1128745/how-can-i-use-xpath-to-find-the-minimum-value-of-an-attribute-in-a-set-of-elemen
// so that one does not work, because min(@sortOrder) maybe 1
// xpath = "/root/*[@isDoc and @sortOrder='0']";
// and we can't use min() because that's XPath 2.0
// that one works
xpath = XPathStrings.RootDocumentWithLowestSortOrder;
}
}
else
{
// if url is not empty, then use it to try lookup a matching page
var urlParts = path.Split(SlashChar, StringSplitOptions.RemoveEmptyEntries);
var xpathBuilder = new StringBuilder();
int partsIndex = 0;
List<XPathVariable> varsList = null;
if (startNodeId == 0)
{
if (hideTopLevelNodeFromPath)
xpathBuilder.Append(XPathStrings.RootDocuments); // first node is not in the url
else
xpathBuilder.Append(XPathStringsDefinition.Root);
}
else
{
xpathBuilder.AppendFormat(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId);
// always "hide top level" when there's a domain
}
while (partsIndex < urlParts.Length)
{
var part = urlParts[partsIndex++];
if (part.Contains('\'') || part.Contains('"'))
{
// use vars, escaping gets ugly pretty quickly
varsList = varsList ?? new List<XPathVariable>();
var varName = string.Format("var{0}", partsIndex);
varsList.Add(new XPathVariable(varName, part));
xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlNameVar, varName);
}
else
{
xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlName, part);
}
}
xpath = xpathBuilder.ToString();
if (varsList != null)
vars = varsList.ToArray();
}
return xpath;
}
#endregion
#region Detached
public IPublishedProperty CreateDetachedProperty(PublishedPropertyType propertyType, object value, bool isPreviewing)
{
if (propertyType.IsDetachedOrNested == false)
throw new ArgumentException("Property type is neither detached nor nested.", "propertyType");
return new XmlPublishedProperty(propertyType, isPreviewing, value.ToString());
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.MediaServices;
namespace Microsoft.WindowsAzure.Management.MediaServices
{
public partial class MediaServicesManagementClient : ServiceClient<MediaServicesManagementClient>, IMediaServicesManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IAccountOperations _accounts;
public virtual IAccountOperations Accounts
{
get { return this._accounts; }
}
/// <summary>
/// Initializes a new instance of the MediaServicesManagementClient
/// class.
/// </summary>
public MediaServicesManagementClient()
: base()
{
this._accounts = new AccountOperations(this);
this._apiVersion = "2011-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the MediaServicesManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public MediaServicesManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the MediaServicesManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public MediaServicesManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the MediaServicesManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public MediaServicesManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._accounts = new AccountOperations(this);
this._apiVersion = "2011-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the MediaServicesManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public MediaServicesManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the MediaServicesManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public MediaServicesManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// MediaServicesManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of MediaServicesManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<MediaServicesManagementClient> client)
{
base.Clone(client);
if (client is MediaServicesManagementClient)
{
MediaServicesManagementClient clonedClient = ((MediaServicesManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityTest.IntegrationTestRunner;
namespace UnityTest
{
[Serializable]
public class IntegrationTestsRunnerWindow : EditorWindow, IHasCustomMenu
{
#region GUI Contents
private readonly GUIContent m_GUICreateNewTest = new GUIContent("Create", "Create new test");
private readonly GUIContent m_GUIRunSelectedTests = new GUIContent("Run Selected", "Run selected test(s)");
private readonly GUIContent m_GUIRunAllTests = new GUIContent("Run All", "Run all tests");
private readonly GUIContent m_GUIBlockUI = new GUIContent("Block UI when running", "Block UI when running tests");
private readonly GUIContent m_GUIPauseOnFailure = new GUIContent("Pause on test failure");
#endregion
#region runner steerign vars
private static IntegrationTestsRunnerWindow s_Instance;
[SerializeField] private List<GameObject> m_TestsToRun;
[SerializeField] private List<string> m_DynamicTestsToRun;
[SerializeField] private bool m_ReadyToRun;
private bool m_IsBuilding;
public static bool selectedInHierarchy;
private float m_HorizontalSplitBarPosition = 200;
private Vector2 m_TestInfoScroll, m_TestListScroll;
private IntegrationTestRendererBase[] m_TestLines;
private string m_CurrectSceneName;
private TestFilterSettings m_FilterSettings;
Vector2 m_resultTextSize;
string m_resultText;
GameObject m_lastSelectedGO;
int m_resultTestMaxLength = 15000;
[SerializeField] private GameObject m_SelectedLine;
[SerializeField] private List<TestResult> m_ResultList = new List<TestResult>();
[SerializeField] private List<GameObject> m_FoldMarkers = new List<GameObject>();
private IntegrationTestsRunnerSettings m_Settings;
#endregion
static IntegrationTestsRunnerWindow()
{
InitBackgroundRunners();
}
private static void InitBackgroundRunners()
{
EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyWindowItemDraw;
EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemDraw;
EditorApplication.hierarchyWindowChanged -= OnHierarchyChangeUpdate;
EditorApplication.hierarchyWindowChanged += OnHierarchyChangeUpdate;
EditorApplication.update -= BackgroundSceneChangeWatch;
EditorApplication.update += BackgroundSceneChangeWatch;
EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged;
EditorApplication.playmodeStateChanged += OnPlaymodeStateChanged;
}
private static void OnPlaymodeStateChanged()
{
if (s_Instance && EditorApplication.isPlaying == EditorApplication.isPlayingOrWillChangePlaymode)
s_Instance.RebuildTestList();
}
public void OnDestroy()
{
EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyWindowItemDraw;
EditorApplication.update -= BackgroundSceneChangeWatch;
EditorApplication.hierarchyWindowChanged -= OnHierarchyChangeUpdate;
EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged;
TestComponent.DestroyAllDynamicTests();
}
private static void BackgroundSceneChangeWatch()
{
if (!s_Instance) return;
if (s_Instance.m_CurrectSceneName != null && s_Instance.m_CurrectSceneName == EditorApplication.currentScene) return;
if (EditorApplication.isPlayingOrWillChangePlaymode) return;
TestComponent.DestroyAllDynamicTests();
s_Instance.m_CurrectSceneName = EditorApplication.currentScene;
s_Instance.m_ResultList.Clear();
s_Instance.RebuildTestList();
}
public void OnEnable()
{
title = "Integration Tests";
s_Instance = this;
m_Settings = ProjectSettingsBase.Load<IntegrationTestsRunnerSettings>();
m_FilterSettings = new TestFilterSettings("UnityTest.IntegrationTestsRunnerWindow");
InitBackgroundRunners();
if (!EditorApplication.isPlayingOrWillChangePlaymode && !m_ReadyToRun) RebuildTestList();
}
public void OnSelectionChange()
{
if (EditorApplication.isPlayingOrWillChangePlaymode
|| Selection.objects == null
|| Selection.objects.Length == 0) return;
if (Selection.gameObjects.Length == 1)
{
var go = Selection.gameObjects.Single();
var temp = go.transform;
while (temp != null)
{
var tc = temp.GetComponent<TestComponent>();
if (tc != null) break;
temp = temp.parent;
}
if (temp != null)
{
SelectInHierarchy(temp.gameObject);
Selection.activeGameObject = temp.gameObject;
m_SelectedLine = temp.gameObject;
}
}
}
public static void OnHierarchyChangeUpdate()
{
if (!s_Instance || s_Instance.m_TestLines == null || EditorApplication.isPlayingOrWillChangePlaymode) return;
// create a test runner if it doesn't exist
TestRunner.GetTestRunner();
// make tests are not places under a go that is not a test itself
foreach (var test in TestComponent.FindAllTestsOnScene())
{
if (test.gameObject.transform.parent != null && test.gameObject.transform.parent.gameObject.GetComponent<TestComponent>() == null)
{
test.gameObject.transform.parent = null;
Debug.LogWarning("Tests need to be on top of the hierarchy or directly under another test.");
}
}
if (selectedInHierarchy) selectedInHierarchy = false;
else s_Instance.RebuildTestList();
}
public static TestResult GetResultForTest(TestComponent tc)
{
if(!s_Instance) return new TestResult(tc);
return s_Instance.m_ResultList.FirstOrDefault(r => r.GameObject == tc.gameObject);
}
public static void OnHierarchyWindowItemDraw(int id, Rect rect)
{
var o = EditorUtility.InstanceIDToObject(id);
if (o is GameObject)
{
var go = o as GameObject;
if (Event.current.type == EventType.MouseDown
&& Event.current.button == 0
&& rect.Contains(Event.current.mousePosition))
{
var temp = go.transform;
while (temp != null)
{
var c = temp.GetComponent<TestComponent>();
if (c != null) break;
temp = temp.parent;
}
if (temp != null) SelectInHierarchy(temp.gameObject);
}
}
}
private static void SelectInHierarchy(GameObject gameObject)
{
if (!s_Instance) return;
if (gameObject == s_Instance.m_SelectedLine && gameObject.activeInHierarchy) return;
if (EditorApplication.isPlayingOrWillChangePlaymode) return;
if (!gameObject.activeSelf)
{
selectedInHierarchy = true;
gameObject.SetActive(true);
}
var tests = TestComponent.FindAllTestsOnScene();
var skipList = gameObject.GetComponentsInChildren(typeof(TestComponent), true).ToList();
tests.RemoveAll(skipList.Contains);
foreach (var test in tests)
{
var enable = test.GetComponentsInChildren(typeof(TestComponent), true).Any(c => c.gameObject == gameObject);
if (test.gameObject.activeSelf != enable) test.gameObject.SetActive(enable);
}
}
private void RunTests(IList<ITestComponent> tests)
{
if (!tests.Any() || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode)
return;
FocusWindowIfItsOpen(GetType());
var testComponents = tests.Where(t => t is TestComponent).Cast<TestComponent>().ToList();
var dynaminTests = testComponents.Where(t => t.dynamic).ToList();
m_DynamicTestsToRun = dynaminTests.Select(c => c.dynamicTypeName).ToList();
testComponents.RemoveAll(dynaminTests.Contains);
m_TestsToRun = testComponents.Select( tc => tc.gameObject ).ToList();
m_ReadyToRun = true;
TestComponent.DisableAllTests();
EditorApplication.isPlaying = true;
}
public void Update()
{
if (m_ReadyToRun && EditorApplication.isPlaying)
{
m_ReadyToRun = false;
var testRunner = TestRunner.GetTestRunner();
testRunner.TestRunnerCallback.Add(new RunnerCallback(this));
var testComponents = m_TestsToRun.Select(go => go.GetComponent<TestComponent>()).ToList();
testRunner.InitRunner(testComponents, m_DynamicTestsToRun);
}
}
private void RebuildTestList()
{
m_TestLines = null;
if (!TestComponent.AnyTestsOnScene()
&& !TestComponent.AnyDynamicTestForCurrentScene()) return;
if (!EditorApplication.isPlayingOrWillChangePlaymode)
{
var dynamicTestsOnScene = TestComponent.FindAllDynamicTestsOnScene();
var dynamicTestTypes = TestComponent.GetTypesWithHelpAttribute(EditorApplication.currentScene);
foreach (var dynamicTestType in dynamicTestTypes)
{
var existingTests = dynamicTestsOnScene.Where(component => component.dynamicTypeName == dynamicTestType.AssemblyQualifiedName);
if (existingTests.Any())
{
var testComponent = existingTests.Single();
foreach (var c in testComponent.gameObject.GetComponents<Component>())
{
var type = Type.GetType(testComponent.dynamicTypeName);
if (c is TestComponent || c is Transform || type.IsInstanceOfType(c)) continue;
DestroyImmediate(c);
}
dynamicTestsOnScene.Remove(existingTests.Single());
continue;
}
TestComponent.CreateDynamicTest(dynamicTestType);
}
foreach (var testComponent in dynamicTestsOnScene)
DestroyImmediate(testComponent.gameObject);
}
var topTestList = TestComponent.FindAllTopTestsOnScene();
var newResultList = new List<TestResult>();
m_TestLines = ParseTestList(topTestList, newResultList);
var oldDynamicResults = m_ResultList.Where(result => result.dynamicTest);
foreach (var oldResult in m_ResultList)
{
var result = newResultList.Find(r => r.Id == oldResult.Id);
if (result == null) continue;
result.Update(oldResult);
}
newResultList.AddRange(oldDynamicResults.Where(r => !newResultList.Contains(r)));
m_ResultList = newResultList;
IntegrationTestRendererBase.RunTest = RunTests;
IntegrationTestGroupLine.FoldMarkers = m_FoldMarkers;
IntegrationTestLine.Results = m_ResultList;
m_FilterSettings.UpdateCounters(m_ResultList.Cast<ITestResult>());
m_FoldMarkers.RemoveAll(o => o == null);
selectedInHierarchy = true;
Repaint();
}
private IntegrationTestRendererBase[] ParseTestList(List<TestComponent> testList, List<TestResult> results)
{
var tempList = new List<IntegrationTestRendererBase>();
foreach (var testObject in testList)
{
if (!testObject.IsTestGroup())
{
var result = new TestResult(testObject);
if (results != null)
results.Add(result);
tempList.Add(new IntegrationTestLine(testObject.gameObject, result));
continue;
}
var group = new IntegrationTestGroupLine(testObject.gameObject);
var children = testObject.gameObject.GetComponentsInChildren(typeof(TestComponent), true).Cast<TestComponent>().ToList();
children = children.Where(c => c.gameObject.transform.parent == testObject.gameObject.transform).ToList();
group.AddChildren(ParseTestList(children, results));
tempList.Add(group);
}
tempList.Sort();
return tempList.ToArray();
}
public void OnGUI()
{
if (BuildPipeline.isBuildingPlayer)
{
m_IsBuilding = true;
}
else if (m_IsBuilding)
{
m_IsBuilding = false;
Repaint();
}
PrintHeadPanel();
EditorGUILayout.BeginVertical(Styles.testList);
m_TestListScroll = EditorGUILayout.BeginScrollView(m_TestListScroll);
bool repaint = PrintTestList(m_TestLines);
GUILayout.FlexibleSpace();
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
RenderDetails();
if (repaint) Repaint();
}
public void PrintHeadPanel()
{
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode);
if (GUILayout.Button(m_GUIRunAllTests, EditorStyles.toolbarButton))
{
RunTests(TestComponent.FindAllTestsOnScene().Cast<ITestComponent>().ToList());
}
EditorGUI.BeginDisabledGroup(!Selection.gameObjects.Any (t => t.GetComponent(typeof(ITestComponent))));
if (GUILayout.Button(m_GUIRunSelectedTests, EditorStyles.toolbarButton))
{
RunTests(Selection.gameObjects.Select(t => t.GetComponent(typeof(TestComponent))).Cast<ITestComponent>().ToList());
}
EditorGUI.EndDisabledGroup();
if (GUILayout.Button(m_GUICreateNewTest, EditorStyles.toolbarButton))
{
var test = TestComponent.CreateTest();
if (Selection.gameObjects.Length == 1
&& Selection.activeGameObject != null
&& Selection.activeGameObject.GetComponent<TestComponent>())
{
test.transform.parent = Selection.activeGameObject.transform.parent;
}
Selection.activeGameObject = test;
RebuildTestList();
}
EditorGUI.EndDisabledGroup();
GUILayout.FlexibleSpace ();
m_FilterSettings.OnGUI ();
EditorGUILayout.EndHorizontal ();
}
public void AddItemsToMenu(GenericMenu menu)
{
menu.AddItem(m_GUIBlockUI, m_Settings.blockUIWhenRunning, m_Settings.ToggleBlockUIWhenRunning);
menu.AddItem(m_GUIPauseOnFailure, m_Settings.pauseOnTestFailure, m_Settings.TogglePauseOnTestFailure);
}
private bool PrintTestList(IntegrationTestRendererBase[] renderedLines)
{
if (renderedLines == null) return false;
var filter = m_FilterSettings.BuildRenderingOptions();
bool repaint = false;
foreach (var renderedLine in renderedLines)
{
repaint |= renderedLine.Render(filter);
}
return repaint;
}
private void RenderDetails()
{
var ctrlId = GUIUtility.GetControlID(FocusType.Passive);
Rect rect = GUILayoutUtility.GetLastRect();
rect.y = rect.height + rect.y - 1;
rect.height = 3;
EditorGUIUtility.AddCursorRect(rect, MouseCursor.ResizeVertical);
var e = Event.current;
switch (e.type)
{
case EventType.MouseDown:
if (GUIUtility.hotControl == 0 && rect.Contains(e.mousePosition))
GUIUtility.hotControl = ctrlId;
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == ctrlId)
{
m_HorizontalSplitBarPosition -= e.delta.y;
if (m_HorizontalSplitBarPosition < 20) m_HorizontalSplitBarPosition = 20;
Repaint();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == ctrlId)
GUIUtility.hotControl = 0;
break;
}
m_TestInfoScroll = EditorGUILayout.BeginScrollView(m_TestInfoScroll, GUILayout.MinHeight(m_HorizontalSplitBarPosition));
if (m_SelectedLine != null)
UpdateResultText(m_SelectedLine);
EditorGUILayout.SelectableLabel(m_resultText, Styles.info,
GUILayout.ExpandHeight(true),
GUILayout.ExpandWidth(true),
GUILayout.MinWidth(m_resultTextSize.x),
GUILayout.MinHeight(m_resultTextSize.y));
EditorGUILayout.EndScrollView();
}
private void UpdateResultText(GameObject go)
{
if(go == m_lastSelectedGO) return;
m_lastSelectedGO = go;
var result = m_ResultList.Find(r => r.GameObject == go);
if (result == null)
{
m_resultText = string.Empty;
m_resultTextSize = Styles.info.CalcSize(new GUIContent(string.Empty));
return;
}
var sb = new StringBuilder(result.Name.Trim());
if (!string.IsNullOrEmpty(result.messages))
{
sb.Append("\n---\n");
sb.Append(result.messages.Trim());
}
if (!string.IsNullOrEmpty(result.stacktrace))
{
sb.Append("\n---\n");
sb.Append(result.stacktrace.Trim());
}
if(sb.Length>m_resultTestMaxLength)
{
sb.Length = m_resultTestMaxLength;
sb.AppendFormat("...\n\n---MESSAGE TRUNCATED AT {0} CHARACTERS---", m_resultTestMaxLength);
}
m_resultText = sb.ToString().Trim();
m_resultTextSize = Styles.info.CalcSize(new GUIContent(m_resultText));
}
public void OnInspectorUpdate()
{
if (focusedWindow != this) Repaint();
}
private void SetCurrentTest(TestComponent tc)
{
foreach (var line in m_TestLines)
line.SetCurrentTest(tc);
}
class RunnerCallback : ITestRunnerCallback
{
private readonly IntegrationTestsRunnerWindow m_Window;
private int m_TestNumber;
private int m_CurrentTestNumber;
private readonly bool m_ConsoleErrorOnPauseValue;
private readonly bool m_RunInBackground;
private TestComponent m_CurrentTest;
public RunnerCallback(IntegrationTestsRunnerWindow window)
{
m_Window = window;
m_ConsoleErrorOnPauseValue = GuiHelper.GetConsoleErrorPause();
GuiHelper.SetConsoleErrorPause(false);
m_RunInBackground = PlayerSettings.runInBackground;
PlayerSettings.runInBackground = true;
}
public void RunStarted(string platform, List<TestComponent> testsToRun)
{
EditorApplication.update += OnEditorUpdate;
m_TestNumber = testsToRun.Count;
foreach (var test in testsToRun)
{
var result = m_Window.m_ResultList.Find(r => r.TestComponent == test);
if (result != null) result.Reset();
}
}
public void RunFinished(List<TestResult> testResults)
{
m_Window.SetCurrentTest(null);
m_CurrentTest = null;
EditorApplication.update -= OnEditorUpdate;
EditorApplication.isPlaying = false;
EditorUtility.ClearProgressBar();
GuiHelper.SetConsoleErrorPause(m_ConsoleErrorOnPauseValue);
PlayerSettings.runInBackground = m_RunInBackground;
}
public void TestStarted(TestResult test)
{
m_Window.SetCurrentTest(test.TestComponent);
m_CurrentTest = test.TestComponent;
}
public void TestFinished(TestResult test)
{
m_CurrentTestNumber++;
var result = m_Window.m_ResultList.Find(r => r.Id == test.Id);
if (result != null)
result.Update(test);
else
m_Window.m_ResultList.Add(test);
if(test.IsFailure && m_Window.m_Settings.pauseOnTestFailure)
{
EditorUtility.ClearProgressBar();
EditorApplication.isPaused = true;
}
}
public void TestRunInterrupted(List<ITestComponent> testsNotRun)
{
Debug.Log("Test run interrupted");
RunFinished(new List<TestResult>());
}
private void OnEditorUpdate()
{
if(!EditorApplication.isPlaying)
{
TestRunInterrupted(null);
return;
}
if (m_Window.m_Settings.blockUIWhenRunning
&& m_CurrentTest != null
&& !EditorApplication.isPaused
&& EditorUtility.DisplayCancelableProgressBar("Integration Test Runner",
"Running " + m_CurrentTest.Name,
(float)m_CurrentTestNumber / m_TestNumber))
{
TestRunInterrupted(null);
}
}
}
[MenuItem("Unity Test Tools/Integration Test Runner %#&t")]
public static IntegrationTestsRunnerWindow ShowWindow()
{
var w = GetWindow(typeof(IntegrationTestsRunnerWindow));
w.Show();
return w as IntegrationTestsRunnerWindow;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Markup.Xaml.MarkupExtensions;
using Avalonia.Styling;
using Avalonia.VisualTree;
namespace Avalonia.Diagnostics.ViewModels
{
internal class ControlDetailsViewModel : ViewModelBase, IDisposable
{
private readonly IVisual _control;
private readonly IDictionary<object, List<PropertyViewModel>> _propertyIndex;
private PropertyViewModel? _selectedProperty;
private bool _snapshotStyles;
private bool _showInactiveStyles;
private string? _styleStatus;
public ControlDetailsViewModel(TreePageViewModel treePage, IVisual control)
{
_control = control;
TreePage = treePage;
var properties = GetAvaloniaProperties(control)
.Concat(GetClrProperties(control))
.OrderBy(x => x, PropertyComparer.Instance)
.ThenBy(x => x.Name)
.ToList();
_propertyIndex = properties.GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.ToList());
var view = new DataGridCollectionView(properties);
view.GroupDescriptions.Add(new DataGridPathGroupDescription(nameof(AvaloniaPropertyViewModel.Group)));
view.Filter = FilterProperty;
PropertiesView = view;
Layout = new ControlLayoutViewModel(control);
if (control is INotifyPropertyChanged inpc)
{
inpc.PropertyChanged += ControlPropertyChanged;
}
if (control is AvaloniaObject ao)
{
ao.PropertyChanged += ControlPropertyChanged;
}
AppliedStyles = new ObservableCollection<StyleViewModel>();
PseudoClasses = new ObservableCollection<PseudoClassViewModel>();
if (control is StyledElement styledElement)
{
styledElement.Classes.CollectionChanged += OnClassesChanged;
var pseudoClassAttributes = styledElement.GetType().GetCustomAttributes<PseudoClassesAttribute>(true);
foreach (var classAttribute in pseudoClassAttributes)
{
foreach (var className in classAttribute.PseudoClasses)
{
PseudoClasses.Add(new PseudoClassViewModel(className, styledElement));
}
}
var styleDiagnostics = styledElement.GetStyleDiagnostics();
foreach (var appliedStyle in styleDiagnostics.AppliedStyles)
{
var styleSource = appliedStyle.Source;
var setters = new List<SetterViewModel>();
if (styleSource is Style style)
{
foreach (var setter in style.Setters)
{
if (setter is Setter regularSetter
&& regularSetter.Property != null)
{
var setterValue = regularSetter.Value;
var resourceInfo = GetResourceInfo(setterValue);
SetterViewModel setterVm;
if (resourceInfo.HasValue)
{
var resourceKey = resourceInfo.Value.resourceKey;
var resourceValue = styledElement.FindResource(resourceKey);
setterVm = new ResourceSetterViewModel(regularSetter.Property, resourceKey, resourceValue, resourceInfo.Value.isDynamic);
}
else
{
setterVm = new SetterViewModel(regularSetter.Property, setterValue);
}
setters.Add(setterVm);
}
}
AppliedStyles.Add(new StyleViewModel(appliedStyle, style.Selector?.ToString() ?? "No selector", setters));
}
}
UpdateStyles();
}
}
private (object resourceKey, bool isDynamic)? GetResourceInfo(object? value)
{
if (value is StaticResourceExtension staticResource)
{
return (staticResource.ResourceKey, false);
}
else if (value is DynamicResourceExtension dynamicResource
&& dynamicResource.ResourceKey != null)
{
return (dynamicResource.ResourceKey, true);
}
return null;
}
public TreePageViewModel TreePage { get; }
public DataGridCollectionView PropertiesView { get; }
public ObservableCollection<StyleViewModel> AppliedStyles { get; }
public ObservableCollection<PseudoClassViewModel> PseudoClasses { get; }
public PropertyViewModel? SelectedProperty
{
get => _selectedProperty;
set => RaiseAndSetIfChanged(ref _selectedProperty, value);
}
public bool SnapshotStyles
{
get => _snapshotStyles;
set => RaiseAndSetIfChanged(ref _snapshotStyles, value);
}
public bool ShowInactiveStyles
{
get => _showInactiveStyles;
set => RaiseAndSetIfChanged(ref _showInactiveStyles, value);
}
public string? StyleStatus
{
get => _styleStatus;
set => RaiseAndSetIfChanged(ref _styleStatus, value);
}
public ControlLayoutViewModel Layout { get; }
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.PropertyName == nameof(SnapshotStyles))
{
if (!SnapshotStyles)
{
UpdateStyles();
}
}
}
public void UpdateStyleFilters()
{
foreach (var style in AppliedStyles)
{
var hasVisibleSetter = false;
foreach (var setter in style.Setters)
{
setter.IsVisible = TreePage.SettersFilter.Filter(setter.Name);
hasVisibleSetter |= setter.IsVisible;
}
style.IsVisible = hasVisibleSetter;
}
}
public void Dispose()
{
if (_control is INotifyPropertyChanged inpc)
{
inpc.PropertyChanged -= ControlPropertyChanged;
}
if (_control is AvaloniaObject ao)
{
ao.PropertyChanged -= ControlPropertyChanged;
}
if (_control is StyledElement se)
{
se.Classes.CollectionChanged -= OnClassesChanged;
}
}
private IEnumerable<PropertyViewModel> GetAvaloniaProperties(object o)
{
if (o is AvaloniaObject ao)
{
return AvaloniaPropertyRegistry.Instance.GetRegistered(ao)
.Union(AvaloniaPropertyRegistry.Instance.GetRegisteredAttached(ao.GetType()))
.Select(x => new AvaloniaPropertyViewModel(ao, x));
}
else
{
return Enumerable.Empty<AvaloniaPropertyViewModel>();
}
}
private IEnumerable<PropertyViewModel> GetClrProperties(object o)
{
foreach (var p in GetClrProperties(o, o.GetType()))
{
yield return p;
}
foreach (var i in o.GetType().GetInterfaces())
{
foreach (var p in GetClrProperties(o, i))
{
yield return p;
}
}
}
private IEnumerable<PropertyViewModel> GetClrProperties(object o, Type t)
{
return t.GetProperties()
.Where(x => x.GetIndexParameters().Length == 0)
.Select(x => new ClrPropertyViewModel(o, x));
}
private void ControlPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e)
{
if (_propertyIndex.TryGetValue(e.Property, out var properties))
{
foreach (var property in properties)
{
property.Update();
}
}
Layout.ControlPropertyChanged(sender, e);
}
private void ControlPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != null
&& _propertyIndex.TryGetValue(e.PropertyName, out var properties))
{
foreach (var property in properties)
{
property.Update();
}
}
if (!SnapshotStyles)
{
UpdateStyles();
}
}
private void OnClassesChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (!SnapshotStyles)
{
UpdateStyles();
}
}
private void UpdateStyles()
{
int activeCount = 0;
foreach (var style in AppliedStyles)
{
style.Update();
if (style.IsActive)
{
activeCount++;
}
}
var propertyBuckets = new Dictionary<AvaloniaProperty, List<SetterViewModel>>();
foreach (var style in AppliedStyles)
{
if (!style.IsActive)
{
continue;
}
foreach (var setter in style.Setters)
{
if (propertyBuckets.TryGetValue(setter.Property, out var setters))
{
foreach (var otherSetter in setters)
{
otherSetter.IsActive = false;
}
setter.IsActive = true;
setters.Add(setter);
}
else
{
setter.IsActive = true;
setters = new List<SetterViewModel> { setter };
propertyBuckets.Add(setter.Property, setters);
}
}
}
foreach (var pseudoClass in PseudoClasses)
{
pseudoClass.Update();
}
StyleStatus = $"Styles ({activeCount}/{AppliedStyles.Count} active)";
}
private bool FilterProperty(object arg)
{
return !(arg is PropertyViewModel property) || TreePage.PropertiesFilter.Filter(property.Name);
}
private class PropertyComparer : IComparer<PropertyViewModel>
{
public static PropertyComparer Instance { get; } = new PropertyComparer();
public int Compare(PropertyViewModel? x, PropertyViewModel? y)
{
var groupX = GroupIndex(x?.Group);
var groupY = GroupIndex(y?.Group);
if (groupX != groupY)
{
return groupX - groupY;
}
else
{
return string.CompareOrdinal(x?.Name, y?.Name);
}
}
private int GroupIndex(string? group)
{
switch (group)
{
case "Properties": return 0;
case "Attached Properties": return 1;
case "CLR Properties": return 2;
default: return 3;
}
}
}
}
}
| |
// <copyright file="GPGSIOSSetupUI.cs" company="Google Inc.">
// Copyright (C) 2014 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>
#if UNITY_IPHONE && !NO_GPGS
namespace GooglePlayGames.Editor
{
using System;
using System.IO;
using System.Collections;
using UnityEngine;
using UnityEditor;
public class GPGSIOSSetupUI : EditorWindow
{
private string mBundleId = string.Empty;
private string mWebClientId = string.Empty;
private string mClassName = "GooglePlayGames.GPGSIds";
private string mClassDirectory = "Assets";
private string mConfigData = string.Empty;
private bool mRequiresGooglePlus = false;
private Vector2 scroll;
[MenuItem("Window/Google Play Games/Setup/iOS setup...", false, 2)]
public static void MenuItemGPGSIOSSetup()
{
EditorWindow window = EditorWindow.GetWindow(
typeof(GPGSIOSSetupUI), true, GPGSStrings.IOSSetup.Title);
window.minSize = new Vector2(500, 600);
}
public void OnEnable()
{
mBundleId = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSBUNDLEIDKEY);
mWebClientId = GPGSProjectSettings.Instance.Get(GPGSUtil.WEBCLIENTIDKEY);
mClassDirectory = GPGSProjectSettings.Instance.Get(GPGSUtil.CLASSDIRECTORYKEY, mClassDirectory);
mClassName = GPGSProjectSettings.Instance.Get(GPGSUtil.CLASSNAMEKEY);
mConfigData = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSRESOURCEKEY);
mRequiresGooglePlus = GPGSProjectSettings.Instance.GetBool(GPGSUtil.REQUIREGOOGLEPLUSKEY, false);
if (mBundleId.Trim().Length == 0)
{
mBundleId = PlayerSettings.bundleIdentifier;
}
}
/// <summary>
/// Save the specified clientId and bundleId to properties file.
/// This maintains the configuration across instances of running Unity.
/// </summary>
/// <param name="clientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="webClientId">web app clientId.</param>
/// <param name="requiresGooglePlus">App requires G+ access</param>
internal static void Save(string clientId,
string bundleId,
string webClientId,
bool requiresGooglePlus)
{
if (clientId != null)
{
clientId = clientId.Trim();
}
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSCLIENTIDKEY, clientId);
if (bundleId != null)
{
bundleId = bundleId.Trim();
}
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSBUNDLEIDKEY, bundleId);
if (webClientId != null)
{
webClientId = webClientId.Trim();
}
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
GPGSProjectSettings.Instance.Set(GPGSUtil.REQUIREGOOGLEPLUSKEY, requiresGooglePlus);
GPGSProjectSettings.Instance.Save();
}
public void OnGUI()
{
GUIStyle link = new GUIStyle(GUI.skin.label);
link.normal.textColor = new Color(.7f, .7f, 1f);
// Title
GUILayout.BeginVertical();
GUILayout.Space(10);
GUILayout.Label(GPGSStrings.IOSSetup.Blurb);
GUILayout.Space(10);
if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false)))
{
Application.OpenURL("https://play.google.com/apps/publish");
}
Rect last = GUILayoutUtility.GetLastRect();
last.y += last.height - 2;
last.x += 3;
last.width -= 6;
last.height = 2;
GUI.Box(last, string.Empty);
GUILayout.Space(15);
// Bundle ID field
GUILayout.Label(GPGSStrings.IOSSetup.BundleIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.IOSSetup.BundleIdBlurb, EditorStyles.wordWrappedLabel);
mBundleId = EditorGUILayout.TextField(GPGSStrings.IOSSetup.BundleId, mBundleId,
GUILayout.Width(450));
GUILayout.Space(30);
// Requires G+ field
GUILayout.BeginHorizontal();
GUILayout.Label(GPGSStrings.Setup.RequiresGPlusTitle, EditorStyles.boldLabel);
mRequiresGooglePlus = EditorGUILayout.Toggle(mRequiresGooglePlus);
GUILayout.EndHorizontal();
GUILayout.Label(GPGSStrings.Setup.RequiresGPlusBlurb);
// Client ID field
GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb, EditorStyles.wordWrappedLabel);
GUILayout.Space(10);
mWebClientId = EditorGUILayout.TextField(GPGSStrings.Setup.ClientId,
mWebClientId, GUILayout.Width(450));
GUILayout.Space(10);
GUILayout.FlexibleSpace();
GUILayout.Label("Constants class name", EditorStyles.boldLabel);
GUILayout.Label("Enter the fully qualified name of the class to create containing the constants");
GUILayout.Space(10);
mClassDirectory = EditorGUILayout.TextField("Directory to save constants",
mClassDirectory, GUILayout.Width(480));
mClassName = EditorGUILayout.TextField("Constants class name",
mClassName, GUILayout.Width(480));
GUILayout.Label("Resources Definition", EditorStyles.boldLabel);
GUILayout.Label("Paste in the Objective-C Resources from the Play Console");
GUILayout.Space(10);
scroll = GUILayout.BeginScrollView(scroll);
mConfigData = EditorGUILayout.TextArea(mConfigData,
GUILayout.Width(475), GUILayout.Height(Screen.height));
GUILayout.EndScrollView();
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
// Setup button
if (GUILayout.Button(GPGSStrings.Setup.SetupButton))
{
// check that the classname entered is valid
try
{
if (GPGSUtil.LooksLikeValidPackageName(mClassName))
{
DoSetup();
}
}
catch (Exception e)
{
GPGSUtil.Alert(GPGSStrings.Error,
"Invalid classname: " + e.Message);
}
}
if (GUILayout.Button(GPGSStrings.Cancel))
{
this.Close();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.EndVertical();
}
/// <summary>
/// Called by the UI to process the configuration.
/// </summary>
internal void DoSetup()
{
if (PerformSetup(mClassDirectory, mClassName, mConfigData, mWebClientId, mBundleId, null, mRequiresGooglePlus))
{
GPGSUtil.Alert(GPGSStrings.Success, GPGSStrings.IOSSetup.SetupComplete);
Close();
}
else
{
GPGSUtil.Alert(GPGSStrings.Error,
"Missing or invalid resource data. Check that CLIENT_ID is defined.");
}
}
/// <summary>
/// Performs setup using the Android resources downloaded XML file
/// from the play console.
/// </summary>
/// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns>
/// <param name="className">Fully qualified class name for the resource Ids.</param>
/// <param name="resourceXmlData">Resource xml data.</param>
/// <param name="webClientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="nearbySvcId">Nearby svc identifier.</param>
/// <param name="requiresGooglePlus">App Requires Google Plus API.</param>
public static bool PerformSetup(
string classDirectory,
string className,
string resourceXmlData,
string webClientId,
string bundleId,
string nearbySvcId,
bool requiresGooglePlus)
{
if (ParseResources(classDirectory, className, resourceXmlData))
{
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className);
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSRESOURCEKEY, resourceXmlData);
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
if (string.IsNullOrEmpty(bundleId))
{
// get from settings
bundleId = GPGSProjectSettings.Instance.Get(GPGSUtil.IOSBUNDLEIDKEY);
PlayerSettings.bundleIdentifier = bundleId;
}
return PerformSetup(GPGSProjectSettings.Instance.Get(GPGSUtil.IOSCLIENTIDKEY),
bundleId, webClientId, nearbySvcId, requiresGooglePlus);
}
Debug.LogError("Failed to parse resources, returing false.");
return false;
}
private static bool ParseResources(string classDirectory, string className, string res)
{
// parse the resources, they keys are in the form of
// #define <KEY> @"<VALUE>"
// transform the string to make it easier to parse
string input = res.Replace("#define ", string.Empty);
input = input.Replace("@\"", string.Empty);
input = input.Replace("\"", string.Empty);
// now input is name value, one per line
StringReader reader = new StringReader(input);
string line = reader.ReadLine();
string key;
string value;
string clientId = null;
Hashtable resourceKeys = new Hashtable();
while (line != null)
{
string[] parts = line.Split(' ');
key = parts[0];
if (parts.Length > 1)
{
value = parts[1];
}
else
{
value = null;
}
if (!string.IsNullOrEmpty(value))
{
if (key == "CLIENT_ID")
{
clientId = value;
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSCLIENTIDKEY, clientId);
}
else if (key == "BUNDLE_ID")
{
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSBUNDLEIDKEY, value);
}
else if (key.StartsWith("ACH_"))
{
string prop = "achievement_" + key.Substring(4).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("LEAD_"))
{
string prop = "leaderboard_" + key.Substring(5).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("EVENT_"))
{
string prop = "event_" + key.Substring(6).ToLower();
resourceKeys[prop] = value;
}
else if (key.StartsWith("QUEST_"))
{
string prop = "quest_" + key.Substring(6).ToLower();
resourceKeys[prop] = value;
}
else
{
resourceKeys[key] = value;
}
}
line = reader.ReadLine();
}
reader.Close();
if (resourceKeys.Count > 0)
{
GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys);
}
GPGSProjectSettings.Instance.Save();
return !string.IsNullOrEmpty(clientId);
}
/// <summary>
/// Performs the setup. This is called externally to facilitate
/// build automation.
/// </summary>
/// <param name="clientId">Client identifier.</param>
/// <param name="bundleId">Bundle identifier.</param>
/// <param name="webClientId">web app client id.</param>
/// <param name="nearbySvcId">Nearby connections service Id.</param>
/// <param name="requiresGooglePlus">App requires G+ access</param>
public static bool PerformSetup(string clientId, string bundleId,
string webClientId, string nearbySvcId, bool requiresGooglePlus)
{
if (!GPGSUtil.LooksLikeValidClientId(clientId))
{
GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError);
return false;
}
if (!GPGSUtil.LooksLikeValidBundleId(bundleId))
{
GPGSUtil.Alert(GPGSStrings.IOSSetup.BundleIdError);
return false;
}
// nearby is optional - only set it up if present.
if (nearbySvcId != null)
{
bool ok = NearbyConnectionUI.PerformSetup(nearbySvcId, false);
if (!ok)
{
Debug.LogError("NearbyConnection Setup failed, returing false.");
return false;
}
}
Save(clientId, bundleId, webClientId, requiresGooglePlus);
GPGSUtil.UpdateGameInfo();
// Finished!
GPGSProjectSettings.Instance.Set(GPGSUtil.IOSSETUPDONEKEY, true);
GPGSProjectSettings.Instance.Save();
AssetDatabase.Refresh();
return true;
}
}
}
#endif
| |
/*
** $Id: lstrlib.c,v 1.132.1.4 2008/07/11 17:27:21 roberto Exp $
** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace SharpLua
{
using ptrdiff_t = System.Int32;
using lua_Integer = System.Int32;
using LUA_INTFRM_T = System.Int64;
using UNSIGNED_LUA_INTFRM_T = System.UInt64;
public partial class Lua
{
private static int str_len (LuaState L) {
uint l;
luaL_checklstring(L, 1, out l);
lua_pushinteger(L, (int)l);
return 1;
}
private static ptrdiff_t posrelat (ptrdiff_t pos, uint len) {
/* relative string position: negative means back from end */
if (pos < 0) pos += (ptrdiff_t)len + 1;
return (pos >= 0) ? pos : 0;
}
private static int str_sub (LuaState L) {
uint l;
CharPtr s = luaL_checklstring(L, 1, out l);
ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l);
ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l);
if (start < 1) start = 1;
if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
if (start <= end)
lua_pushlstring(L, s+start-1, (uint)(end-start+1));
else lua_pushliteral(L, "");
return 1;
}
private static int str_reverse (LuaState L) {
uint l;
luaL_Buffer b = new luaL_Buffer();
CharPtr s = luaL_checklstring(L, 1, out l);
luaL_buffinit(L, b);
while ((l--) != 0) luaL_addchar(b, s[l]);
luaL_pushresult(b);
return 1;
}
private static int str_lower (LuaState L) {
uint l;
uint i;
luaL_Buffer b = new luaL_Buffer();
CharPtr s = luaL_checklstring(L, 1, out l);
luaL_buffinit(L, b);
for (i=0; i<l; i++)
luaL_addchar(b, tolower(s[i]));
luaL_pushresult(b);
return 1;
}
private static int str_upper (LuaState L) {
uint l;
uint i;
luaL_Buffer b = new luaL_Buffer();
CharPtr s = luaL_checklstring(L, 1, out l);
luaL_buffinit(L, b);
for (i=0; i<l; i++)
luaL_addchar(b, toupper(s[i]));
luaL_pushresult(b);
return 1;
}
private static int str_rep (LuaState L) {
uint l;
luaL_Buffer b = new luaL_Buffer();
CharPtr s = luaL_checklstring(L, 1, out l);
int n = luaL_checkint(L, 2);
luaL_buffinit(L, b);
while (n-- > 0)
luaL_addlstring(b, s, l);
luaL_pushresult(b);
return 1;
}
private static int str_byte (LuaState L) {
uint l;
CharPtr s = luaL_checklstring(L, 1, out l);
ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
int n, i;
if (posi <= 0) posi = 1;
if ((uint)pose > l) pose = (int)l;
if (posi > pose) return 0; /* empty interval; return no values */
n = (int)(pose - posi + 1);
if (posi + n <= pose) /* overflow? */
luaL_error(L, "string slice too long");
luaL_checkstack(L, n, "string slice too long");
for (i=0; i<n; i++)
lua_pushinteger(L, (int)(s[posi + i - 1]));
return n;
}
private static int str_char (LuaState L) {
int n = lua_gettop(L); /* number of arguments */
int i;
luaL_Buffer b = new luaL_Buffer();
luaL_buffinit(L, b);
for (i=1; i<=n; i++) {
int c = luaL_checkint(L, i);
//luaL_argcheck(L, (byte)(c) == c, i, "invalid value");
//luaL_addchar(b, (char)(byte)c);
luaL_argcheck(L, c < 65536, i, "invalid value");
luaL_addchar(b, (char)c);
}
luaL_pushresult(b);
return 1;
}
private static int writer (LuaState L, object b, uint size, object B)
{
if (b.GetType() != typeof(CharPtr))
{
using (MemoryStream stream = new MemoryStream())
{
// todo: figure out a way to do this
/*
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, b);
stream.Flush();
byte[] bytes = stream.GetBuffer();
char[] chars = new char[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
chars[i] = (char)bytes[i];
b = new CharPtr(chars);
* */
}
}
luaL_addlstring((luaL_Buffer)B, (CharPtr)b, size);
return 0;
}
private static int str_dump (LuaState L) {
luaL_Buffer b = new luaL_Buffer();
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L, 1);
luaL_buffinit(L,b);
if (lua_dump(L, writer, b) != 0)
luaL_error(L, "unable to dump given function");
luaL_pushresult(b);
return 1;
}
/*
** {======================================================
** PATTERN MATCHING
** =======================================================
*/
public const int CAP_UNFINISHED = (-1);
public const int CAP_POSITION = (-2);
public class MatchState {
public MatchState()
{
for (int i = 0; i < LUA_MAXCAPTURES; i++)
capture[i] = new capture_();
}
public CharPtr src_init; /* init of source string */
public CharPtr src_end; /* end (`\0') of source string */
public LuaState L;
public int level; /* total number of captures (finished or unfinished) */
public class capture_{
public CharPtr init;
public ptrdiff_t len;
};
public capture_[] capture = new capture_[LUA_MAXCAPTURES];
};
public const char L_ESC = '%';
public const string SPECIALS = "^$*+?.([%-";
private static int check_capture (MatchState ms, int l) {
l -= '1';
if (l < 0 || l >= ms.level || ms.capture[l].len == CAP_UNFINISHED)
return luaL_error(ms.L, "invalid capture index");
return l;
}
private static int capture_to_close (MatchState ms) {
int level = ms.level;
for (level--; level>=0; level--)
if (ms.capture[level].len == CAP_UNFINISHED) return level;
return luaL_error(ms.L, "invalid pattern capture");
}
private static CharPtr classend (MatchState ms, CharPtr p) {
p = new CharPtr(p);
char c = p[0];
p = p.next();
switch (c) {
case L_ESC: {
if (p[0] == '\0')
luaL_error(ms.L, "malformed pattern (ends with " + LUA_QL("%%") + ")");
return p+1;
}
case '[': {
if (p[0] == '^') p = p.next();
do { /* look for a `]' */
if (p[0] == '\0')
luaL_error(ms.L, "malformed pattern (missing " + LUA_QL("]") + ")");
c = p[0];
p = p.next();
if (c == L_ESC && p[0] != '\0')
p = p.next(); /* skip escapes (e.g. `%]') */
} while (p[0] != ']');
return p+1;
}
default: {
return p;
}
}
}
private static int match_class (int c, int cl) {
bool res;
switch (tolower(cl)) {
case 'a' : res = isalpha(c); break;
case 'c' : res = iscntrl(c); break;
case 'd' : res = isdigit(c); break;
case 'l' : res = islower(c); break;
case 'p' : res = ispunct(c); break;
case 's' : res = isspace(c); break;
case 'u' : res = isupper(c); break;
case 'w' : res = isalnum(c); break;
case 'x' : res = isxdigit((char)c); break;
case 'z' : res = (c == 0); break;
default: return (cl == c) ? 1 : 0;
}
return (islower(cl) ? (res ? 1 : 0) : ((!res) ? 1 : 0));
}
private static int matchbracketclass (int c, CharPtr p, CharPtr ec) {
int sig = 1;
if (p[1] == '^') {
sig = 0;
p = p.next(); /* skip the `^' */
}
while ((p=p.next()) < ec) {
if (p == L_ESC) {
p = p.next();
if (match_class(c, (byte)(p[0])) != 0)
return sig;
}
else if ((p[1] == '-') && (p + 2 < ec)) {
p+=2;
if ((byte)((p[-2])) <= c && (c <= (byte)p[0]))
return sig;
}
else if ((byte)(p[0]) == c) return sig;
}
return (sig == 0) ? 1 : 0;
}
private static int singlematch (int c, CharPtr p, CharPtr ep) {
switch (p[0]) {
case '.': return 1; /* matches any char */
case L_ESC: return match_class(c, (byte)(p[1]));
case '[': return matchbracketclass(c, p, ep-1);
default: return ((byte)(p[0]) == c) ? 1 : 0;
}
}
private static CharPtr matchbalance (MatchState ms, CharPtr s,
CharPtr p) {
if ((p[0] == 0) || (p[1] == 0))
luaL_error(ms.L, "unbalanced pattern");
if (s[0] != p[0]) return null;
else {
int b = p[0];
int e = p[1];
int cont = 1;
while ((s=s.next()) < ms.src_end) {
if (s[0] == e) {
if (--cont == 0) return s+1;
}
else if (s[0] == b) cont++;
}
}
return null; /* string ends out of balance */
}
private static CharPtr max_expand (MatchState ms, CharPtr s,
CharPtr p, CharPtr ep) {
ptrdiff_t i = 0; /* counts maximum expand for item */
while ( (s+i < ms.src_end) && (singlematch((byte)(s[i]), p, ep) != 0) )
i++;
/* keeps trying to match with the maximum repetitions */
while (i>=0) {
CharPtr res = match(ms, (s+i), ep+1);
if (res != null) return res;
i--; /* else didn't match; reduce 1 repetition to try again */
}
return null;
}
private static CharPtr min_expand (MatchState ms, CharPtr s,
CharPtr p, CharPtr ep) {
for (;;) {
CharPtr res = match(ms, s, ep+1);
if (res != null)
return res;
else if ( (s < ms.src_end) && (singlematch((byte)(s[0]), p, ep) != 0) )
s = s.next(); /* try with one more repetition */
else return null;
}
}
private static CharPtr start_capture (MatchState ms, CharPtr s,
CharPtr p, int what) {
CharPtr res;
int level = ms.level;
if (level >= LUA_MAXCAPTURES) luaL_error(ms.L, "too many captures");
ms.capture[level].init = s;
ms.capture[level].len = what;
ms.level = level+1;
if ((res=match(ms, s, p)) == null) /* match failed? */
ms.level--; /* undo capture */
return res;
}
private static CharPtr end_capture(MatchState ms, CharPtr s,
CharPtr p) {
int l = capture_to_close(ms);
CharPtr res;
ms.capture[l].len = s - ms.capture[l].init; /* close capture */
if ((res = match(ms, s, p)) == null) /* match failed? */
ms.capture[l].len = CAP_UNFINISHED; /* undo capture */
return res;
}
private static CharPtr match_capture(MatchState ms, CharPtr s, int l)
{
uint len;
l = check_capture(ms, l);
len = (uint)ms.capture[l].len;
if ((uint)(ms.src_end-s) >= len &&
memcmp(ms.capture[l].init, s, len) == 0)
return s+len;
else return null;
}
private static CharPtr match (MatchState ms, CharPtr s, CharPtr p) {
s = new CharPtr(s);
p = new CharPtr(p);
init: /* using goto's to optimize tail recursion */
switch (p[0]) {
case '(': { /* start capture */
if (p[1] == ')') /* position capture? */
return start_capture(ms, s, p+2, CAP_POSITION);
else
return start_capture(ms, s, p+1, CAP_UNFINISHED);
}
case ')': { /* end capture */
return end_capture(ms, s, p+1);
}
case L_ESC: {
switch (p[1]) {
case 'b': { /* balanced string? */
s = matchbalance(ms, s, p+2);
if (s == null) return null;
p+=4; goto init; /* else return match(ms, s, p+4); */
}
case 'f': { /* frontier? */
CharPtr ep; char previous;
p += 2;
if (p[0] != '[')
luaL_error(ms.L, "missing " + LUA_QL("[") + " after " +
LUA_QL("%%f") + " in pattern");
ep = classend(ms, p); /* points to what is next */
previous = (s == ms.src_init) ? '\0' : s[-1];
if ((matchbracketclass((byte)(previous), p, ep-1)!=0) ||
(matchbracketclass((byte)(s[0]), p, ep-1)==0)) return null;
p=ep; goto init; /* else return match(ms, s, ep); */
}
default: {
if (isdigit((byte)(p[1]))) { /* capture results (%0-%9)? */
s = match_capture(ms, s, (byte)(p[1]));
if (s == null) return null;
p+=2; goto init; /* else return match(ms, s, p+2) */
}
goto dflt; /* case default */
}
}
}
case '\0': { /* end of pattern */
return s; /* match succeeded */
}
case '$': {
if (p[1] == '\0') /* is the `$' the last char in pattern? */
return (s == ms.src_end) ? s : null; /* check end of string */
else goto dflt;
}
default: dflt: { /* it is a pattern item */
CharPtr ep = classend(ms, p); /* points to what is next */
int m = (s<ms.src_end) && (singlematch((byte)(s[0]), p, ep)!=0) ? 1 : 0;
switch (ep[0]) {
case '?': { /* optional */
CharPtr res;
if ((m!=0) && ((res=match(ms, s+1, ep+1)) != null))
return res;
p=ep+1; goto init; /* else return match(ms, s, ep+1); */
}
case '*': { /* 0 or more repetitions */
return max_expand(ms, s, p, ep);
}
case '+': { /* 1 or more repetitions */
return ((m!=0) ? max_expand(ms, s+1, p, ep) : null);
}
case '-': { /* 0 or more repetitions (minimum) */
return min_expand(ms, s, p, ep);
}
default: {
if (m==0) return null;
s = s.next(); p=ep; goto init; /* else return match(ms, s+1, ep); */
}
}
}
}
}
private static CharPtr lmemfind (CharPtr s1, uint l1,
CharPtr s2, uint l2) {
if (l2 == 0) return s1; /* empty strings are everywhere */
else if (l2 > l1) return null; /* avoids a negative `l1' */
else {
CharPtr init; /* to search for a `*s2' inside `s1' */
l2--; /* 1st char will be checked by `memchr' */
l1 = l1-l2; /* `s2' cannot be found after that */
while (l1 > 0 && (init = memchr(s1, s2[0], l1)) != null) {
init = init.next(); /* 1st char is already checked */
if (memcmp(init, s2+1, l2) == 0)
return init-1;
else { /* correct `l1' and `s1' to try again */
l1 -= (uint)(init-s1);
s1 = init;
}
}
return null; /* not found */
}
}
private static void push_onecapture (MatchState ms, int i, CharPtr s,
CharPtr e) {
if (i >= ms.level) {
if (i == 0) /* ms.level == 0, too */
lua_pushlstring(ms.L, s, (uint)(e - s)); /* add whole match */
else
luaL_error(ms.L, "invalid capture index");
}
else {
ptrdiff_t l = ms.capture[i].len;
if (l == CAP_UNFINISHED) luaL_error(ms.L, "unfinished capture");
if (l == CAP_POSITION)
lua_pushinteger(ms.L, ms.capture[i].init - ms.src_init + 1);
else
lua_pushlstring(ms.L, ms.capture[i].init, (uint)l);
}
}
private static int push_captures (MatchState ms, CharPtr s, CharPtr e) {
int i;
int nlevels = ((ms.level == 0) && (s!=null)) ? 1 : ms.level;
luaL_checkstack(ms.L, nlevels, "too many captures");
for (i = 0; i < nlevels; i++)
push_onecapture(ms, i, s, e);
return nlevels; /* number of strings pushed */
}
private static int str_find_aux (LuaState L, int find) {
uint l1, l2;
CharPtr s = luaL_checklstring(L, 1, out l1);
CharPtr p = luaL_checklstring(L, 2, out l2);
ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
if (init < 0) init = 0;
else if ((uint)(init) > l1) init = (ptrdiff_t)l1;
if ((find!=0) && ((lua_toboolean(L, 4)!=0) || /* explicit request? */
strpbrk(p, SPECIALS) == null)) { /* or no special characters? */
/* do a plain search */
CharPtr s2 = lmemfind(s+init, (uint)(l1-init), p, (uint)(l2));
if (s2 != null) {
lua_pushinteger(L, s2-s+1);
lua_pushinteger(L, (int)(s2-s+l2));
return 2;
}
}
else {
MatchState ms = new MatchState();
int anchor = 0;
if (p[0] == '^')
{
p = p.next();
anchor = 1;
}
CharPtr s1=s+init;
ms.L = L;
ms.src_init = s;
ms.src_end = s+l1;
do {
CharPtr res;
ms.level = 0;
if ((res=match(ms, s1, p)) != null) {
if (find != 0) {
lua_pushinteger(L, s1-s+1); /* start */
lua_pushinteger(L, res-s); /* end */
return push_captures(ms, null, null) + 2;
}
else
return push_captures(ms, s1, res);
}
} while (((s1=s1.next()) <= ms.src_end) && (anchor==0));
}
lua_pushnil(L); /* not found */
return 1;
}
private static int str_find (LuaState L) {
return str_find_aux(L, 1);
}
private static int str_match (LuaState L) {
return str_find_aux(L, 0);
}
private static int gmatch_aux (LuaState L) {
MatchState ms = new MatchState();
uint ls;
CharPtr s = lua_tolstring(L, lua_upvalueindex(1), out ls);
CharPtr p = lua_tostring(L, lua_upvalueindex(2));
CharPtr src;
ms.L = L;
ms.src_init = s;
ms.src_end = s+ls;
for (src = s + (uint)lua_tointeger(L, lua_upvalueindex(3));
src <= ms.src_end;
src = src.next()) {
CharPtr e;
ms.level = 0;
if ((e = match(ms, src, p)) != null) {
lua_Integer newstart = e-s;
if (e == src) newstart++; /* empty match? go at least one position */
lua_pushinteger(L, newstart);
lua_replace(L, lua_upvalueindex(3));
return push_captures(ms, src, e);
}
}
return 0; /* not found */
}
private static int gmatch (LuaState L) {
luaL_checkstring(L, 1);
luaL_checkstring(L, 2);
lua_settop(L, 2);
lua_pushinteger(L, 0);
lua_pushcclosure(L, gmatch_aux, 3);
return 1;
}
private static int gfind_nodef (LuaState L) {
return luaL_error(L, LUA_QL("string.gfind") + " was renamed to " +
LUA_QL("string.gmatch"));
}
private static void add_s (MatchState ms, luaL_Buffer b, CharPtr s,
CharPtr e) {
uint l, i;
CharPtr news = lua_tolstring(ms.L, 3, out l);
for (i = 0; i < l; i++) {
if (news[i] != L_ESC)
luaL_addchar(b, news[i]);
else {
i++; /* skip ESC */
if (!isdigit((byte)(news[i])))
luaL_addchar(b, news[i]);
else if (news[i] == '0')
luaL_addlstring(b, s, (uint)(e - s));
else {
push_onecapture(ms, news[i] - '1', s, e);
luaL_addvalue(b); /* add capture to accumulated result */
}
}
}
}
private static void add_value (MatchState ms, luaL_Buffer b, CharPtr s,
CharPtr e) {
LuaState L = ms.L;
switch (lua_type(L, 3)) {
case LUA_TNUMBER:
case LUA_TSTRING: {
add_s(ms, b, s, e);
return;
}
case LUA_TFUNCTION: {
int n;
lua_pushvalue(L, 3);
n = push_captures(ms, s, e);
lua_call(L, n, 1);
break;
}
case LUA_TTABLE: {
push_onecapture(ms, 0, s, e);
lua_gettable(L, 3);
break;
}
}
if (lua_toboolean(L, -1)==0) { /* nil or false? */
lua_pop(L, 1);
lua_pushlstring(L, s, (uint)(e - s)); /* keep original text */
}
else if (lua_isstring(L, -1)==0)
luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
luaL_addvalue(b); /* add result to accumulator */
}
private static int str_gsub (LuaState L) {
uint srcl;
CharPtr src = luaL_checklstring(L, 1, out srcl);
CharPtr p = luaL_checkstring(L, 2);
int tr = lua_type(L, 3);
int max_s = luaL_optint(L, 4, (int)(srcl+1));
int anchor = 0;
if (p[0] == '^')
{
p = p.next();
anchor = 1;
}
int n = 0;
MatchState ms = new MatchState();
luaL_Buffer b = new luaL_Buffer();
luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
"string/function/table expected");
luaL_buffinit(L, b);
ms.L = L;
ms.src_init = src;
ms.src_end = src+srcl;
while (n < max_s) {
CharPtr e;
ms.level = 0;
e = match(ms, src, p);
if (e != null) {
n++;
add_value(ms, b, src, e);
}
if ((e!=null) && e>src) /* non empty match? */
src = e; /* skip it */
else if (src < ms.src_end)
{
char c = src[0];
src = src.next();
luaL_addchar(b, c);
}
else break;
if (anchor != 0) break;
}
luaL_addlstring(b, src, (uint)(ms.src_end-src));
luaL_pushresult(b);
lua_pushinteger(L, n); /* number of substitutions */
return 2;
}
/* }====================================================== */
/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
public const int MAX_ITEM = 512;
/* valid flags in a format specification */
public const string FLAGS = "-+ #0";
/*
** maximum size of each format specification (such as '%-099.99d')
** (+10 accounts for %99.99x plus margin of error)
*/
public static readonly int MAX_FORMAT = (FLAGS.Length+1) + (LUA_INTFRMLEN.Length+1) + 10;
private static void addquoted (LuaState L, luaL_Buffer b, int arg) {
uint l;
CharPtr s = luaL_checklstring(L, arg, out l);
luaL_addchar(b, '"');
while ((l--) != 0) {
switch (s[0]) {
case '"': case '\\': case '\n': {
luaL_addchar(b, '\\');
luaL_addchar(b, s[0]);
break;
}
case '\r': {
luaL_addlstring(b, "\\r", 2);
break;
}
case '\0': {
luaL_addlstring(b, "\\000", 4);
break;
}
default: {
luaL_addchar(b, s[0]);
break;
}
}
s = s.next();
}
luaL_addchar(b, '"');
}
private static CharPtr scanformat (LuaState L, CharPtr strfrmt, CharPtr form) {
CharPtr p = strfrmt;
while (p[0] != '\0' && strchr(FLAGS, p[0]) != null) p = p.next(); /* skip flags */
if ((uint)(p - strfrmt) >= (FLAGS.Length+1))
luaL_error(L, "invalid format (repeated flags)");
if (isdigit((byte)(p[0]))) p = p.next(); /* skip width */
if (isdigit((byte)(p[0]))) p = p.next(); /* (2 digits at most) */
if (p[0] == '.') {
p = p.next();
if (isdigit((byte)(p[0]))) p = p.next(); /* skip precision */
if (isdigit((byte)(p[0]))) p = p.next(); /* (2 digits at most) */
}
if (isdigit((byte)(p[0])))
luaL_error(L, "invalid format (width or precision too long)");
form[0] = '%';
form = form.next();
strncpy(form, strfrmt, p - strfrmt + 1);
form += p - strfrmt + 1;
form[0] = '\0';
return p;
}
private static void addintlen (CharPtr form) {
uint l = (uint)strlen(form);
char spec = form[l - 1];
strcpy(form + l - 1, LUA_INTFRMLEN);
form[l + (LUA_INTFRMLEN.Length + 1) - 2] = spec;
form[l + (LUA_INTFRMLEN.Length + 1) - 1] = '\0';
}
private static int str_format (LuaState L) {
int top = lua_gettop(L);
int arg = 1;
uint sfl;
CharPtr strfrmt = luaL_checklstring(L, arg, out sfl);
CharPtr strfrmt_end = strfrmt+sfl;
luaL_Buffer b = new luaL_Buffer();
luaL_buffinit(L, b);
while (strfrmt < strfrmt_end) {
if (strfrmt[0] != L_ESC)
{
luaL_addchar(b, strfrmt[0]);
strfrmt = strfrmt.next();
}
else if (strfrmt[1] == L_ESC)
{
luaL_addchar(b, strfrmt[0]); /* %% */
strfrmt = strfrmt + 2;
}
else
{ /* format item */
strfrmt = strfrmt.next();
CharPtr form = new char[MAX_FORMAT]; /* to store the format (`%...') */
CharPtr buff = new char[MAX_ITEM]; /* to store the formatted item */
if (++arg > top)
luaL_argerror(L, arg, "no value");
strfrmt = scanformat(L, strfrmt, form);
char ch = strfrmt[0];
strfrmt = strfrmt.next();
switch (ch)
{
case 'c':
{
sprintf(buff, form, (int)luaL_checknumber(L, arg));
break;
}
case 'd':
case 'i':
{
addintlen(form);
sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));
break;
}
case 'o':
case 'u':
case 'x':
case 'X':
{
addintlen(form);
sprintf(buff, form, (UNSIGNED_LUA_INTFRM_T)luaL_checknumber(L, arg));
break;
}
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
{
sprintf(buff, form, (double)luaL_checknumber(L, arg));
break;
}
case 'q':
{
addquoted(L, b, arg);
continue; /* skip the 'addsize' at the end */
}
case 's':
{
uint l;
CharPtr s = luaL_checklstring(L, arg, out l);
if ((strchr(form, '.') == null) && l >= 100)
{
/* no precision and string is too long to be formatted;
keep original string */
lua_pushvalue(L, arg);
luaL_addvalue(b);
continue; /* skip the `addsize' at the end */
}
else
{
sprintf(buff, form, s);
break;
}
}
default:
{ /* also treat cases `pnLlh' */
return luaL_error(L, "invalid option " + LUA_QL("%%%c") + " to " +
LUA_QL("format"), strfrmt[-1]);
}
}
luaL_addlstring(b, buff, (uint)strlen(buff));
}
}
luaL_pushresult(b);
return 1;
}
private readonly static luaL_Reg[] strlib = {
new luaL_Reg("byte", str_byte),
new luaL_Reg("char", str_char),
new luaL_Reg("dump", str_dump),
new luaL_Reg("find", str_find),
new luaL_Reg("format", str_format),
new luaL_Reg("gfind", gfind_nodef),
new luaL_Reg("gmatch", gmatch),
new luaL_Reg("gsub", str_gsub),
new luaL_Reg("len", str_len),
new luaL_Reg("lower", str_lower),
new luaL_Reg("match", str_match),
new luaL_Reg("rep", str_rep),
new luaL_Reg("reverse", str_reverse),
new luaL_Reg("sub", str_sub),
new luaL_Reg("upper", str_upper),
new luaL_Reg(null, null)
};
private static void createmetatable (LuaState L) {
lua_createtable(L, 0, 1); /* create metatable for strings */
lua_pushliteral(L, ""); /* dummy string */
lua_pushvalue(L, -2);
lua_setmetatable(L, -2); /* set string metatable */
lua_pop(L, 1); /* pop dummy string */
lua_pushvalue(L, -2); /* string library... */
lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
lua_pop(L, 1); /* pop metatable */
}
/*
** Open string library
*/
public static int luaopen_string (LuaState L) {
luaL_register(L, LUA_STRLIBNAME, strlib);
#if LUA_COMPAT_GFIND
lua_getfield(L, -1, "gmatch");
lua_setfield(L, -2, "gfind");
#endif
createmetatable(L);
return 1;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Management.Automation;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// This Cmdlet enables the IT Pro to create a CIM Session. CIM Session object
/// is a client-side representation of the connection between the client and the
/// server.
/// The CimSession object returned by the Cmdlet is used by all other CIM
/// cmdlets.
/// </summary>
[Cmdlet(VerbsCommon.New, "CimSession", DefaultParameterSetName = CredentialParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227967")]
[OutputType(typeof(CimSession))]
public sealed class NewCimSessionCommand : CimBaseCommand
{
#region cmdlet parameters
/// <summary>
/// The following is the definition of the input parameter "Authentication".
/// The following is the validation set for allowed authentication types.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CredentialParameterSet)]
public PasswordAuthenticationMechanism Authentication
{
get { return authentication;}
set
{
authentication = value;
authenticationSet = true;
}
}
private PasswordAuthenticationMechanism authentication;
private bool authenticationSet = false;
/// <summary>
/// The following is the definition of the input parameter "Credential".
/// Specifies a user account that has permission to perform this action.
/// The default is the current user.
/// </summary>
[Parameter(Position = 1, ParameterSetName = CredentialParameterSet)]
[Credential()]
public PSCredential Credential
{
get { return credential; }
set { credential = value; }
}
private PSCredential credential;
/// <summary>
/// The following is the definition of the input parameter "CertificateThumbprint".
/// This is specificly for wsman protocol.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CertificateParameterSet)]
public string CertificateThumbprint
{
get { return certificatethumbprint; }
set { certificatethumbprint = value; }
}
private string certificatethumbprint;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Specifies the computer on which the commands associated with this session
/// will run. The default value is LocalHost.
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
Position = 0,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName
{
get { return computername;}
set { computername = value; }
}
private string[] computername;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Name".
/// Specifies a friendly name for the CIM Session connection.
/// </para>
/// <para>
/// If a name is not passed, then the session is given the name CimSession<int>,
/// where <int> is the next available session number. Example, CimSession1,
/// CimSession2, etc...
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public string Name
{
get { return name;}
set { name = value; }
}
private string name;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Specifies the operation timeout for all operations in session. Individual
/// operations can override this timeout.
/// </para>
/// <para>
/// The unit is Second.
/// <para>
/// </summary>
[Alias(AliasOT)]
[Parameter(ValueFromPipelineByPropertyName = true)]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set
{
operationTimeout = value;
operationTimeoutSet = true;
}
}
private UInt32 operationTimeout;
internal bool operationTimeoutSet = false;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "SkipTestConnection".
/// Specifies where test connection should be skipped
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter SkipTestConnection
{
get { return skipTestConnection; }
set
{
skipTestConnection = value;
}
}
private SwitchParameter skipTestConnection;
/// <summary>
/// The following is the definition of the input parameter "Port".
/// Specifies the port number to use, if different than the default port number.
/// This is specificly for wsman protocol.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public UInt32 Port
{
get { return port; }
set
{
port = value;
portSet = true;
}
}
private UInt32 port;
private bool portSet = false;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "SessionOption".
/// Specifies the SessionOption object that is passed to the Cmdlet as argument.
/// </para>
/// <para>
/// If the argument is not given, a default SessionOption will be created for
/// the session in .NET API layer.
/// </para>
/// If a <see cref="DCOMSessionOption"/> object is passed, then
/// connection is made using DCOM. If a <see cref="WsManSessionOption"/>
/// object is passed, then connection is made using WsMan.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public Microsoft.Management.Infrastructure.Options.CimSessionOptions SessionOption
{
get { return sessionOption; }
set { sessionOption = value; }
}
private Microsoft.Management.Infrastructure.Options.CimSessionOptions sessionOption;
#endregion
#region cmdlet processing methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
cimNewSession = new CimNewSession();
this.CmdletOperation = new CmdletOperationTestCimSession(this, this.cimNewSession);
this.AtBeginProcess = false;
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
CimSessionOptions outputOptions;
CimCredential outputCredential;
BuildSessionOptions(out outputOptions, out outputCredential);
cimNewSession.NewCimSession(this, outputOptions, outputCredential);
cimNewSession.ProcessActions(this.CmdletOperation);
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
cimNewSession.ProcessRemainActions(this.CmdletOperation);
}
#endregion
#region helper methods
/// <summary>
/// Build a CimSessionOptions, used to create CimSession.
/// </summary>
/// <returns>Null means no prefer CimSessionOptions.</returns>
internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCredential outputCredential)
{
DebugHelper.WriteLogEx();
CimSessionOptions options = null;
if (this.SessionOption != null)
{
// clone the sessionOption object
if (this.SessionOption is WSManSessionOptions)
{
options = new WSManSessionOptions(this.sessionOption as WSManSessionOptions);
}
else
{
options = new DComSessionOptions(this.sessionOption as DComSessionOptions);
}
}
outputOptions = null;
outputCredential = null;
if (options != null)
{
DComSessionOptions dcomOptions = (options as DComSessionOptions);
if (dcomOptions != null)
{
bool conflict = false;
string parameterName = string.Empty;
if (this.CertificateThumbprint != null)
{
conflict = true;
parameterName = @"CertificateThumbprint";
}
if (portSet)
{
conflict = true;
parameterName = @"Port";
}
if (conflict)
{
ThrowConflictParameterWasSet(@"New-CimSession", parameterName, @"DComSessionOptions");
return;
}
}
}
if (portSet || (this.CertificateThumbprint != null))
{
WSManSessionOptions wsmanOptions = (options == null) ? new WSManSessionOptions() : options as WSManSessionOptions;
if (portSet)
{
wsmanOptions.DestinationPort = this.Port;
portSet = false;
}
if (this.CertificateThumbprint != null)
{
CimCredential credentials = new CimCredential(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint);
wsmanOptions.AddDestinationCredentials(credentials);
}
options = wsmanOptions;
}
if (this.operationTimeoutSet)
{
if (options != null)
{
options.Timeout = TimeSpan.FromSeconds((double)this.OperationTimeoutSec);
}
}
if (this.authenticationSet || (this.credential != null))
{
PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default;
if (this.authenticationSet)
{
this.authenticationSet = false;
}
CimCredential credentials = CreateCimCredentials(this.Credential, authentication, @"New-CimSession", @"Authentication");
if (credentials == null)
{
return;
}
DebugHelper.WriteLog("Credentials: {0}", 1, credentials);
outputCredential = credentials;
if (options != null)
{
DebugHelper.WriteLog("Add credentials to option: {0}", 1, options);
options.AddDestinationCredentials(credentials);
}
}
DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, outputOptions);
outputOptions = options;
}
#endregion
#region private members
/// <summary>
/// <para>
/// CimNewSession object
/// </para>
/// </summary>
private CimNewSession cimNewSession;
#endregion
#region IDisposable
/// <summary>
/// Clean up resources.
/// </summary>
protected override void DisposeInternal()
{
base.DisposeInternal();
// Dispose managed resources.
if (this.cimNewSession != null)
{
this.cimNewSession.Dispose();
}
}
#endregion
}
}
| |
namespace android.os
{
[global::MonoJavaBridge.JavaClass()]
public partial class Process : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Process(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
public static long ElapsedCpuTime
{
get
{
return getElapsedCpuTime();
}
}
private static global::MonoJavaBridge.MethodId _m0;
public static long getElapsedCpuTime()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m0.native == global::System.IntPtr.Zero)
global::android.os.Process._m0 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "getElapsedCpuTime", "()J");
return @__env.CallStaticLongMethod(android.os.Process.staticClass, global::android.os.Process._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public static int myPid()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m1.native == global::System.IntPtr.Zero)
global::android.os.Process._m1 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "myPid", "()I");
return @__env.CallStaticIntMethod(android.os.Process.staticClass, global::android.os.Process._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public static int myTid()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m2.native == global::System.IntPtr.Zero)
global::android.os.Process._m2 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "myTid", "()I");
return @__env.CallStaticIntMethod(android.os.Process.staticClass, global::android.os.Process._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public static int myUid()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m3.native == global::System.IntPtr.Zero)
global::android.os.Process._m3 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "myUid", "()I");
return @__env.CallStaticIntMethod(android.os.Process.staticClass, global::android.os.Process._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
public static int getUidForName(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m4.native == global::System.IntPtr.Zero)
global::android.os.Process._m4 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "getUidForName", "(Ljava/lang/String;)I");
return @__env.CallStaticIntMethod(android.os.Process.staticClass, global::android.os.Process._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public static int getGidForName(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m5.native == global::System.IntPtr.Zero)
global::android.os.Process._m5 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "getGidForName", "(Ljava/lang/String;)I");
return @__env.CallStaticIntMethod(android.os.Process.staticClass, global::android.os.Process._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public static void setThreadPriority(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m6.native == global::System.IntPtr.Zero)
global::android.os.Process._m6 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "setThreadPriority", "(II)V");
@__env.CallStaticVoidMethod(android.os.Process.staticClass, global::android.os.Process._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public static int ThreadPriority
{
set
{
setThreadPriority(value);
}
}
private static global::MonoJavaBridge.MethodId _m7;
public static void setThreadPriority(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m7.native == global::System.IntPtr.Zero)
global::android.os.Process._m7 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "setThreadPriority", "(I)V");
@__env.CallStaticVoidMethod(android.os.Process.staticClass, global::android.os.Process._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
public static int getThreadPriority(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m8.native == global::System.IntPtr.Zero)
global::android.os.Process._m8 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "getThreadPriority", "(I)I");
return @__env.CallStaticIntMethod(android.os.Process.staticClass, global::android.os.Process._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
public static bool supportsProcesses()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m9.native == global::System.IntPtr.Zero)
global::android.os.Process._m9 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "supportsProcesses", "()Z");
return @__env.CallStaticBooleanMethod(android.os.Process.staticClass, global::android.os.Process._m9);
}
private static global::MonoJavaBridge.MethodId _m10;
public static void killProcess(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m10.native == global::System.IntPtr.Zero)
global::android.os.Process._m10 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "killProcess", "(I)V");
@__env.CallStaticVoidMethod(android.os.Process.staticClass, global::android.os.Process._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public static void sendSignal(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m11.native == global::System.IntPtr.Zero)
global::android.os.Process._m11 = @__env.GetStaticMethodIDNoThrow(global::android.os.Process.staticClass, "sendSignal", "(II)V");
@__env.CallStaticVoidMethod(android.os.Process.staticClass, global::android.os.Process._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m12;
public Process() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Process._m12.native == global::System.IntPtr.Zero)
global::android.os.Process._m12 = @__env.GetMethodIDNoThrow(global::android.os.Process.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Process.staticClass, global::android.os.Process._m12);
Init(@__env, handle);
}
public static int SYSTEM_UID
{
get
{
return 1000;
}
}
public static int PHONE_UID
{
get
{
return 1001;
}
}
public static int FIRST_APPLICATION_UID
{
get
{
return 10000;
}
}
public static int LAST_APPLICATION_UID
{
get
{
return 99999;
}
}
public static int BLUETOOTH_GID
{
get
{
return 2000;
}
}
public static int THREAD_PRIORITY_DEFAULT
{
get
{
return 0;
}
}
public static int THREAD_PRIORITY_LOWEST
{
get
{
return 19;
}
}
public static int THREAD_PRIORITY_BACKGROUND
{
get
{
return 10;
}
}
public static int THREAD_PRIORITY_FOREGROUND
{
get
{
return -2;
}
}
public static int THREAD_PRIORITY_DISPLAY
{
get
{
return -4;
}
}
public static int THREAD_PRIORITY_URGENT_DISPLAY
{
get
{
return -8;
}
}
public static int THREAD_PRIORITY_AUDIO
{
get
{
return -16;
}
}
public static int THREAD_PRIORITY_URGENT_AUDIO
{
get
{
return -19;
}
}
public static int THREAD_PRIORITY_MORE_FAVORABLE
{
get
{
return -1;
}
}
public static int THREAD_PRIORITY_LESS_FAVORABLE
{
get
{
return 1;
}
}
public static int SIGNAL_QUIT
{
get
{
return 3;
}
}
public static int SIGNAL_KILL
{
get
{
return 9;
}
}
public static int SIGNAL_USR1
{
get
{
return 10;
}
}
static Process()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.Process.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/Process"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.SqlClient
{
public sealed partial class SqlConnection : DbConnection, ICloneable
{
private bool _AsyncCommandInProgress;
// SQLStatistics support
internal SqlStatistics _statistics;
private bool _collectstats;
private bool _fireInfoMessageEventOnUserErrors; // False by default
// root task associated with current async invocation
private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion;
private string _connectionString;
private int _connectRetryCount;
// connection resiliency
private object _reconnectLock = new object();
internal Task _currentReconnectionTask;
private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections
private Guid _originalConnectionId = Guid.Empty;
private CancellationTokenSource _reconnectionCancellationSource;
internal SessionData _recoverySessionData;
internal bool _suppressStateChangeForReconnection;
private int _reconnectCount;
// diagnostics listener
private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
// Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not
// The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened
// using SqlConnection.Open() method.
internal bool _applyTransientFaultHandling = false;
public SqlConnection(string connectionString) : this()
{
ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available
CacheConnectionStringProperties();
}
private SqlConnection(SqlConnection connection)
{
GC.SuppressFinalize(this);
CopyFrom(connection);
_connectionString = connection._connectionString;
CacheConnectionStringProperties();
}
// This method will be called once connection string is set or changed.
private void CacheConnectionStringProperties()
{
SqlConnectionString connString = ConnectionOptions as SqlConnectionString;
if (connString != null)
{
_connectRetryCount = connString.ConnectRetryCount;
}
}
//
// PUBLIC PROPERTIES
//
// used to start/stop collection of statistics data and do verify the current state
//
// devnote: start/stop should not performed using a property since it requires execution of code
//
// start statistics
// set the internal flag (_statisticsEnabled) to true.
// Create a new SqlStatistics object if not already there.
// connect the parser to the object.
// if there is no parser at this time we need to connect it after creation.
//
public bool StatisticsEnabled
{
get
{
return (_collectstats);
}
set
{
{
if (value)
{
// start
if (ConnectionState.Open == State)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
ADP.TimerCurrent(out _statistics._openTimestamp);
}
// set statistics on the parser
// update timestamp;
Debug.Assert(Parser != null, "Where's the parser?");
Parser.Statistics = _statistics;
}
}
else
{
// stop
if (null != _statistics)
{
if (ConnectionState.Open == State)
{
// remove statistics from parser
// update timestamp;
TdsParser parser = Parser;
Debug.Assert(parser != null, "Where's the parser?");
parser.Statistics = null;
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
}
_collectstats = value;
}
}
}
internal bool AsyncCommandInProgress
{
get
{
return (_AsyncCommandInProgress);
}
set
{
_AsyncCommandInProgress = value;
}
}
internal SqlConnectionString.TypeSystem TypeSystem
{
get
{
return ((SqlConnectionString)ConnectionOptions).TypeSystemVersion;
}
}
internal int ConnectRetryInterval
{
get
{
return ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval;
}
}
override public string ConnectionString
{
get
{
return ConnectionString_Get();
}
set
{
ConnectionString_Set(new SqlConnectionPoolKey(value));
_connectionString = value; // Change _connectionString value only after value is validated
CacheConnectionStringProperties();
}
}
override public int ConnectionTimeout
{
get
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout);
}
}
override public string Database
{
// if the connection is open, we need to ask the inner connection what it's
// current catalog is because it may have gotten changed, otherwise we can
// just return what the connection string had.
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDatabase;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog);
}
return result;
}
}
override public string DataSource
{
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDataSource;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source);
}
return result;
}
}
public int PacketSize
{
// if the connection is open, we need to ask the inner connection what it's
// current packet size is because it may have gotten changed, otherwise we
// can just return what the connection string had.
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
int result;
if (null != innerConnection)
{
result = innerConnection.PacketSize;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size);
}
return result;
}
}
public Guid ClientConnectionId
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null != innerConnection)
{
return innerConnection.ClientConnectionId;
}
else
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return _originalConnectionId;
}
return Guid.Empty;
}
}
}
override public string ServerVersion
{
get
{
return GetOpenTdsConnection().ServerVersion;
}
}
override public ConnectionState State
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return ConnectionState.Open;
}
return InnerConnection.State;
}
}
internal SqlStatistics Statistics
{
get
{
return _statistics;
}
}
public string WorkstationId
{
get
{
// If not supplied by the user, the default value is the MachineName
// Note: In Longhorn you'll be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
string result = ((null != constr) ? constr.WorkstationId : string.Empty);
return result;
}
}
// SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication
//
// PUBLIC EVENTS
//
public event SqlInfoMessageEventHandler InfoMessage;
public bool FireInfoMessageEventOnUserErrors
{
get
{
return _fireInfoMessageEventOnUserErrors;
}
set
{
_fireInfoMessageEventOnUserErrors = value;
}
}
// Approx. number of times that the internal connection has been reconnected
internal int ReconnectCount
{
get
{
return _reconnectCount;
}
}
internal bool ForceNewConnection { get; set; }
protected override void OnStateChange(StateChangeEventArgs stateChange)
{
if (!_suppressStateChangeForReconnection)
{
base.OnStateChange(stateChange);
}
}
//
// PUBLIC METHODS
//
new public SqlTransaction BeginTransaction()
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(IsolationLevel.Unspecified, null);
}
new public SqlTransaction BeginTransaction(IsolationLevel iso)
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(iso, null);
}
public SqlTransaction BeginTransaction(string transactionName)
{
// Use transaction names only on the outermost pair of nested
// BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names
// are ignored for nested BEGIN's. The only way to rollback a nested
// transaction is to have a save point from a SAVE TRANSACTION call.
return BeginTransaction(IsolationLevel.Unspecified, transactionName);
}
[SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
DbTransaction transaction = BeginTransaction(isolationLevel);
// InnerConnection doesn't maintain a ref on the outer connection (this) and
// subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction
// is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable
// until the completion of BeginTransaction with KeepAlive
GC.KeepAlive(this);
return transaction;
}
public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName)
{
WaitForPendingReconnection();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
SqlTransaction transaction;
bool isFirstAttempt = true;
do
{
transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice
Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt");
isFirstAttempt = false;
} while (transaction.InternalTransaction.ConnectionHasBeenRestored);
// The GetOpenConnection line above doesn't keep a ref on the outer connection (this),
// and it could be collected before the inner connection can hook it to the transaction, resulting in
// a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen.
GC.KeepAlive(this);
return transaction;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
override public void ChangeDatabase(string database)
{
SqlStatistics statistics = null;
RepairInnerConnection();
try
{
statistics = SqlStatistics.StartTimer(Statistics);
InnerConnection.ChangeDatabase(database);
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
public static void ClearAllPools()
{
SqlConnectionFactory.SingletonInstance.ClearAllPools();
}
public static void ClearPool(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
DbConnectionOptions connectionOptions = connection.UserConnectionOptions;
if (null != connectionOptions)
{
SqlConnectionFactory.SingletonInstance.ClearPool(connection);
}
}
private void CloseInnerConnection()
{
// CloseConnection() now handles the lock
// The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
// the command will no longer be cancelable. It might be desirable to be able to cancel the close operation, but this is
// outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock.
InnerConnection.CloseConnection(this, ConnectionFactory);
}
override public void Close()
{
ConnectionState previousState = State;
Guid operationId = default(Guid);
Guid clientConnectionId = default(Guid);
// during the call to Dispose() there is a redundant call to
// Close(). because of this, the second time Close() is invoked the
// connection is already in a closed state. this doesn't seem to be a
// problem except for logging, as we'll get duplicate Before/After/Error
// log entries
if (previousState != ConnectionState.Closed)
{
operationId = s_diagnosticListener.WriteConnectionCloseBefore(this);
// we want to cache the ClientConnectionId for After/Error logging, as when the connection
// is closed then we will lose this identifier
//
// note: caching this is only for diagnostics logging purposes
clientConnectionId = ClientConnectionId;
}
SqlStatistics statistics = null;
Exception e = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
CancellationTokenSource cts = _reconnectionCancellationSource;
if (cts != null)
{
cts.Cancel();
}
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection
if (State != ConnectionState.Open)
{// if we cancelled before the connection was opened
OnStateChange(DbConnectionInternal.StateChangeClosed);
}
}
CancelOpenAndWait();
CloseInnerConnection();
GC.SuppressFinalize(this);
if (null != Statistics)
{
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
catch (Exception ex)
{
e = ex;
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
// we only want to log this if the previous state of the
// connection is open, as that's the valid use-case
if (previousState != ConnectionState.Closed)
{
if (e != null)
{
s_diagnosticListener.WriteConnectionCloseError(operationId, clientConnectionId, this, e);
}
else
{
s_diagnosticListener.WriteConnectionCloseAfter(operationId, clientConnectionId, this);
}
}
}
}
new public SqlCommand CreateCommand()
{
return new SqlCommand(null, this);
}
private void DisposeMe(bool disposing)
{
if (!disposing)
{
// For non-pooled connections we need to make sure that if the SqlConnection was not closed,
// then we release the GCHandle on the stateObject to allow it to be GCed
// For pooled connections, we will rely on the pool reclaiming the connection
var innerConnection = (InnerConnection as SqlInternalConnectionTds);
if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling))
{
var parser = innerConnection.Parser;
if ((parser != null) && (parser._physicalStateObj != null))
{
parser._physicalStateObj.DecrementPendingCallbacks(release: false);
}
}
}
}
override public void Open()
{
Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this);
PrepareStatisticsForNewConnection();
SqlStatistics statistics = null;
Exception e = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
if (!TryOpen(null))
{
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
catch (Exception ex)
{
e = ex;
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
if (e != null)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, e);
}
else
{
s_diagnosticListener.WriteConnectionOpenAfter(operationId, this);
}
}
}
internal void RegisterWaitingForReconnect(Task waitingTask)
{
if (((SqlConnectionString)ConnectionOptions).MARS)
{
return;
}
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null);
if (_asyncWaitingForReconnection != waitingTask)
{ // somebody else managed to register
throw SQL.MARSUnspportedOnConnection();
}
}
private async Task ReconnectAsync(int timeout)
{
try
{
long commandTimeoutExpiration = 0;
if (timeout > 0)
{
commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout);
}
CancellationTokenSource cts = new CancellationTokenSource();
_reconnectionCancellationSource = cts;
CancellationToken ctoken = cts.Token;
int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string
for (int attempt = 0; attempt < retryCount; attempt++)
{
if (ctoken.IsCancellationRequested)
{
return;
}
try
{
try
{
ForceNewConnection = true;
await OpenAsync(ctoken).ConfigureAwait(false);
// On success, increment the reconnect count - we don't really care if it rolls over since it is approx.
_reconnectCount = unchecked(_reconnectCount + 1);
#if DEBUG
Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !");
#endif
}
finally
{
ForceNewConnection = false;
}
return;
}
catch (SqlException e)
{
if (attempt == retryCount - 1)
{
throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId);
}
if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval))
{
throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId);
}
}
await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false);
}
}
finally
{
_recoverySessionData = null;
_suppressStateChangeForReconnection = false;
}
Debug.Assert(false, "Should not reach this point");
}
internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
{
Task runningReconnect = _currentReconnectionTask;
// This loop in the end will return not completed reconnect task or null
while (runningReconnect != null && runningReconnect.IsCompleted)
{
// clean current reconnect task (if it is the same one we checked
Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect);
// make sure nobody started new task (if which case we did not clean it)
runningReconnect = _currentReconnectionTask;
}
if (runningReconnect == null)
{
if (_connectRetryCount > 0)
{
SqlInternalConnectionTds tdsConn = GetOpenTdsConnection();
if (tdsConn._sessionRecoveryAcknowledged)
{
TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj;
if (!stateObj.ValidateSNIConnection())
{
if (tdsConn.Parser._sessionPool != null)
{
if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0)
{
// >1 MARS session
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null);
}
}
SessionData cData = tdsConn.CurrentSessionData;
cData.AssertUnrecoverableStateCountIsCorrect();
if (cData._unrecoverableStatesCount == 0)
{
bool callDisconnect = false;
lock (_reconnectLock)
{
runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
if (runningReconnect == null)
{
if (cData._unrecoverableStatesCount == 0)
{ // could change since the first check, but now is stable since connection is know to be broken
_originalConnectionId = ClientConnectionId;
_recoverySessionData = cData;
if (beforeDisconnect != null)
{
beforeDisconnect();
}
try
{
_suppressStateChangeForReconnection = true;
tdsConn.DoomThisConnection();
}
catch (SqlException)
{
}
runningReconnect = Task.Run(() => ReconnectAsync(timeout));
// if current reconnect is not null, somebody already started reconnection task - some kind of race condition
Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected");
_currentReconnectionTask = runningReconnect;
}
}
else
{
callDisconnect = true;
}
}
if (callDisconnect && beforeDisconnect != null)
{
beforeDisconnect();
}
}
else
{
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null);
}
} // ValidateSNIConnection
} // sessionRecoverySupported
} // connectRetryCount>0
}
else
{ // runningReconnect = null
if (beforeDisconnect != null)
{
beforeDisconnect();
}
}
return runningReconnect;
}
// this is straightforward, but expensive method to do connection resiliency - it take locks and all preparations as for TDS request
partial void RepairInnerConnection()
{
WaitForPendingReconnection();
if (_connectRetryCount == 0)
{
return;
}
SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds;
if (tdsConn != null)
{
tdsConn.ValidateConnectionForExecute(null);
tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this);
}
}
private void WaitForPendingReconnection()
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false);
}
}
private void CancelOpenAndWait()
{
// copy from member to avoid changes by background thread
var completion = _currentCompletion;
if (completion != null)
{
completion.Item1.TrySetCanceled();
((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne();
}
Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source");
}
public override Task OpenAsync(CancellationToken cancellationToken)
{
Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this);
PrepareStatisticsForNewConnection();
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(Statistics);
TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>();
TaskCompletionSource<object> result = new TaskCompletionSource<object>();
if (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection) ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection))
{
result.Task.ContinueWith((t) =>
{
if (t.Exception != null)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, t.Exception);
}
else
{
s_diagnosticListener.WriteConnectionOpenAfter(operationId, this);
}
}, TaskScheduler.Default);
}
if (cancellationToken.IsCancellationRequested)
{
result.SetCanceled();
return result.Task;
}
bool completed;
try
{
completed = TryOpen(completion);
}
catch (Exception e)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, e);
result.SetException(e);
return result.Task;
}
if (completed)
{
result.SetResult(null);
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(s => ((TaskCompletionSource<DbConnectionInternal>)s).TrySetCanceled(), completion);
}
OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration);
_currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task);
completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default);
return result.Task;
}
return result.Task;
}
catch (Exception ex)
{
s_diagnosticListener.WriteConnectionOpenError(operationId, this, ex);
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
private class OpenAsyncRetry
{
private SqlConnection _parent;
private TaskCompletionSource<DbConnectionInternal> _retry;
private TaskCompletionSource<object> _result;
private CancellationTokenRegistration _registration;
public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration)
{
_parent = parent;
_retry = retry;
_result = result;
_registration = registration;
}
internal void Retry(Task<DbConnectionInternal> retryTask)
{
_registration.Dispose();
try
{
SqlStatistics statistics = null;
try
{
statistics = SqlStatistics.StartTimer(_parent.Statistics);
if (retryTask.IsFaulted)
{
Exception e = retryTask.Exception.InnerException;
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(retryTask.Exception.InnerException);
}
else if (retryTask.IsCanceled)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetCanceled();
}
else
{
bool result;
// protect continuation from races with close and cancel
lock (_parent.InnerConnection)
{
result = _parent.TryOpen(_retry);
}
if (result)
{
_parent._currentCompletion = null;
_result.SetResult(null);
}
else
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending)));
}
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
catch (Exception e)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(e);
}
}
}
private void PrepareStatisticsForNewConnection()
{
if (StatisticsEnabled ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) ||
s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection))
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
}
else
{
_statistics.ContinueOnNewConnection();
}
}
}
private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry)
{
SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
_applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0);
if (ForceNewConnection)
{
if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
else
{
if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
// does not require GC.KeepAlive(this) because of OnStateChange
var tdsInnerConnection = (SqlInternalConnectionTds)InnerConnection;
Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?");
if (!tdsInnerConnection.ConnectionOptions.Pooling)
{
// For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles
GC.ReRegisterForFinalize(this);
}
// The _statistics can change with StatisticsEnabled. Copying to a local variable before checking for a null value.
SqlStatistics statistics = _statistics;
if (StatisticsEnabled ||
( s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) && statistics != null))
{
ADP.TimerCurrent(out _statistics._openTimestamp);
tdsInnerConnection.Parser.Statistics = _statistics;
}
else
{
tdsInnerConnection.Parser.Statistics = null;
_statistics = null; // in case of previous Open/Close/reset_CollectStats sequence
}
return true;
}
//
// INTERNAL PROPERTIES
//
internal bool HasLocalTransaction
{
get
{
return GetOpenTdsConnection().HasLocalTransaction;
}
}
internal bool HasLocalTransactionFromAPI
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return false; //we will not go into reconnection if we are inside the transaction
}
return GetOpenTdsConnection().HasLocalTransactionFromAPI;
}
}
internal bool IsKatmaiOrNewer
{
get
{
if (_currentReconnectionTask != null)
{ // holds true even if task is completed
return true; // if CR is enabled, connection, if established, will be Katmai+
}
return GetOpenTdsConnection().IsKatmaiOrNewer;
}
}
internal TdsParser Parser
{
get
{
SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection();
return tdsConnection.Parser;
}
}
//
// INTERNAL METHODS
//
internal void ValidateConnectionForExecute(string method, SqlCommand command)
{
Task asyncWaitingForReconnection = _asyncWaitingForReconnection;
if (asyncWaitingForReconnection != null)
{
if (!asyncWaitingForReconnection.IsCompleted)
{
throw SQL.MARSUnspportedOnConnection();
}
else
{
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection);
}
}
if (_currentReconnectionTask != null)
{
Task currentReconnectionTask = _currentReconnectionTask;
if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted)
{
return; // execution will wait for this task later
}
}
SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method);
innerConnection.ValidateConnectionForExecute(command);
}
// Surround name in brackets and then escape any end bracket to protect against SQL Injection.
// NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well
// as native OleDb and Odbc.
internal static string FixupDatabaseTransactionName(string name)
{
if (!string.IsNullOrEmpty(name))
{
return SqlServerEscapeHelper.EscapeIdentifier(name);
}
else
{
return name;
}
}
// If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
// The close action also supports being run asynchronously
internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
{
Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!");
if (breakConnection && (ConnectionState.Open == State))
{
if (wrapCloseInAction != null)
{
int capturedCloseCount = _closeCount;
Action closeAction = () =>
{
if (capturedCloseCount == _closeCount)
{
Close();
}
};
wrapCloseInAction(closeAction);
}
else
{
Close();
}
}
if (exception.Class >= TdsEnums.MIN_ERROR_CLASS)
{
// It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error,
// below TdsEnums.MIN_ERROR_CLASS denotes an info message.
throw exception;
}
else
{
// If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler
this.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
}
}
//
// PRIVATE METHODS
//
internal SqlInternalConnectionTds GetOpenTdsConnection()
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.ClosedConnectionError();
}
return innerConnection;
}
internal SqlInternalConnectionTds GetOpenTdsConnection(string method)
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.OpenConnectionRequired(method, InnerConnection.State);
}
return innerConnection;
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent)
{
bool notified;
OnInfoMessage(imevent, out notified);
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified)
{
SqlInfoMessageEventHandler handler = InfoMessage;
if (null != handler)
{
notified = true;
try
{
handler(this, imevent);
}
catch (Exception e)
{
if (!ADP.IsCatchableOrSecurityExceptionType(e))
{
throw;
}
}
}
else
{
notified = false;
}
}
//
// SQL DEBUGGING SUPPORT
//
// this only happens once per connection
// SxS: using named file mapping APIs
internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag)
{
// Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect
outerTask = outerTask.ContinueWith(task =>
{
RemoveWeakReference(value);
return task;
}, TaskScheduler.Default).Unwrap();
}
public void ResetStatistics()
{
if (null != Statistics)
{
Statistics.Reset();
if (ConnectionState.Open == State)
{
// update timestamp;
ADP.TimerCurrent(out _statistics._openTimestamp);
}
}
}
public IDictionary RetrieveStatistics()
{
if (null != Statistics)
{
UpdateStatistics();
return Statistics.GetDictionary();
}
else
{
return new SqlStatistics().GetDictionary();
}
}
private void UpdateStatistics()
{
if (ConnectionState.Open == State)
{
// update timestamp
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
// delegate the rest of the work to the SqlStatistics class
Statistics.UpdateStatistics();
}
object ICloneable.Clone() => new SqlConnection(this);
private void CopyFrom(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
_userConnectionOptions = connection.UserConnectionOptions;
_poolGroup = connection.PoolGroup;
if (DbConnectionClosedNeverOpened.SingletonInstance == connection._innerConnection)
{
_innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
else
{
_innerConnection = DbConnectionClosedPreviouslyOpened.SingletonInstance;
}
}
} // SqlConnection
} // System.Data.SqlClient namespace
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
namespace UnityEngine.Rendering.LWRP
{
/// <summary>
/// Class <c>ScriptableRenderer</c> implements a rendering strategy. It describes how culling and lighting works and
/// the effects supported.
///
/// A renderer can be used for all cameras or be overridden on a per-camera basis. It will implement light culling and setup
/// and describe a list of <c>ScriptableRenderPass</c> to execute in a frame. The renderer can be extended to support more effect with additional
/// <c>ScriptableRendererFeature</c>. Resources for the renderer are serialized in <c>ScriptableRendererData</c>.
///
/// he renderer resources are serialized in <c>ScriptableRendererData</c>.
/// <seealso cref="ScriptableRendererData"/>
/// <seealso cref="ScriptableRendererFeature"/>
/// <seealso cref="ScriptableRenderPass"/>
/// </summary>
public abstract class ScriptableRenderer
{
public RenderTargetIdentifier cameraColorTarget
{
get => m_CameraColorTarget;
}
public RenderTargetIdentifier cameraDepth
{
get => m_CameraDepthTarget;
}
protected List<ScriptableRendererFeature> rendererFeatures
{
get => m_RendererFeatures;
}
protected List<ScriptableRenderPass> activeRenderPassQueue
{
get => m_ActiveRenderPassQueue;
}
List<ScriptableRenderPass> m_ActiveRenderPassQueue = new List<ScriptableRenderPass>(32);
List<ScriptableRendererFeature> m_RendererFeatures = new List<ScriptableRendererFeature>(10);
RenderTargetIdentifier m_CameraColorTarget;
RenderTargetIdentifier m_CameraDepthTarget;
bool m_FirstCameraRenderPassExecuted = false;
const string k_ClearRenderStateTag = "Clear Render State";
const string k_SetRenderTarget = "Set RenderTarget";
const string k_ReleaseResourcesTag = "Release Resources";
static RenderTargetIdentifier m_ActiveColorAttachment;
static RenderTargetIdentifier m_ActiveDepthAttachment;
static bool m_InsideStereoRenderBlock;
internal static void ConfigureActiveTarget(RenderTargetIdentifier colorAttachment,
RenderTargetIdentifier depthAttachment)
{
m_ActiveColorAttachment = colorAttachment;
m_ActiveDepthAttachment = depthAttachment;
}
public ScriptableRenderer(ScriptableRendererData data)
{
foreach (var feature in data.rendererFeatures)
{
if (feature == null)
continue;
feature.Create();
m_RendererFeatures.Add(feature);
}
Clear();
}
/// <summary>
/// Configures the camera target.
/// </summary>
/// <param name="colorTarget">Camera color target. Pass BuiltinRenderTextureType.CameraTarget if rendering to backbuffer.</param>
/// <param name="depthTarget">Camera depth target. Pass BuiltinRenderTextureType.CameraTarget if color has depth or rendering to backbuffer.</param>
public void ConfigureCameraTarget(RenderTargetIdentifier colorTarget, RenderTargetIdentifier depthTarget)
{
m_CameraColorTarget = colorTarget;
m_CameraDepthTarget = depthTarget;
}
/// <summary>
/// Configures the render passes that will execute for this renderer.
/// This method is called per-camera every frame.
/// </summary>
/// <param name="context">Use this render context to issue any draw commands during execution.</param>
/// <param name="renderingData">Current render state information.</param>
/// <seealso cref="ScriptableRenderPass"/>
/// <seealso cref="ScriptableRendererFeature"/>
public abstract void Setup(ScriptableRenderContext context, ref RenderingData renderingData);
/// <summary>
/// Override this method to implement the lighting setup for the renderer. You can use this to
/// compute and upload light CBUFFER for example.
/// </summary>
/// <param name="context">Use this render context to issue any draw commands during execution.</param>
/// <param name="renderingData">Current render state information.</param>
public virtual void SetupLights(ScriptableRenderContext context, ref RenderingData renderingData)
{
}
/// <summary>
/// Override this method to configure the culling parameters for the renderer. You can use this to configure if
/// lights should be culled per-object or the maximum shadow distance for example.
/// </summary>
/// <param name="cullingParameters">Use this to change culling parameters used by the render pipeline.</param>
/// <param name="cameraData">Current render state information.</param>
public virtual void SetupCullingParameters(ref ScriptableCullingParameters cullingParameters,
ref CameraData cameraData)
{
}
/// <summary>
/// Called upon finishing camera rendering. You can release any resources created on setup here.
/// </summary>
/// <param name="cmd"></param>
public virtual void FinishRendering(CommandBuffer cmd)
{
}
/// <summary>
/// Execute the enqueued render passes. This automatically handles editor and stereo rendering.
/// </summary>
/// <param name="context">Use this render context to issue any draw commands during execution.</param>
/// <param name="renderingData">Current render state information.</param>
public void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
Camera camera = renderingData.cameraData.camera;
ClearRenderState(context);
SortStable(m_ActiveRenderPassQueue);
// Before Render Block. This render blocks always execute in mono rendering.
// Camera is not setup. Lights are not setup.
// Used to render input textures like shadowmaps.
ExecuteBlock(RenderPassEvent.BeforeRendering, RenderPassEvent.BeforeRenderingPrepasses, context, ref renderingData);
/// Configure shader variables and other unity properties that are required for rendering.
/// * Setup Camera RenderTarget and Viewport
/// * VR Camera Setup and SINGLE_PASS_STEREO props
/// * Setup camera view, projection and their inverse matrices.
/// * Setup properties: _WorldSpaceCameraPos, _ProjectionParams, _ScreenParams, _ZBufferParams, unity_OrthoParams
/// * Setup camera world clip planes properties
/// * Setup HDR keyword
/// * Setup global time properties (_Time, _SinTime, _CosTime)
bool stereoEnabled = renderingData.cameraData.isStereoEnabled;
context.SetupCameraProperties(camera, stereoEnabled);
SetupLights(context, ref renderingData);
if (stereoEnabled)
BeginXRRendering(context, camera);
// In this block main rendering executes.
ExecuteBlock(RenderPassEvent.BeforeRenderingPrepasses, RenderPassEvent.AfterRenderingPostProcessing, context, ref renderingData);
DrawGizmos(context, camera, GizmoSubset.PreImageEffects);
// In this block after rendering drawing happens, e.g, post processing, video player capture.
ExecuteBlock(RenderPassEvent.AfterRenderingPostProcessing, (RenderPassEvent)Int32.MaxValue, context, ref renderingData);
if (stereoEnabled)
EndXRRendering(context, camera);
DrawGizmos(context, camera, GizmoSubset.PostImageEffects);
InternalFinishRendering(context);
}
/// <summary>
/// Enqueues a render pass for execution.
/// </summary>
/// <param name="pass">Render pass to be enqueued.</param>
public void EnqueuePass(ScriptableRenderPass pass)
{
m_ActiveRenderPassQueue.Add(pass);
}
/// <summary>
/// Returns a clear flag based on CameraClearFlags.
/// </summary>
/// <param name="cameraClearFlags">Camera clear flags.</param>
/// <returns>A clear flag that tells if color and/or depth should be cleared.</returns>
protected static ClearFlag GetCameraClearFlag(CameraClearFlags cameraClearFlags)
{
#if UNITY_EDITOR
// We need public API to tell if FrameDebugger is active and enabled. In that case
// we want to force a clear to see properly the drawcall stepping.
// For now, to fix FrameDebugger in Editor, we force a clear.
cameraClearFlags = CameraClearFlags.SolidColor;
#endif
// LWRP doesn't support CameraClearFlags.DepthOnly and CameraClearFlags.Nothing.
// CameraClearFlags.DepthOnly has the same effect of CameraClearFlags.SolidColor
// CameraClearFlags.Nothing clears Depth on PC/Desktop and in mobile it clears both
// depth and color.
// CameraClearFlags.Skybox clears depth only.
// Implementation details:
// Camera clear flags are used to initialize the attachments on the first render pass.
// ClearFlag is used together with Tile Load action to figure out how to clear the camera render target.
// In Tile Based GPUs ClearFlag.Depth + RenderBufferLoadAction.DontCare becomes DontCare load action.
// While ClearFlag.All + RenderBufferLoadAction.DontCare become Clear load action.
// In mobile we force ClearFlag.All as DontCare doesn't have noticeable perf. difference from Clear
// and this avoid tile clearing issue when not rendering all pixels in some GPUs.
// In desktop/consoles there's actually performance difference between DontCare and Clear.
// RenderBufferLoadAction.DontCare in PC/Desktop behaves as not clearing screen
// RenderBufferLoadAction.DontCare in Vulkan/Metal behaves as DontCare load action
// RenderBufferLoadAction.DontCare in GLES behaves as glInvalidateBuffer
// Always clear on first render pass in mobile as it's same perf of DontCare and avoid tile clearing issues.
if (Application.isMobilePlatform)
return ClearFlag.All;
if ((cameraClearFlags == CameraClearFlags.Skybox && RenderSettings.skybox != null) ||
cameraClearFlags == CameraClearFlags.Nothing)
return ClearFlag.Depth;
return ClearFlag.All;
}
void ClearRenderState(ScriptableRenderContext context)
{
// Keywords are enabled while executing passes.
CommandBuffer cmd = CommandBufferPool.Get(k_ClearRenderStateTag);
cmd.DisableShaderKeyword(ShaderKeywordStrings.MainLightShadows);
cmd.DisableShaderKeyword(ShaderKeywordStrings.MainLightShadowCascades);
cmd.DisableShaderKeyword(ShaderKeywordStrings.AdditionalLightsVertex);
cmd.DisableShaderKeyword(ShaderKeywordStrings.AdditionalLightsPixel);
cmd.DisableShaderKeyword(ShaderKeywordStrings.AdditionalLightShadows);
cmd.DisableShaderKeyword(ShaderKeywordStrings.SoftShadows);
cmd.DisableShaderKeyword(ShaderKeywordStrings.MixedLightingSubtractive);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
internal void Clear()
{
m_CameraColorTarget = BuiltinRenderTextureType.CameraTarget;
m_CameraDepthTarget = BuiltinRenderTextureType.CameraTarget;
m_ActiveColorAttachment = BuiltinRenderTextureType.CameraTarget;
m_ActiveDepthAttachment = BuiltinRenderTextureType.CameraTarget;
m_FirstCameraRenderPassExecuted = false;
m_InsideStereoRenderBlock = false;
m_ActiveRenderPassQueue.Clear();
}
void ExecuteBlock(RenderPassEvent startEvent, RenderPassEvent endEvent,
ScriptableRenderContext context, ref RenderingData renderingData, bool submit = false)
{
int currIndex = m_ActiveRenderPassQueue.FindIndex(x => (x.renderPassEvent >= startEvent && x.renderPassEvent < endEvent));
if (currIndex == -1)
return;
while (currIndex < m_ActiveRenderPassQueue.Count && m_ActiveRenderPassQueue[currIndex].renderPassEvent < endEvent)
{
var renderPass = m_ActiveRenderPassQueue[currIndex];
ExecuteRenderPass(context, renderPass, ref renderingData);
currIndex++;
}
if (submit)
context.Submit();
}
void ExecuteRenderPass(ScriptableRenderContext context, ScriptableRenderPass renderPass, ref RenderingData renderingData)
{
CommandBuffer cmd = CommandBufferPool.Get(k_SetRenderTarget);
renderPass.Configure(cmd, renderingData.cameraData.cameraTargetDescriptor);
RenderTargetIdentifier passColorAttachment = renderPass.colorAttachment;
RenderTargetIdentifier passDepthAttachment = renderPass.depthAttachment;
ref CameraData cameraData = ref renderingData.cameraData;
// When render pass doesn't call ConfigureTarget we assume it's expected to render to camera target
// which might be backbuffer or the framebuffer render textures.
if (!renderPass.overrideCameraTarget)
{
passColorAttachment = m_CameraColorTarget;
passDepthAttachment = m_CameraDepthTarget;
}
if (passColorAttachment == m_CameraColorTarget && !m_FirstCameraRenderPassExecuted)
{
m_FirstCameraRenderPassExecuted = true;
Camera camera = cameraData.camera;
ClearFlag clearFlag = GetCameraClearFlag(camera.clearFlags);
SetRenderTarget(cmd, m_CameraColorTarget, m_CameraDepthTarget, clearFlag,
CoreUtils.ConvertSRGBToActiveColorSpace(camera.backgroundColor));
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
if (cameraData.isStereoEnabled)
{
context.StartMultiEye(cameraData.camera);
XRUtils.DrawOcclusionMesh(cmd, cameraData.camera);
}
}
// Only setup render target if current render pass attachments are different from the active ones
else if (passColorAttachment != m_ActiveColorAttachment || passDepthAttachment != m_ActiveDepthAttachment)
SetRenderTarget(cmd, passColorAttachment, passDepthAttachment, renderPass.clearFlag, renderPass.clearColor);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
renderPass.Execute(context, ref renderingData);
}
void BeginXRRendering(ScriptableRenderContext context, Camera camera)
{
context.StartMultiEye(camera);
m_InsideStereoRenderBlock = true;
}
void EndXRRendering(ScriptableRenderContext context, Camera camera)
{
context.StopMultiEye(camera);
context.StereoEndRender(camera);
m_InsideStereoRenderBlock = false;
}
internal static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorAttachment, RenderTargetIdentifier depthAttachment, ClearFlag clearFlag, Color clearColor)
{
m_ActiveColorAttachment = colorAttachment;
m_ActiveDepthAttachment = depthAttachment;
RenderBufferLoadAction colorLoadAction = clearFlag != ClearFlag.None ?
RenderBufferLoadAction.DontCare : RenderBufferLoadAction.Load;
RenderBufferLoadAction depthLoadAction = CoreUtils.HasFlag(clearFlag, ClearFlag.Depth) ?
RenderBufferLoadAction.DontCare : RenderBufferLoadAction.Load;
TextureDimension dimension = (m_InsideStereoRenderBlock) ? XRGraphics.eyeTextureDesc.dimension : TextureDimension.Tex2D;
SetRenderTarget(cmd, colorAttachment, colorLoadAction, RenderBufferStoreAction.Store,
depthAttachment, depthLoadAction, RenderBufferStoreAction.Store, clearFlag, clearColor, dimension);
}
static void SetRenderTarget(
CommandBuffer cmd,
RenderTargetIdentifier colorAttachment,
RenderBufferLoadAction colorLoadAction,
RenderBufferStoreAction colorStoreAction,
ClearFlag clearFlags,
Color clearColor,
TextureDimension dimension)
{
if (dimension == TextureDimension.Tex2DArray)
CoreUtils.SetRenderTarget(cmd, colorAttachment, clearFlags, clearColor, 0, CubemapFace.Unknown, -1);
else
CoreUtils.SetRenderTarget(cmd, colorAttachment, colorLoadAction, colorStoreAction, clearFlags, clearColor);
}
static void SetRenderTarget(
CommandBuffer cmd,
RenderTargetIdentifier colorAttachment,
RenderBufferLoadAction colorLoadAction,
RenderBufferStoreAction colorStoreAction,
RenderTargetIdentifier depthAttachment,
RenderBufferLoadAction depthLoadAction,
RenderBufferStoreAction depthStoreAction,
ClearFlag clearFlags,
Color clearColor,
TextureDimension dimension)
{
if (depthAttachment == BuiltinRenderTextureType.CameraTarget)
{
SetRenderTarget(cmd, colorAttachment, colorLoadAction, colorStoreAction, clearFlags, clearColor,
dimension);
}
else
{
if (dimension == TextureDimension.Tex2DArray)
CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment,
clearFlags, clearColor, 0, CubemapFace.Unknown, -1);
else
CoreUtils.SetRenderTarget(cmd, colorAttachment, colorLoadAction, colorStoreAction,
depthAttachment, depthLoadAction, depthStoreAction, clearFlags, clearColor);
}
}
[Conditional("UNITY_EDITOR")]
void DrawGizmos(ScriptableRenderContext context, Camera camera, GizmoSubset gizmoSubset)
{
#if UNITY_EDITOR
if (UnityEditor.Handles.ShouldRenderGizmos())
context.DrawGizmos(camera, gizmoSubset);
#endif
}
void InternalFinishRendering(ScriptableRenderContext context)
{
CommandBuffer cmd = CommandBufferPool.Get(k_ReleaseResourcesTag);
for (int i = 0; i < m_ActiveRenderPassQueue.Count; ++i)
m_ActiveRenderPassQueue[i].FrameCleanup(cmd);
FinishRendering(cmd);
Clear();
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
internal static void SortStable(List<ScriptableRenderPass> list)
{
int j;
for (int i = 1; i < list.Count; ++i)
{
ScriptableRenderPass curr = list[i];
j = i - 1;
for (; j >= 0 && curr < list[j]; --j)
list[j + 1] = list[j];
list[j + 1] = curr;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
{
public class DateTimeModelBinderTest
{
[Fact]
public async Task BindModel_ReturnsFailure_IfAttemptedValueCannotBeParsed()
{
// Arrange
var bindingContext = GetBindingContext();
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", "some-value" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
}
[Fact]
public async Task BindModel_CreatesError_IfAttemptedValueCannotBeParsed()
{
// Arrange
var message = "The value 'not a date' is not valid.";
var bindingContext = GetBindingContext();
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", "not a date" },
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
Assert.False(bindingContext.ModelState.IsValid);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal(message, error.ErrorMessage);
}
[Fact]
public async Task BindModel_CreatesError_IfAttemptedValueCannotBeCompletelyParsed()
{
// Arrange
var bindingContext = GetBindingContext();
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("en-GB"))
{
{ "theModelName", "2020-08-not-a-date" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal("The value '2020-08-not-a-date' is not valid.", error.ErrorMessage, StringComparer.Ordinal);
Assert.Null(error.Exception);
}
[Fact]
public async Task BindModel_ReturnsFailed_IfValueProviderEmpty()
{
// Arrange
var bindingContext = GetBindingContext(typeof(DateTime));
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.Equal(ModelBindingResult.Failed(), bindingContext.Result);
Assert.Empty(bindingContext.ModelState);
}
[Fact]
public async Task BindModel_NullableDatetime_ReturnsFailed_IfValueProviderEmpty()
{
// Arrange
var bindingContext = GetBindingContext(typeof(DateTime?));
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.Equal(ModelBindingResult.Failed(), bindingContext.Result);
Assert.Empty(bindingContext.ModelState);
}
[Theory]
[InlineData("")]
[InlineData(" \t \r\n ")]
public async Task BindModel_CreatesError_IfTrimmedAttemptedValueIsEmpty_NonNullableDestination(string value)
{
// Arrange
var message = $"The value '{value}' is invalid.";
var bindingContext = GetBindingContext();
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", value },
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.False(bindingContext.Result.IsModelSet);
Assert.Null(bindingContext.Result.Model);
var error = Assert.Single(bindingContext.ModelState["theModelName"].Errors);
Assert.Equal(message, error.ErrorMessage, StringComparer.Ordinal);
Assert.Null(error.Exception);
}
[Theory]
[InlineData("")]
[InlineData(" \t \r\n ")]
public async Task BindModel_ReturnsNull_IfTrimmedAttemptedValueIsEmpty_NullableDestination(string value)
{
// Arrange
var bindingContext = GetBindingContext(typeof(DateTime?));
bindingContext.ValueProvider = new SimpleValueProvider
{
{ "theModelName", value }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.Null(bindingContext.Result.Model);
var entry = Assert.Single(bindingContext.ModelState);
Assert.Equal("theModelName", entry.Key);
}
[Theory]
[InlineData(typeof(DateTime))]
[InlineData(typeof(DateTime?))]
public async Task BindModel_ReturnsModel_IfAttemptedValueIsValid(Type type)
{
// Arrange
var expected = new DateTime(2019, 06, 14, 2, 30, 4, 0, DateTimeKind.Utc);
var bindingContext = GetBindingContext(type);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("fr-FR"))
{
{ "theModelName", "2019-06-14T02:30:04.0000000Z" }
};
var binder = GetBinder();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
var model = Assert.IsType<DateTime>(bindingContext.Result.Model);
Assert.Equal(expected, model);
Assert.Equal(DateTimeKind.Utc, model.Kind);
Assert.True(bindingContext.ModelState.ContainsKey("theModelName"));
}
[Fact]
public async Task UsesSpecifiedStyleToParseModel()
{
// Arrange
var bindingContext = GetBindingContext();
var expected = DateTime.Parse("2019-06-14T02:30:04.0000000Z", CultureInfo.InvariantCulture);
bindingContext.ValueProvider = new SimpleValueProvider(new CultureInfo("fr-FR"))
{
{ "theModelName", "2019-06-14T02:30:04.0000000Z" }
};
var binder = GetBinder(DateTimeStyles.AssumeLocal);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
var model = Assert.IsType<DateTime>(bindingContext.Result.Model);
Assert.Equal(expected, model);
Assert.Equal(DateTimeKind.Local, model.Kind);
Assert.True(bindingContext.ModelState.ContainsKey("theModelName"));
}
private IModelBinder GetBinder(DateTimeStyles? dateTimeStyles = null)
{
return new DateTimeModelBinder(dateTimeStyles ?? DateTimeModelBinderProvider.SupportedStyles, NullLoggerFactory.Instance);
}
private static DefaultModelBindingContext GetBindingContext(Type modelType = null)
{
modelType ??= typeof(DateTime);
return new DefaultModelBindingContext
{
ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(modelType),
ModelName = "theModelName",
ModelState = new ModelStateDictionary(),
ValueProvider = new SimpleValueProvider() // empty
};
}
}
}
| |
//---------------------------------------------------------------------------
// <copyright file="RubberbandSelector.cs" company="Microsoft">
// Copyright (C) 2003 by Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
//
// History:
// 09/29/2004 - Eric Leese (eleese) - Created.
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
using MS.Internal; // For Invariant.Assert
using MS.Internal.Documents;
using System.Windows; // DependencyID etc.
using System.Windows.Controls; // Canvas
using System.Collections;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.TextFormatting; // CharacterHit
using System.Windows.Shapes; // Glyphs
using System.Windows.Markup;
using System.Windows.Input;
using System.Threading;
using System;
using System.IO;
using System.Collections.Generic;
using System.Security ;
using System.Security.Permissions ;
using System.Diagnostics;
//=====================================================================
/// <summary>
/// Class has a function similar to that of TextEditor. It can be attached
/// to a PageGrid by PageViewer to enable rubber band selection. It should not
/// be attached at the same time TextEditor is attached.
/// </summary>
internal sealed class RubberbandSelector
{
#region Internal Methods
/// <summary>
/// Clears current selection
/// </summary>
internal void ClearSelection()
{
if (HasSelection)
{
FixedPage p = _page;
_page = null;
UpdateHighlightVisual(p);
}
_selectionRect = Rect.Empty;
}
/// <summary>
/// Attaches selector to scope to start rubberband selection mode
/// </summary>
/// <param name="scope">the scope, typically a DocumentGrid</param>
///<SecurityNote>
/// Critical - creates a command binding.
/// TAS - registering our own internal commands is considered safe.
///</SecurityNote>
[SecurityCritical , SecurityTreatAsSafe ]
internal void AttachRubberbandSelector(FrameworkElement scope)
{
if (scope == null)
{
throw new ArgumentNullException("scope");
}
ClearSelection();
scope.MouseLeftButtonDown += new MouseButtonEventHandler(OnLeftMouseDown);
scope.MouseLeftButtonUp += new MouseButtonEventHandler(OnLeftMouseUp);
scope.MouseMove += new MouseEventHandler(OnMouseMove);
scope.QueryCursor += new QueryCursorEventHandler(OnQueryCursor);
scope.Cursor = null; // Cursors.Cross;
//If the passed-in scope is DocumentGrid, we want to
//attach our commands to its DocumentViewerOwner, since
//DocumentGrid is not focusable by default.
if (scope is DocumentGrid)
{
_uiScope = ((DocumentGrid)scope).DocumentViewerOwner;
Invariant.Assert(_uiScope != null, "DocumentGrid's DocumentViewerOwner cannot be null.");
}
else
{
_uiScope = scope;
}
//Attach the RubberBandSelector's Copy command to the UIScope.
CommandBinding binding = new CommandBinding(ApplicationCommands.Copy);
binding.Executed += new ExecutedRoutedEventHandler(OnCopy);
binding.CanExecute += new CanExecuteRoutedEventHandler(QueryCopy);
_uiScope.CommandBindings.Add(binding);
_scope = scope;
}
/// <summary>
/// Removes rubberband selector from its scope -- gets out of rubberband selection mode
/// </summary>
internal void DetachRubberbandSelector()
{
ClearSelection();
if (_scope != null)
{
_scope.MouseLeftButtonDown -= new MouseButtonEventHandler(OnLeftMouseDown);
_scope.MouseLeftButtonUp -= new MouseButtonEventHandler(OnLeftMouseUp);
_scope.MouseMove -= new MouseEventHandler(OnMouseMove);
_scope.QueryCursor -= new QueryCursorEventHandler(OnQueryCursor);
_scope = null;
}
if (_uiScope != null)
{
CommandBindingCollection commandBindings = _uiScope.CommandBindings;
foreach (CommandBinding binding in commandBindings)
{
if (binding.Command == ApplicationCommands.Copy)
{
binding.Executed -= new ExecutedRoutedEventHandler(OnCopy);
binding.CanExecute -= new CanExecuteRoutedEventHandler(QueryCopy);
}
}
_uiScope = null;
}
}
#endregion Internal Methods
#region Private Methods
// extends current selection to point
private void ExtendSelection(Point pt)
{
// clip to page
Size pageSize = _panel.ComputePageSize(_page);
if (pt.X < 0)
{
pt.X = 0;
}
else if (pt.X > pageSize.Width)
{
pt.X = pageSize.Width;
}
if (pt.Y < 0)
{
pt.Y = 0;
}
else if (pt.Y > pageSize.Height)
{
pt.Y = pageSize.Height;
}
//create rectangle extending from selection origin to current point
_selectionRect = new Rect(_origin, pt);
UpdateHighlightVisual(_page);
}
//redraws highlights on page
private void UpdateHighlightVisual(FixedPage page)
{
if (page != null)
{
HighlightVisual hv = HighlightVisual.GetHighlightVisual(page);
if (hv != null)
{
hv.UpdateRubberbandSelection(this);
}
}
}
/// <SecurityNote>
/// Critical : Demands
/// Safe : Does not leak security exception information to caller.
/// This code checks for all permissions
/// that it would otherwise assert to enable rubber band copy. This is to make sure untrusted applications
/// do not trigger a copy.
/// </SecurityNote>
[SecuritySafeCritical]
private bool HasRubberBandCopyPermissions()
{
try
{
(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter | SecurityPermissionFlag.UnmanagedCode)).Demand();
CodeAccessPermission mediaAccessPermission = SecurityHelper.CreateMediaAccessPermission(null);
mediaAccessPermission.Demand();
return true;
}
catch (SecurityException)
{
return false;
}
}
/// <SecurityNote>
/// Critical: This calls into GetBitmap, which is security critical. It also puts a bitmap on the
/// clipboard, which is not typically allowed in partially trusted code.It also asserts
/// to add content to the clipboard
/// TreatAsSafe: We guarantee this code can only be triggered by the user deliberately copying the
/// selection. Because we generate the bitmap from what the user sees, this is no more
/// dangerous than a screen capture.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void OnCopy(object sender, ExecutedRoutedEventArgs e)
{
if (HasSelection && _selectionRect.Width > 0 && _selectionRect.Height > 0)
{
//Copy to clipboard
IDataObject dataObject;
string textString = GetText();
object bmp = null;
bool supportImageCopy = false;
if (_scope is DocumentGrid && ((DocumentGrid)_scope).DocumentViewerOwner is DocumentApplicationDocumentViewer)
{
// This is XPSViewer, make sure it is user initiated
if (!e.UserInitiated && !HasRubberBandCopyPermissions())
{
return;
}
supportImageCopy = true;
}
else
{
//Outside of XPSViewer, support image copy in full trust only
supportImageCopy = HasRubberBandCopyPermissions();
}
if (supportImageCopy)
{
bmp = SystemDrawingHelper.GetBitmapFromBitmapSource(GetImage());
}
(new UIPermission(UIPermissionClipboard.AllClipboard)).Assert();//BlessedAssert
try
{
dataObject = new DataObject();
// Order of data is irrelevant, the pasting application will determine format
dataObject.SetData(DataFormats.Text, textString, true);
dataObject.SetData(DataFormats.UnicodeText, textString, true);
if (bmp != null)
{
dataObject.SetData(DataFormats.Bitmap, bmp, true);
}
}
finally
{
UIPermission.RevertAssert();
}
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
ps.AddPermission(new UIPermission(UIPermissionClipboard.AllClipboard));
ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
if (supportImageCopy)
{
CodeAccessPermission mediaAccessPermission = SecurityHelper.CreateMediaAccessPermission(null);
ps.AddPermission(mediaAccessPermission);
}
ps.Assert(); // BlessedAssert
try
{
Clipboard.SetDataObject(dataObject, true);
}
catch (System.Runtime.InteropServices.ExternalException)
{
// Clipboard is failed to set the data object.
return;
}
finally
{
SecurityPermission.RevertAssert();
}
}
}
//gets snapshot image
private BitmapSource GetImage()
{
//get copy of page
Visual v = GetVisual(-_selectionRect.Left, -_selectionRect.Top);
//create image of appropriate size
double dpi = 96; // default screen dpi, in fact no other dpi seems to work if you want something at 100% scale
double scale = dpi / 96.0;
RenderTargetBitmap data = new RenderTargetBitmap((int)(scale * _selectionRect.Width), (int)(scale * _selectionRect.Height),dpi,dpi, PixelFormats.Pbgra32);
data.Render(v);
return data;
}
private Visual GetVisual(double offsetX, double offsetY)
{
ContainerVisual root = new ContainerVisual();
DrawingVisual visual = new DrawingVisual();
root.Children.Add(visual);
visual.Offset = new Vector(offsetX, offsetY);
DrawingContext dc = visual.RenderOpen();
dc.DrawDrawing(_page.GetDrawing());
dc.Close();
UIElementCollection vc = _page.Children;
foreach (UIElement child in vc)
{
CloneVisualTree(visual, child);
}
return root;
}
private void CloneVisualTree(ContainerVisual parent, Visual old)
{
DrawingVisual visual = new DrawingVisual();
parent.Children.Add(visual);
visual.Clip = VisualTreeHelper.GetClip(old);
visual.Offset = VisualTreeHelper.GetOffset(old);
visual.Transform = VisualTreeHelper.GetTransform(old);
visual.Opacity = VisualTreeHelper.GetOpacity(old);
visual.OpacityMask = VisualTreeHelper.GetOpacityMask(old);
#pragma warning disable 0618
visual.BitmapEffectInput = VisualTreeHelper.GetBitmapEffectInput(old);
visual.BitmapEffect = VisualTreeHelper.GetBitmapEffect(old);
#pragma warning restore 0618
// snapping guidelines??
DrawingContext dc = visual.RenderOpen();
dc.DrawDrawing(old.GetDrawing());
dc.Close();
int count = VisualTreeHelper.GetChildrenCount(old);
for(int i = 0; i < count; i++)
{
Visual child = old.InternalGetVisualChild(i);
CloneVisualTree(visual, child);
}
}
//gets text within selected area
private string GetText()
{
double top = _selectionRect.Top;
double bottom = _selectionRect.Bottom;
double left = _selectionRect.Left;
double right = _selectionRect.Right;
double lastBaseline = 0;
double baseline = 0;
double lastHeight = 0;
double height = 0;
int nChildren = _page.Children.Count;
ArrayList ranges = new ArrayList(); //text ranges in area
FixedNode[] nodesInLine = _panel.FixedContainer.FixedTextBuilder.GetFirstLine(_pageIndex);
while (nodesInLine != null && nodesInLine.Length > 0)
{
TextPositionPair textRange = null; //current text range
foreach (FixedNode node in nodesInLine)
{
Glyphs g = _page.GetGlyphsElement(node);
if (g != null)
{
int begin, end; //first and last index in range
bool includeEnd; //is the end of this glyphs included in selection?
if (IntersectGlyphs(g, top, left, bottom, right, out begin, out end, out includeEnd, out baseline, out height))
{
if (textRange == null || begin > 0)
{
//begin new text range
textRange = new TextPositionPair();
textRange.first = _GetTextPosition(node, begin);
ranges.Add(textRange);
}
textRange.second = _GetTextPosition(node, end);
if (!includeEnd)
{
// so future textRanges aren't concatenated with this one
textRange = null;
}
}
else
{
//this Glyphs completely outside selected region
textRange = null;
}
lastBaseline = baseline;
lastHeight = height;
}
}
int count = 1;
nodesInLine = _panel.FixedContainer.FixedTextBuilder.GetNextLine(nodesInLine[0], true, ref count);
}
string text = "";
foreach (TextPositionPair range in ranges)
{
Debug.Assert(range.first != null && range.second != null);
text = text + TextRangeBase.GetTextInternal(range.first, range.second) + "\r\n"; //CRLF
}
return text;
}
private ITextPointer _GetTextPosition(FixedNode node, int charIndex)
{
FixedPosition fixedPosition = new FixedPosition(node, charIndex);
// Create a FlowPosition to represent this fixed position
FlowPosition flowHit = _panel.FixedContainer.FixedTextBuilder.CreateFlowPosition(fixedPosition);
if (flowHit != null)
{
// Create a TextPointer from the flow position
return new FixedTextPointer(false, LogicalDirection.Forward, flowHit);
}
return null;
}
//determines whether and where a rectangle intersects a Glyphs
private bool IntersectGlyphs(Glyphs g, double top, double left, double bottom, double right, out int begin, out int end, out bool includeEnd, out double baseline, out double height)
{
begin = 0;
end = 0;
includeEnd = false;
GlyphRun run = g.ToGlyphRun();
Rect boundingRect = run.ComputeAlignmentBox();
boundingRect.Offset(run.BaselineOrigin.X, run.BaselineOrigin.Y);
//useful for same line detection
baseline = run.BaselineOrigin.Y;
height = boundingRect.Height;
double centerLine = boundingRect.Y + .5 * boundingRect.Height;
GeneralTransform t = g.TransformToAncestor(_page);
Point pt1;
t.TryTransform(new Point(boundingRect.Left, centerLine), out pt1);
Point pt2;
t.TryTransform(new Point(boundingRect.Right, centerLine), out pt2);
double dStart, dEnd;
bool cross = false;
if (pt1.X < left)
{
if (pt2.X < left)
{
return false;
}
cross = true;
}
else if (pt1.X > right)
{
if (pt2.X > right)
{
return false;
}
cross = true;
}
else if (pt2.X < left || pt2.X > right)
{
cross = true;
}
if (cross)
{
double d1 = (left - pt1.X) / (pt2.X - pt1.X);
double d2 = (right - pt1.X) / (pt2.X - pt1.X);
if (d2 > d1)
{
dStart = d1;
dEnd = d2;
}
else
{
dStart = d2;
dEnd = d1;
}
}
else
{
dStart = 0;
dEnd = 1;
}
cross = false;
if (pt1.Y < top)
{
if (pt2.Y < top)
{
return false;
}
cross = true;
}
else if (pt1.Y > bottom)
{
if (pt2.Y > bottom)
{
return false;
}
cross = true;
}
else if (pt2.Y < top || pt2.Y > bottom)
{
cross = true;
}
if (cross)
{
double d1 = (top - pt1.Y) / (pt2.Y - pt1.Y);
double d2 = (bottom - pt1.Y) / (pt2.Y - pt1.Y);
if (d2 > d1)
{
if (d1 > dStart)
{
dStart = d1;
}
if (d2 < dEnd)
{
dEnd = d2;
}
}
else
{
if (d2 > dStart)
{
dStart = d2;
}
if (d1 < dEnd)
{
dEnd = d1;
}
}
}
dStart = boundingRect.Left + boundingRect.Width * dStart;
dEnd = boundingRect.Left + boundingRect.Width * dEnd;
bool leftToRight = ((run.BidiLevel & 1) == 0);
begin = GlyphRunHitTest(run, dStart, leftToRight);
end = GlyphRunHitTest(run, dEnd, leftToRight);
if (begin > end)
{
int temp = begin;
begin = end;
end = temp;
}
Debug.Assert(end >= begin);
int characterCount = (run.Characters == null) ? 0 : run.Characters.Count;
includeEnd = (end == characterCount);
return true;
}
//Returns the character offset in a GlyphRun given an X position
private int GlyphRunHitTest(GlyphRun run, double xoffset, bool LTR)
{
bool isInside;
double distance = LTR ? xoffset - run.BaselineOrigin.X : run.BaselineOrigin.X - xoffset;
CharacterHit hit = run.GetCaretCharacterHitFromDistance(distance, out isInside);
return hit.FirstCharacterIndex + hit.TrailingLength;
}
//queryenabled handler for copy command
private void QueryCopy(object sender, CanExecuteRoutedEventArgs e)
{
if (HasSelection)
{
e.CanExecute = true;
}
}
private void OnLeftMouseDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
FixedDocumentPage dp = GetFixedPanelDocumentPage(e.GetPosition(_scope));
if (dp != null)
{
//give focus to the UI Scope so that actions like
//Copy will work after making a selection.
_uiScope.Focus();
//turn on mouse capture
_scope.CaptureMouse();
ClearSelection();
//mark start position
_panel = dp.Owner;
_page = dp.FixedPage;
_isSelecting = true;
_origin = e.GetPosition(_page);
_pageIndex = dp.PageIndex;
}
}
private void OnLeftMouseUp(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
_scope.ReleaseMouseCapture();
if (_isSelecting)
{
_isSelecting = false;
if (_page != null)
{
ExtendSelection(e.GetPosition(_page));
}
}
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
e.Handled = true;
if (e.LeftButton == MouseButtonState.Released)
{
_isSelecting = false;
}
else if (_isSelecting)
{
if (_page != null)
{
ExtendSelection(e.GetPosition(_page));
}
}
}
private void OnQueryCursor(object sender, QueryCursorEventArgs e)
{
if (_isSelecting || GetFixedPanelDocumentPage(e.GetPosition(_scope)) != null)
{
e.Cursor = Cursors.Cross;
}
else
{
e.Cursor = Cursors.Arrow;
}
e.Handled = true;
}
private FixedDocumentPage GetFixedPanelDocumentPage(Point pt)
{
DocumentGrid mpScope = _scope as DocumentGrid;
if (mpScope != null)
{
DocumentPage dp = mpScope.GetDocumentPageFromPoint(pt);
FixedDocumentPage fdp = dp as FixedDocumentPage;
if (fdp == null)
{
FixedDocumentSequenceDocumentPage fdsdp = dp as FixedDocumentSequenceDocumentPage;
if (fdsdp != null)
{
fdp = fdsdp.ChildDocumentPage as FixedDocumentPage;
}
}
return fdp;
}
return null;
}
#endregion Private Methods
#region Internal Properties
internal FixedPage Page
{
get { return _page; }
}
internal Rect SelectionRect
{
get { return _selectionRect; }
}
internal bool HasSelection
{
get { return _page != null && _panel != null && !_selectionRect.IsEmpty; }
}
#endregion Internal Properties
#region Private Fields
private FixedDocument _panel; // FixedDocument on which we are selecting
private FixedPage _page; // page on which we are selecting, or null
private Rect _selectionRect; // rectangle in page coordinates, or empty
private bool _isSelecting; // true if mouse is down and we are currently drawing the box
private Point _origin; // point where we started dragging
private UIElement _scope; // element to which we are attached
private FrameworkElement _uiScope; // parent of _scope, if _scope is a DocumentGrid.
private int _pageIndex; // index of _page
#endregion Private Fields
// a lightweight TextRange like class used in GetText. We needed a class
// here because we needed this to be a reference type.
private class TextPositionPair
{
public ITextPointer first;
public ITextPointer second;
}
}
}
| |
// Copyright (c) 2013-2014 Andrew Downing
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// identifies a unit on a path segment
/// </summary>
/// <remarks>this is a struct instead of a class because it compares by value</remarks>
public struct SegmentUnit {
public readonly Sim g;
public readonly Segment segment;
public readonly Unit unit;
public SegmentUnit(Segment segmentVal, Unit unitVal) {
segment = segmentVal;
unit = unitVal;
g = segment.g;
}
/// <summary>
/// removes unit from this segment and fewest possible unseen segments such that all remaining possibilities are valid,
/// returns whether successful
/// </summary>
public bool delete(bool addMoveLines = false) {
// *****************
// BEGIN DANGER ZONE
// *****************
// There are many non-trivial cases this function needs to handle, so only modify it if you know what you are doing.
// Even then, you will likely break a corner case anyway but not notice until a week or two later.
//
// If what you want to do is actually some sort of postprocessing using the deleted SegmentUnits,
// it's best to do it at the end of the function (after the "danger zone") by iterating over the "removed" variable.
if (!segment.units.Contains (unit)) return true; // if this segment already doesn't contain this unit, return true
List<SegmentUnit> ancestors = new List<SegmentUnit> { this };
Dictionary<Segment, List<Unit>> removed = new Dictionary<Segment, List<Unit>>();
long timeEarliestChild = long.MaxValue;
int i;
// find all ancestor segments to start removal from
for (i = 0; i < ancestors.Count; i++) {
if (ancestors[i].prev ().Any ()) {
// if this ancestor has a sibling segment that we're not currently planning to remove unit from,
// don't remove unit from previous segments shared by both
Unit u = unit;
if (!ancestors[i].segment.branches.Where(seg => seg.units.Contains(u) && !ancestors.Contains(new SegmentUnit(seg, u))
&& (seg.path.timeSimPast == long.MaxValue || ancestors[i].segment.path.timeSimPast != long.MaxValue)).Any()) {
// indicate to remove unit from previous segments
ancestors.AddRange (ancestors[i].prev ());
ancestors.RemoveAt(i);
i--;
}
} else if (ancestors[i].segment.prev ().Any ()) {
// unit has a parent but we're deleting its first segment, so may need to check resources starting at this time
if (ancestors[i].unit.attacks.Count > 0) return false;
if (ancestors[i].segment.timeStart < timeEarliestChild && ancestors[i].unit.type.rscCollectRate.Where (r => r > 0).Any ()) {
timeEarliestChild = ancestors[i].segment.timeStart;
}
} else {
// reached a segment with no previous segment whatsoever, so return false (we assume other players know the scenario's starting state)
return false;
}
}
// remove unit recursively, starting at the ancestor segments we found
for (i = 0; i < ancestors.Count; i++) {
if (!ancestors[i].deleteAfter (ref removed, ref timeEarliestChild)) break;
}
// if a deleteAfter() call failed or removing unit led to player ever having negative resources,
// add units back to segments they were removed from
if (i < ancestors.Count || (timeEarliestChild != long.MaxValue && segment.path.player.checkNegRsc (timeEarliestChild, false) >= 0)) {
foreach (KeyValuePair<Segment, List<Unit>> item in removed) {
item.Key.units.AddRange (item.Value);
}
return false;
}
// ***************
// END DANGER ZONE
// ***************
foreach (KeyValuePair<Segment, List<Unit>> item in removed) {
// add deleted units to list
if (item.Key.timeStart < g.timeSim) {
if (item.Key.nextOnPath () == null) item.Key.path.insertSegment (g.timeSim);
item.Key.deletedUnits.AddRange (item.Value);
}
}
if (addMoveLines) {
// add deleted unit lines
// TODO: tweak time if deleted before timeSimPast
MoveLine deleteLine = new MoveLine(Math.Min (Math.Max (segment.path.timeSimPast, segment.path.moves[0].timeStart), g.timeSim), unit.player);
foreach (Segment seg in removed.Keys) {
deleteLine.vertices.AddRange (seg.path.moveLines (seg.timeStart,
(seg.nextOnPath () == null || seg.nextOnPath ().timeStart > deleteLine.time) ? deleteLine.time : seg.nextOnPath ().timeStart));
}
g.deleteLines.Add (deleteLine);
}
return true;
}
private bool deleteAfter(ref Dictionary<Segment, List<Unit>> removed, ref long timeEarliestChild) {
// *****************
// BEGIN DANGER ZONE - see comment in delete()
// *****************
if (segment.units.Contains (unit)) {
if (!segment.unseen && segment.timeStart < g.timeSim) return false;
// only remove units from next segments if this is their only previous segment
if (segment.nextOnPath () == null || new SegmentUnit(segment.nextOnPath (), unit).prev ().Count () == 1) {
// remove unit from next segments
foreach (SegmentUnit segmentUnit in next ()) {
if (!segmentUnit.deleteAfter (ref removed, ref timeEarliestChild)) return false;
}
// remove child units that only this unit could have made
foreach (SegmentUnit child in children ().ToArray ()) {
// TODO: if has alternate non-live parent, do we need to recursively make children non-live?
if (child.parents ().Count () == 1) {
if (child.unit.attacks.Count > 0) return false;
if (!child.deleteAfter (ref removed, ref timeEarliestChild)) return false;
if (child.segment.timeStart < timeEarliestChild && child.unit.type.rscCollectRate.Where (r => r > 0).Any ()) {
timeEarliestChild = child.segment.timeStart;
}
}
}
}
// remove unit from this segment
segment.units.Remove (unit);
if (!removed.ContainsKey (segment)) removed.Add (segment, new List<Unit>());
removed[segment].Add (unit);
}
return true;
// ***************
// END DANGER ZONE
// ***************
}
public bool unseenAfter(long time) {
if (!segment.unseen || (unit.attacks.Count > 0 && time < unit.attacks.Last().time)) return false;
foreach (SegmentUnit segmentUnit in next ()) {
if (!segmentUnit.unseenAfter (time)) return false;
}
foreach (SegmentUnit child in children ()) {
if (!child.unseenAfter (time)) return false;
}
return true;
}
public bool hasChildrenAfter() {
if (children ().Any ()) return false; // TODO: this should return true if other units could make the child
foreach (SegmentUnit segmentUnit in next ()) {
if (!segmentUnit.hasChildrenAfter ()) return false;
}
return true;
}
/// <summary>
/// returns whether this unit exists before specified time,
/// so if it makes a child unit at specified time, it's unambiguous who is the parent
/// </summary>
public bool canBeUnambiguousParent(long time) {
return segment.timeStart < time || prev().Any();
}
/// <summary>
/// iterates over all segment/unit pairs that could have made this unit in this segment
/// </summary>
public IEnumerable<SegmentUnit> parents() {
if (!prev ().Any ()) {
foreach (Segment seg in segment.prev ()) {
foreach (SegmentUnit segmentUnit in seg.segmentUnits ()) {
if (segmentUnit.unit.type.canMake[unit.type.id]) {
yield return segmentUnit;
}
}
}
}
}
/// <summary>
/// iterates over all segment/unit pairs that this unit in this segment could have made
/// </summary>
public IEnumerable<SegmentUnit> children() {
foreach (Segment seg in segment.next ()) {
foreach (SegmentUnit segmentUnit in seg.segmentUnits ()) {
if (unit.type.canMake[segmentUnit.unit.type.id] && !segmentUnit.prev ().Any ()) {
yield return segmentUnit;
}
}
}
}
/// <summary>
/// iterates over all segments containing this unit that merge onto the beginning of this segment
/// </summary>
public IEnumerable<SegmentUnit> prev() {
foreach (Segment seg in segment.prev()) {
if (seg.units.Contains (unit)) yield return new SegmentUnit(seg, unit);
}
}
/// <summary>
/// iterates over all segments containing this unit that branch off from the end of this segment
/// </summary>
public IEnumerable<SegmentUnit> next() {
foreach (Segment seg in segment.next()) {
if (seg.units.Contains (unit)) yield return new SegmentUnit(seg, unit);
}
}
}
| |
// 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.Globalization;
namespace System.ServiceModel.Channels
{
public abstract class FaultConverter
{
public static FaultConverter GetDefaultFaultConverter(MessageVersion version)
{
return new DefaultFaultConverter(version);
}
protected abstract bool OnTryCreateException(Message message, MessageFault fault, out Exception exception);
protected abstract bool OnTryCreateFaultMessage(Exception exception, out Message message);
public bool TryCreateException(Message message, MessageFault fault, out Exception exception)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(message));
}
if (fault == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(fault));
}
bool created = OnTryCreateException(message, fault, out exception);
if (created)
{
if (exception == null)
{
string text = SR.Format(SR.FaultConverterDidNotCreateException, GetType().Name);
Exception error = new InvalidOperationException(text);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
else
{
if (exception != null)
{
string text = SR.Format(SR.FaultConverterCreatedException, GetType().Name);
Exception error = new InvalidOperationException(text, exception);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
return created;
}
public bool TryCreateFaultMessage(Exception exception, out Message message)
{
bool created = OnTryCreateFaultMessage(exception, out message);
if (created)
{
if (message == null)
{
string text = SR.Format(SR.FaultConverterDidNotCreateFaultMessage, GetType().Name);
Exception error = new InvalidOperationException(text);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
else
{
if (message != null)
{
string text = SR.Format(SR.FaultConverterCreatedFaultMessage, GetType().Name);
Exception error = new InvalidOperationException(text);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
return created;
}
internal class DefaultFaultConverter : FaultConverter
{
private MessageVersion _version;
internal DefaultFaultConverter(MessageVersion version)
{
_version = version;
}
protected override bool OnTryCreateException(Message message, MessageFault fault, out Exception exception)
{
exception = null;
// SOAP MustUnderstand
if (string.Compare(fault.Code.Namespace, _version.Envelope.Namespace, StringComparison.Ordinal) == 0
&& string.Compare(fault.Code.Name, MessageStrings.MustUnderstandFault, StringComparison.Ordinal) == 0)
{
exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text);
return true;
}
bool checkSender;
bool checkReceiver;
FaultCode code;
if (_version.Envelope == EnvelopeVersion.Soap11)
{
checkSender = true;
checkReceiver = true;
code = fault.Code;
}
else
{
checkSender = fault.Code.IsSenderFault;
checkReceiver = fault.Code.IsReceiverFault;
code = fault.Code.SubCode;
}
if (code == null)
{
return false;
}
if (code.Namespace == null)
{
return false;
}
if (checkSender)
{
// WS-Addressing
if (string.Compare(code.Namespace, _version.Addressing.Namespace, StringComparison.Ordinal) == 0)
{
if (string.Compare(code.Name, AddressingStrings.ActionNotSupported, StringComparison.Ordinal) == 0)
{
exception = new ActionNotSupportedException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text);
return true;
}
else if (string.Compare(code.Name, AddressingStrings.DestinationUnreachable, StringComparison.Ordinal) == 0)
{
exception = new EndpointNotFoundException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text);
return true;
}
else if (string.Compare(code.Name, Addressing10Strings.InvalidAddressingHeader, StringComparison.Ordinal) == 0)
{
if (code.SubCode != null && string.Compare(code.SubCode.Namespace, _version.Addressing.Namespace, StringComparison.Ordinal) == 0 &&
string.Compare(code.SubCode.Name, Addressing10Strings.InvalidCardinality, StringComparison.Ordinal) == 0)
{
exception = new MessageHeaderException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text, true);
return true;
}
}
else if (_version.Addressing == AddressingVersion.WSAddressing10)
{
if (string.Compare(code.Name, Addressing10Strings.MessageAddressingHeaderRequired, StringComparison.Ordinal) == 0)
{
exception = new MessageHeaderException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text);
return true;
}
else if (string.Compare(code.Name, Addressing10Strings.InvalidAddressingHeader, StringComparison.Ordinal) == 0)
{
exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text);
return true;
}
}
else
{
if (string.Compare(code.Name, Addressing200408Strings.MessageInformationHeaderRequired, StringComparison.Ordinal) == 0)
{
exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text);
return true;
}
else if (string.Compare(code.Name, Addressing200408Strings.InvalidMessageInformationHeader, StringComparison.Ordinal) == 0)
{
exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text);
return true;
}
}
}
}
if (checkReceiver)
{
// WS-Addressing
if (string.Compare(code.Namespace, _version.Addressing.Namespace, StringComparison.Ordinal) == 0)
{
if (string.Compare(code.Name, AddressingStrings.EndpointUnavailable, StringComparison.Ordinal) == 0)
{
exception = new ServerTooBusyException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text);
return true;
}
}
}
return false;
}
protected override bool OnTryCreateFaultMessage(Exception exception, out Message message)
{
// WSA
if (_version.Addressing == AddressingVersion.WSAddressing10)
{
if (exception is MessageHeaderException)
{
MessageHeaderException mhe = exception as MessageHeaderException;
if (mhe.HeaderNamespace == AddressingVersion.WSAddressing10.Namespace)
{
message = mhe.ProvideFault(_version);
return true;
}
}
else if (exception is ActionMismatchAddressingException)
{
ActionMismatchAddressingException amae = exception as ActionMismatchAddressingException;
message = amae.ProvideFault(_version);
return true;
}
}
if (_version.Addressing != AddressingVersion.None)
{
if (exception is ActionNotSupportedException)
{
ActionNotSupportedException anse = exception as ActionNotSupportedException;
message = anse.ProvideFault(_version);
return true;
}
}
// SOAP
if (exception is MustUnderstandSoapException)
{
MustUnderstandSoapException muse = exception as MustUnderstandSoapException;
message = muse.ProvideFault(_version);
return true;
}
message = null;
return false;
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Implementation of the LineOutput interface for printer
/// </summary>
internal sealed class PrinterLineOutput : LineOutput
{
#region LineOutput implementation
/// <summary>
/// full buffering for printer
/// </summary>
internal override bool RequiresBuffering { get { return true; } }
/// <summary>
/// do the printing on playback
/// </summary>
internal override void ExecuteBufferPlayBack(DoPlayBackCall playback)
{
_playbackCall = playback;
DoPrint();
}
/// <summary>
/// the # of columns for the printer
/// </summary>
/// <value></value>
internal override int ColumnNumber
{
get
{
CheckStopProcessing();
return _deviceColumns;
}
}
/// <summary>
/// the # of rows for the printer
/// </summary>
/// <value></value>
internal override int RowNumber
{
get
{
CheckStopProcessing();
return _deviceRows;
}
}
/// <summary>
/// write a line to the output device
/// </summary>
/// <param name="s">line to write</param>
internal override void WriteLine(string s)
{
CheckStopProcessing();
// delegate the action to the helper,
// that will properly break the string into
// screen lines
_writeLineHelper.WriteLine(s, this.ColumnNumber);
}
#endregion
/// <summary>
/// Used for static initializations like DefaultPrintFontName
/// </summary>
static PrinterLineOutput()
{
// This default must be loaded from a resource file as different
// cultures will have different defaults and the localizer would
// know the default for different cultures.
s_defaultPrintFontName = OutPrinterDisplayStrings.DefaultPrintFontName;
}
/// <summary>
/// constructor for the class
/// </summary>
/// <param name="printerName">name of printer, if null use default printer</param>
internal PrinterLineOutput(string printerName)
{
_printerName = printerName;
// instantiate the helper to do the line processing when LineOutput.WriteXXX() is called
WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine);
WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite);
_writeLineHelper = new WriteLineHelper(true, wl, w, this.DisplayCells);
}
/// <summary>
/// callback to be called when IConsole.WriteLine() is called by WriteLineHelper
/// </summary>
/// <param name="s">string to write</param>
private void OnWriteLine(string s)
{
_lines.Enqueue(s);
}
/// <summary>
/// callback to be called when Console.Write() is called by WriteLineHelper
/// This is called when the WriteLineHelper needs to write a line whose length
/// is the same as the width of the screen buffer
/// </summary>
/// <param name="s">string to write</param>
private void OnWrite(string s)
{
_lines.Enqueue(s);
}
/// <summary>
/// do the printing
/// </summary>
private void DoPrint()
{
try
{
// create a new print document object and set the printer name, if available
PrintDocument pd = new PrintDocument();
if (!string.IsNullOrEmpty(_printerName))
{
pd.PrinterSettings.PrinterName = _printerName;
}
// set up the callback mechanism
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
// start printing
pd.Print();
}
finally
{
// make sure we do not leak the font
if (_printFont != null)
{
_printFont.Dispose();
_printFont = null;
}
}
}
/// <summary>
/// helper to create a font.
/// If the font object exists, it does nothing.
/// Else, the a new object is created and verified
/// </summary>
/// <param name="g">GDI+ graphics object needed for verification</param>
private void CreateFont(Graphics g)
{
if (_printFont != null)
return;
// create the font
// do we have a specified font?
if (string.IsNullOrEmpty(_printFontName))
{
_printFontName = s_defaultPrintFontName;
}
if (_printFontSize <= 0)
{
_printFontSize = DefaultPrintFontSize;
}
_printFont = new Font(_printFontName, _printFontSize);
VerifyFont(g);
}
/// <summary>
/// internal helper to verify that the font is fixed pitch. If the test fails,
/// it reverts to the default font
/// </summary>
/// <param name="g">GDI+ graphics object needed for verification</param>
private void VerifyFont(Graphics g)
{
// check if the font is fixed pitch
// HEURISTICS:
// we compute the length of two strings, one made of "large" characters
// one made of "narrow" ones. If they are the same length, we assume that
// the font is fixed pitch.
string large = "ABCDEF";
float wLarge = g.MeasureString(large, _printFont).Width / large.Length;
string narrow = ".;'}l|";
float wNarrow = g.MeasureString(narrow, _printFont).Width / narrow.Length;
if (Math.Abs((float)(wLarge - wNarrow)) < 0.001F)
{
// we passed the test
return;
}
// just get back to the default, since it's not fixed pitch
_printFont.Dispose();
_printFont = new Font(s_defaultPrintFontName, DefaultPrintFontSize);
}
/// <summary>
/// Event fired for each page to print
/// </summary>
/// <param name="sender">sender, not used</param>
/// <param name="ev">print page event</param>
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float yPos = 0; // GDI+ coordinate down the page
int linesPrinted = 0; // linesPrinted
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
CreateFont(ev.Graphics);
// compute the height of a line of text
float lineHeight = _printFont.GetHeight(ev.Graphics);
// Work out the number of lines per page
// Use the MarginBounds on the event to do this
float linesPerPage = ev.MarginBounds.Height / _printFont.GetHeight(ev.Graphics);
if (!_printingInitialized)
{
// on the first page we have to initialize the metrics for LineOutput
// work out the number of columns per page assuming fixed pitch font
string s = "ABCDEF";
float w = ev.Graphics.MeasureString(s, _printFont).Width / s.Length;
float columnsPerPage = ev.MarginBounds.Width / w;
_printingInitialized = true;
_deviceRows = (int)linesPerPage;
_deviceColumns = (int)columnsPerPage;
// now that we initialized the column and row count for the LineOutput
// interface we can tell the outputter to playback from cache to do the
// proper computations of line widths
// returning from this call, the string queue on this object is full of
// lines of text to print
_playbackCall();
}
// now iterate over the file printing out each line
while ((linesPrinted < linesPerPage) && (_lines.Count > 0))
{
// get the string to be printed
String line = _lines.Dequeue();
// compute the Y position where to draw
yPos = topMargin + (linesPrinted * lineHeight);
// do the actual drawing
ev.Graphics.DrawString(line, _printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
linesPrinted++;
}
//If we have more lines then print another page
ev.HasMorePages = _lines.Count > 0;
}
/// <summary>
/// flag for one time initialization of the interface (columns, etc.)
/// </summary>
private bool _printingInitialized = false;
/// <summary>
/// callback to ask the outputter to playback its cache
/// </summary>
private DoPlayBackCall _playbackCall;
/// <summary>
/// name of the printer to print to. Null means default printer
/// </summary>
private string _printerName = null;
/// <summary>
/// name of the font to use, if null the default is used
/// </summary>
private string _printFontName = null;
/// <summary>
/// font size
/// </summary>
private int _printFontSize = 0;
/// <summary>
/// default font, used if the printFont is not specified or if the
/// printFont is not fixed pitch.
/// </summary>
/// <remarks>
/// This default must be loaded from a resource file as different
/// cultures will have different defaults and the localizer would
/// know the default for different cultures.
/// </remarks>
private static readonly string s_defaultPrintFontName;
/// <summary>
/// default size for the default font
/// </summary>
private const int DefaultPrintFontSize = 8;
/// <summary>
/// number of columns on the sheet
/// </summary>
private int _deviceColumns = 80;
// number of rows per sheet
private int _deviceRows = 40;
/// <summary>
/// text lines ready to print (after output cache playback)
/// </summary>
private Queue<string> _lines = new Queue<string>();
/// <summary>
/// cached font object
/// </summary>
private Font _printFont = null;
private WriteLineHelper _writeLineHelper;
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetDegradedBlobsSpectraS3Request : Ds3Request
{
private string _blobId;
public string BlobId
{
get { return _blobId; }
set { WithBlobId(value); }
}
private string _bucketId;
public string BucketId
{
get { return _bucketId; }
set { WithBucketId(value); }
}
private string _ds3ReplicationRuleId;
public string Ds3ReplicationRuleId
{
get { return _ds3ReplicationRuleId; }
set { WithDs3ReplicationRuleId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _persistenceRuleId;
public string PersistenceRuleId
{
get { return _persistenceRuleId; }
set { WithPersistenceRuleId(value); }
}
public GetDegradedBlobsSpectraS3Request WithBlobId(Guid? blobId)
{
this._blobId = blobId.ToString();
if (blobId != null)
{
this.QueryParams.Add("blob_id", blobId.ToString());
}
else
{
this.QueryParams.Remove("blob_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithBlobId(string blobId)
{
this._blobId = blobId;
if (blobId != null)
{
this.QueryParams.Add("blob_id", blobId);
}
else
{
this.QueryParams.Remove("blob_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithBucketId(Guid? bucketId)
{
this._bucketId = bucketId.ToString();
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId.ToString());
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithBucketId(string bucketId)
{
this._bucketId = bucketId;
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId);
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithDs3ReplicationRuleId(Guid? ds3ReplicationRuleId)
{
this._ds3ReplicationRuleId = ds3ReplicationRuleId.ToString();
if (ds3ReplicationRuleId != null)
{
this.QueryParams.Add("ds3_replication_rule_id", ds3ReplicationRuleId.ToString());
}
else
{
this.QueryParams.Remove("ds3_replication_rule_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithDs3ReplicationRuleId(string ds3ReplicationRuleId)
{
this._ds3ReplicationRuleId = ds3ReplicationRuleId;
if (ds3ReplicationRuleId != null)
{
this.QueryParams.Add("ds3_replication_rule_id", ds3ReplicationRuleId);
}
else
{
this.QueryParams.Remove("ds3_replication_rule_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPersistenceRuleId(Guid? persistenceRuleId)
{
this._persistenceRuleId = persistenceRuleId.ToString();
if (persistenceRuleId != null)
{
this.QueryParams.Add("persistence_rule_id", persistenceRuleId.ToString());
}
else
{
this.QueryParams.Remove("persistence_rule_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPersistenceRuleId(string persistenceRuleId)
{
this._persistenceRuleId = persistenceRuleId;
if (persistenceRuleId != null)
{
this.QueryParams.Add("persistence_rule_id", persistenceRuleId);
}
else
{
this.QueryParams.Remove("persistence_rule_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/degraded_blob";
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 408099 $
* $LastChangedDate: 2006-05-20 15:56:36 -0600 (Sat, 20 May 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Using
using System;
using System.Data;
using System.Reflection;
using System.Xml.Serialization;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities;
#endregion
namespace IBatisNet.Common
{
/// <summary>
/// Information about a data provider.
/// </summary>
[Serializable]
[XmlRoot("provider", Namespace = "http://ibatis.apache.org/providers")]
public class DbProvider : IDbProvider
{
private const string SQLPARAMETER = "?";
#region Fields
[NonSerialized] private bool _allowMARS;
[NonSerialized] private string _assemblyName = string.Empty;
[NonSerialized] private string _commandBuilderClass = string.Empty;
[NonSerialized] private Type _commandBuilderType;
[NonSerialized] private string _commandClass = string.Empty;
[NonSerialized] private string _connectionClass = string.Empty;
[NonSerialized] private string _dataAdapterClass = string.Empty;
[NonSerialized] private int _dbCommandTimeOut;
[NonSerialized] private string _description = string.Empty;
[NonSerialized] private bool _isDefault;
[NonSerialized] private bool _isEnabled = true;
[NonSerialized] private string _name = string.Empty;
[NonSerialized] private Type _parameterDbType;
[NonSerialized] private string _parameterDbTypeClass = string.Empty;
[NonSerialized] private string _parameterDbTypeProperty = string.Empty;
[NonSerialized] private string _parameterPrefix = string.Empty;
[NonSerialized] private bool _setDbParameterPrecision = true;
[NonSerialized] private bool _setDbParameterScale = true;
[NonSerialized] private bool _setDbParameterSize = true;
[NonSerialized] private IDbConnection _templateConnection;
[NonSerialized] private bool _templateConnectionIsICloneable;
[NonSerialized] private IDbDataAdapter _templateDataAdapter;
[NonSerialized] private bool _templateDataAdapterIsICloneable;
[NonSerialized] private bool _useDeriveParameters = true;
[NonSerialized] private bool _useParameterPrefixInParameter = true;
[NonSerialized] private bool _useParameterPrefixInSql = true;
[NonSerialized] private bool _usePositionalParameters;
// private static readonly ILog _connectionLogger = LogManager.GetLogger("System.Data.IDbConnection");
#endregion
#region Properties
/// <summary>
/// An optional property to specify the DBCommand Timeout for
/// the specified provider.
/// </summary>
/// <value>The DB command timeout.</value>
public int DbCommandTimeout
{
get { return _dbCommandTimeOut; }
set { _dbCommandTimeOut = value; }
}
/// <summary>
/// The name of the assembly which conatins the definition of the provider.
/// </summary>
/// <example>Examples : "System.Data", "Microsoft.Data.Odbc"</example>
[XmlAttribute("assemblyName")]
public string AssemblyName
{
get { return _assemblyName; }
set
{
CheckPropertyString("AssemblyName", value);
_assemblyName = value;
}
}
/// <summary>
/// Tell us if it is the default data source.
/// Default false.
/// </summary>
[XmlAttribute("default")]
public bool IsDefault
{
get { return _isDefault; }
set { _isDefault = value; }
}
/// <summary>
/// Tell us if this provider is enabled.
/// Default true.
/// </summary>
[XmlAttribute("enabled")]
public bool IsEnabled
{
get { return _isEnabled; }
set { _isEnabled = value; }
}
/// <summary>
/// Tell us if this provider allows having multiple open <see cref="IDataReader"/> with
/// the same <see cref="IDbConnection"/>.
/// </summary>
/// <remarks>
/// It's a new feature in ADO.NET 2.0 and Sql Server 2005 that allows for multiple forward only read only result sets (MARS).
/// Some databases have supported this functionality for a long time :
/// Not Supported : DB2, MySql.Data, OLE DB provider [except Sql Server 2005 when using MDAC 9], SQLite, Obdc
/// Supported : Sql Server 2005, Npgsql
/// </remarks>
[XmlAttribute("allowMARS")]
public bool AllowMARS
{
get { return _allowMARS; }
set { _allowMARS = value; }
}
/// <summary>
/// The connection class name to use.
/// </summary>
/// <example>
/// "System.Data.OleDb.OleDbConnection",
/// "System.Data.SqlClient.SqlConnection",
/// "Microsoft.Data.Odbc.OdbcConnection"
/// </example>
[XmlAttribute("connectionClass")]
public string DbConnectionClass
{
get { return _connectionClass; }
set
{
CheckPropertyString("DbConnectionClass", value);
_connectionClass = value;
}
}
/// <summary>
/// Does this ConnectionProvider require the use of a Named Prefix in the SQL
/// statement.
/// </summary>
/// <remarks>
/// The OLE DB/ODBC .NET Provider does not support named parameters for
/// passing parameters to an SQL Statement or a stored procedure called
/// by an IDbCommand when CommandType is set to Text.
///
/// For example, SqlClient requires select * from simple where simple_id = @simple_id
/// If this is false, like with the OleDb or Obdc provider, then it is assumed that
/// the ? can be a placeholder for the parameter in the SQL statement when CommandType
/// is set to Text.
/// </remarks>
[XmlAttribute("useParameterPrefixInSql")]
public bool UseParameterPrefixInSql
{
get { return _useParameterPrefixInSql; }
set { _useParameterPrefixInSql = value; }
}
/// <summary>
/// Does this ConnectionProvider require the use of the Named Prefix when trying
/// to reference the Parameter in the Command's Parameter collection.
/// </summary>
/// <remarks>
/// This is really only useful when the UseParameterPrefixInSql = true.
/// When this is true the code will look like IDbParameter param = cmd.Parameters["@paramName"],
/// if this is false the code will be IDbParameter param = cmd.Parameters["paramName"] - ie - Oracle.
/// </remarks>
[XmlAttribute("useParameterPrefixInParameter")]
public bool UseParameterPrefixInParameter
{
get { return _useParameterPrefixInParameter; }
set { _useParameterPrefixInParameter = value; }
}
/// <summary>
/// The OLE DB/OBDC .NET Provider uses positional parameters that are marked with a
/// question mark (?) instead of named parameters.
/// </summary>
[XmlAttribute("usePositionalParameters")]
public bool UsePositionalParameters
{
get { return _usePositionalParameters; }
set { _usePositionalParameters = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports parameter size.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter size.
/// </remarks>
[XmlAttribute("setDbParameterSize")]
public bool SetDbParameterSize
{
get { return _setDbParameterSize; }
set { _setDbParameterSize = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports parameter precision.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter precision.
/// </remarks>
[XmlAttribute("setDbParameterPrecision")]
public bool SetDbParameterPrecision
{
get { return _setDbParameterPrecision; }
set { _setDbParameterPrecision = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports a parameter scale.
/// </summary>
/// <remarks>
/// See JIRA-49 about SQLite.Net provider not supporting parameter scale.
/// </remarks>
[XmlAttribute("setDbParameterScale")]
public bool SetDbParameterScale
{
get { return _setDbParameterScale; }
set { _setDbParameterScale = value; }
}
/// <summary>
/// Used to indicate whether or not the provider
/// supports DeriveParameters method for procedure.
/// </summary>
[XmlAttribute("useDeriveParameters")]
public bool UseDeriveParameters
{
get { return _useDeriveParameters; }
set { _useDeriveParameters = value; }
}
/// <summary>
/// The command class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlClient.SqlCommand"
/// </example>
[XmlAttribute("commandClass")]
public string DbCommandClass
{
get { return _commandClass; }
set
{
CheckPropertyString("DbCommandClass", value);
_commandClass = value;
}
}
/// <summary>
/// The ParameterDbType class name to use.
/// </summary>
/// <example>
/// "System.Data.SqlDbType"
/// </example>
[XmlAttribute("parameterDbTypeClass")]
public string ParameterDbTypeClass
{
get { return _parameterDbTypeClass; }
set
{
CheckPropertyString("ParameterDbTypeClass", value);
_parameterDbTypeClass = value;
}
}
/// <summary>
/// The ParameterDbTypeProperty class name to use.
/// </summary>
/// <example >
/// SqlDbType in SqlParamater.SqlDbType,
/// OracleType in OracleParameter.OracleType.
/// </example>
[XmlAttribute("parameterDbTypeProperty")]
public string ParameterDbTypeProperty
{
get { return _parameterDbTypeProperty; }
set
{
CheckPropertyString("ParameterDbTypeProperty", value);
_parameterDbTypeProperty = value;
}
}
/// <summary>
/// The dataAdapter class name to use.
/// </summary>
/// <example >
/// "System.Data.SqlDbType"
/// </example>
[XmlAttribute("dataAdapterClass")]
public string DataAdapterClass
{
get { return _dataAdapterClass; }
set
{
CheckPropertyString("DataAdapterClass", value);
_dataAdapterClass = value;
}
}
/// <summary>
/// The commandBuilder class name to use.
/// </summary>
/// <example >
/// "System.Data.OleDb.OleDbCommandBuilder",
/// "System.Data.SqlClient.SqlCommandBuilder",
/// "Microsoft.Data.Odbc.OdbcCommandBuilder"
/// </example>
[XmlAttribute("commandBuilderClass")]
public string CommandBuilderClass
{
get { return _commandBuilderClass; }
set
{
CheckPropertyString("CommandBuilderClass", value);
_commandBuilderClass = value;
}
}
/// <summary>
/// Name used to identify the provider amongst the others.
/// </summary>
[XmlAttribute("name")]
public string Name
{
get { return _name; }
set
{
CheckPropertyString("Name", value);
_name = value;
}
}
/// <summary>
/// Description.
/// </summary>
[XmlAttribute("description")]
public string Description
{
get { return _description; }
set { _description = value; }
}
/// <summary>
/// Parameter prefix use in store procedure.
/// </summary>
/// <example> @ for Sql Server.</example>
[XmlAttribute("parameterPrefix")]
public string ParameterPrefix
{
get { return _parameterPrefix; }
set
{
if ((value == null) || (value.Length < 1))
{
_parameterPrefix = "";
}
else
{
_parameterPrefix = value;
}
}
}
/// <summary>
/// Check if this provider is Odbc ?
/// </summary>
[XmlIgnore]
public bool IsObdc
{
get { return (_connectionClass.IndexOf(".Odbc.") > 0); }
}
/// <summary>
/// Get the CommandBuilder Type for this provider.
/// </summary>
/// <returns>An object.</returns>
public Type CommandBuilderType
{
get { return _commandBuilderType; }
}
/// <summary>
/// Get the ParameterDb Type for this provider.
/// </summary>
/// <returns>An object.</returns>
[XmlIgnore]
public Type ParameterDbType
{
get { return _parameterDbType; }
}
#endregion
#region Constructor (s) / Destructor
#endregion
#region Methods
/// <summary>
/// Init the provider.
/// </summary>
public void Initialize()
{
Assembly assembly = null;
Type type = null;
try
{
assembly = Assembly.Load(_assemblyName);
// Build the DataAdapter template
type = assembly.GetType(_dataAdapterClass, true);
CheckPropertyType("DataAdapterClass", typeof (IDbDataAdapter), type);
_templateDataAdapter = (IDbDataAdapter) type.GetConstructor(Type.EmptyTypes).Invoke(null);
// Build the connection template
type = assembly.GetType(_connectionClass, true);
CheckPropertyType("DbConnectionClass", typeof (IDbConnection), type);
_templateConnection = (IDbConnection) type.GetConstructor(Type.EmptyTypes).Invoke(null);
// Get the CommandBuilder Type
_commandBuilderType = assembly.GetType(_commandBuilderClass, true);
if (_parameterDbTypeClass.IndexOf(',') > 0)
{
_parameterDbType = TypeUtils.ResolveType(_parameterDbTypeClass);
}
else
{
_parameterDbType = assembly.GetType(_parameterDbTypeClass, true);
}
_templateConnectionIsICloneable = _templateConnection is ICloneable;
_templateDataAdapterIsICloneable = _templateDataAdapter is ICloneable;
}
catch (Exception e)
{
throw new ConfigurationException(
string.Format(
"Could not configure providers. Unable to load provider named \"{0}\" not found, failed. Cause: {1}",
_name, e.Message), e
);
}
}
/// <summary>
/// Create a connection object for this provider.
/// </summary>
/// <returns>An 'IDbConnection' object.</returns>
public virtual IDbConnection CreateConnection()
{
// Cannot do that because on
// IDbCommand.Connection = cmdConnection
// .NET cast the cmdConnection to the real type (as SqlConnection)
// and we pass a proxy --> exception invalid cast !
// if (_connectionLogger.IsDebugEnabled)
// {
// connection = (IDbConnection)IDbConnectionProxy.NewInstance(connection, this);
// }
if (_templateConnectionIsICloneable)
{
return (IDbConnection) ((ICloneable) _templateConnection).Clone();
}
return (IDbConnection) Activator.CreateInstance(_templateConnection.GetType());
}
/// <summary>
/// Create a command object for this provider.
/// </summary>
/// <returns>An 'IDbCommand' object.</returns>
public virtual IDbCommand CreateCommand()
{
return _templateConnection.CreateCommand();
}
/// <summary>
/// Create a dataAdapter object for this provider.
/// </summary>
/// <returns>An 'IDbDataAdapter' object.</returns>
public virtual IDbDataAdapter CreateDataAdapter()
{
if (_templateDataAdapterIsICloneable)
{
return (IDbDataAdapter) ((ICloneable) _templateDataAdapter).Clone();
}
return (IDbDataAdapter) Activator.CreateInstance(_templateDataAdapter.GetType());
}
/// <summary>
/// Create a IDbDataParameter object for this provider.
/// </summary>
/// <returns>An 'IDbDataParameter' object.</returns>
public virtual IDbDataParameter CreateDataParameter()
{
return _templateConnection.CreateCommand().CreateParameter();
}
/// <summary>
/// Change the parameterName into the correct format IDbCommand.CommandText
/// for the ConnectionProvider
/// </summary>
/// <param name="parameterName">The unformatted name of the parameter</param>
/// <returns>A parameter formatted for an IDbCommand.CommandText</returns>
public virtual string FormatNameForSql(string parameterName)
{
return _useParameterPrefixInSql ? (_parameterPrefix + parameterName) : SQLPARAMETER;
}
/// <summary>
/// Changes the parameterName into the correct format for an IDbParameter
/// for the Driver.
/// </summary>
/// <remarks>
/// For SqlServerConnectionProvider it will change <c>id</c> to <c>@id</c>
/// </remarks>
/// <param name="parameterName">The unformatted name of the parameter</param>
/// <returns>A parameter formatted for an IDbParameter.</returns>
public virtual string FormatNameForParameter(string parameterName)
{
return _useParameterPrefixInParameter ? (_parameterPrefix + parameterName) : parameterName;
}
/// <summary>
/// Equals implemantation.
/// </summary>
/// <param name="obj">The test object.</param>
/// <returns>A boolean.</returns>
public override bool Equals(object obj)
{
if ((obj != null) && (obj is IDbProvider))
{
IDbProvider that = (IDbProvider)obj;
return ((_name == that.Name) &&
(_assemblyName == that.AssemblyName) &&
(_connectionClass == that.DbConnectionClass));
}
return false;
}
/// <summary>
/// A hashcode for the provider.
/// </summary>
/// <returns>An integer.</returns>
public override int GetHashCode()
{
return (_name.GetHashCode() ^ _assemblyName.GetHashCode() ^ _connectionClass.GetHashCode());
}
/// <summary>
/// ToString implementation.
/// </summary>
/// <returns>A string that describes the provider.</returns>
public override string ToString()
{
return "Provider " + _name;
}
private void CheckPropertyString(string propertyName, string value)
{
if (value == null || value.Trim().Length == 0)
{
throw new ArgumentException(
"The " + propertyName + " property cannot be " +
"set to a null or empty string value.", propertyName);
}
}
private void CheckPropertyType(string propertyName, Type expectedType, Type value)
{
if (value == null)
{
throw new ArgumentNullException(
propertyName, "The " + propertyName + " property cannot be null.");
}
if (!expectedType.IsAssignableFrom(value))
{
throw new ArgumentException(
"The Type passed to the " + propertyName + " property must be an " + expectedType.Name +
" implementation.");
}
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="AdGroupAdLabelServiceClient"/> instances.</summary>
public sealed partial class AdGroupAdLabelServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupAdLabelServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupAdLabelServiceSettings"/>.</returns>
public static AdGroupAdLabelServiceSettings GetDefault() => new AdGroupAdLabelServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdGroupAdLabelServiceSettings"/> object with default settings.
/// </summary>
public AdGroupAdLabelServiceSettings()
{
}
private AdGroupAdLabelServiceSettings(AdGroupAdLabelServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupAdLabelSettings = existing.GetAdGroupAdLabelSettings;
MutateAdGroupAdLabelsSettings = existing.MutateAdGroupAdLabelsSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupAdLabelServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupAdLabelServiceClient.GetAdGroupAdLabel</c> and
/// <c>AdGroupAdLabelServiceClient.GetAdGroupAdLabelAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdGroupAdLabelSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupAdLabelServiceClient.MutateAdGroupAdLabels</c> and
/// <c>AdGroupAdLabelServiceClient.MutateAdGroupAdLabelsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAdGroupAdLabelsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupAdLabelServiceSettings"/> object.</returns>
public AdGroupAdLabelServiceSettings Clone() => new AdGroupAdLabelServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupAdLabelServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdGroupAdLabelServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupAdLabelServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupAdLabelServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupAdLabelServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupAdLabelServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupAdLabelServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupAdLabelServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupAdLabelServiceClient Build()
{
AdGroupAdLabelServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupAdLabelServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupAdLabelServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupAdLabelServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupAdLabelServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupAdLabelServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupAdLabelServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupAdLabelServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupAdLabelServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupAdLabelServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupAdLabelService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on ad group ads.
/// </remarks>
public abstract partial class AdGroupAdLabelServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupAdLabelService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupAdLabelService scopes.</summary>
/// <remarks>
/// The default AdGroupAdLabelService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupAdLabelServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupAdLabelServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupAdLabelServiceClient"/>.</returns>
public static stt::Task<AdGroupAdLabelServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupAdLabelServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupAdLabelServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupAdLabelServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupAdLabelServiceClient"/>.</returns>
public static AdGroupAdLabelServiceClient Create() => new AdGroupAdLabelServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupAdLabelServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupAdLabelServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupAdLabelServiceClient"/>.</returns>
internal static AdGroupAdLabelServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupAdLabelServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupAdLabelService.AdGroupAdLabelServiceClient grpcClient = new AdGroupAdLabelService.AdGroupAdLabelServiceClient(callInvoker);
return new AdGroupAdLabelServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupAdLabelService client</summary>
public virtual AdGroupAdLabelService.AdGroupAdLabelServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAdLabel GetAdGroupAdLabel(GetAdGroupAdLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdLabel> GetAdGroupAdLabelAsync(GetAdGroupAdLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdLabel> GetAdGroupAdLabelAsync(GetAdGroupAdLabelRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupAdLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAdLabel GetAdGroupAdLabel(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAdLabel(new GetAdGroupAdLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdLabel> GetAdGroupAdLabelAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAdLabelAsync(new GetAdGroupAdLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad label to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdLabel> GetAdGroupAdLabelAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAdLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupAdLabel GetAdGroupAdLabel(gagvr::AdGroupAdLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAdLabel(new GetAdGroupAdLabelRequest
{
ResourceNameAsAdGroupAdLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdLabel> GetAdGroupAdLabelAsync(gagvr::AdGroupAdLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAdLabelAsync(new GetAdGroupAdLabelRequest
{
ResourceNameAsAdGroupAdLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group ad label to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupAdLabel> GetAdGroupAdLabelAsync(gagvr::AdGroupAdLabelName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAdLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes ad group ad labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupAdLabelsResponse MutateAdGroupAdLabels(MutateAdGroupAdLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes ad group ad labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(MutateAdGroupAdLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes ad group ad labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(MutateAdGroupAdLabelsRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupAdLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes ad group ad labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group ad labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group ad labels.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupAdLabelsResponse MutateAdGroupAdLabels(string customerId, scg::IEnumerable<AdGroupAdLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupAdLabels(new MutateAdGroupAdLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes ad group ad labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group ad labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group ad labels.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(string customerId, scg::IEnumerable<AdGroupAdLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupAdLabelsAsync(new MutateAdGroupAdLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes ad group ad labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group ad labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group ad labels.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(string customerId, scg::IEnumerable<AdGroupAdLabelOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupAdLabelsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupAdLabelService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on ad group ads.
/// </remarks>
public sealed partial class AdGroupAdLabelServiceClientImpl : AdGroupAdLabelServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupAdLabelRequest, gagvr::AdGroupAdLabel> _callGetAdGroupAdLabel;
private readonly gaxgrpc::ApiCall<MutateAdGroupAdLabelsRequest, MutateAdGroupAdLabelsResponse> _callMutateAdGroupAdLabels;
/// <summary>
/// Constructs a client wrapper for the AdGroupAdLabelService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AdGroupAdLabelServiceSettings"/> used within this client.</param>
public AdGroupAdLabelServiceClientImpl(AdGroupAdLabelService.AdGroupAdLabelServiceClient grpcClient, AdGroupAdLabelServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupAdLabelServiceSettings effectiveSettings = settings ?? AdGroupAdLabelServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroupAdLabel = clientHelper.BuildApiCall<GetAdGroupAdLabelRequest, gagvr::AdGroupAdLabel>(grpcClient.GetAdGroupAdLabelAsync, grpcClient.GetAdGroupAdLabel, effectiveSettings.GetAdGroupAdLabelSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroupAdLabel);
Modify_GetAdGroupAdLabelApiCall(ref _callGetAdGroupAdLabel);
_callMutateAdGroupAdLabels = clientHelper.BuildApiCall<MutateAdGroupAdLabelsRequest, MutateAdGroupAdLabelsResponse>(grpcClient.MutateAdGroupAdLabelsAsync, grpcClient.MutateAdGroupAdLabels, effectiveSettings.MutateAdGroupAdLabelsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroupAdLabels);
Modify_MutateAdGroupAdLabelsApiCall(ref _callMutateAdGroupAdLabels);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdGroupAdLabelApiCall(ref gaxgrpc::ApiCall<GetAdGroupAdLabelRequest, gagvr::AdGroupAdLabel> call);
partial void Modify_MutateAdGroupAdLabelsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupAdLabelsRequest, MutateAdGroupAdLabelsResponse> call);
partial void OnConstruction(AdGroupAdLabelService.AdGroupAdLabelServiceClient grpcClient, AdGroupAdLabelServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupAdLabelService client</summary>
public override AdGroupAdLabelService.AdGroupAdLabelServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupAdLabelRequest(ref GetAdGroupAdLabelRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateAdGroupAdLabelsRequest(ref MutateAdGroupAdLabelsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdGroupAdLabel GetAdGroupAdLabel(GetAdGroupAdLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupAdLabelRequest(ref request, ref callSettings);
return _callGetAdGroupAdLabel.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad group ad label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdGroupAdLabel> GetAdGroupAdLabelAsync(GetAdGroupAdLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupAdLabelRequest(ref request, ref callSettings);
return _callGetAdGroupAdLabel.Async(request, callSettings);
}
/// <summary>
/// Creates and removes ad group ad labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAdGroupAdLabelsResponse MutateAdGroupAdLabels(MutateAdGroupAdLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupAdLabelsRequest(ref request, ref callSettings);
return _callMutateAdGroupAdLabels.Sync(request, callSettings);
}
/// <summary>
/// Creates and removes ad group ad labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAdGroupAdLabelsResponse> MutateAdGroupAdLabelsAsync(MutateAdGroupAdLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupAdLabelsRequest(ref request, ref callSettings);
return _callMutateAdGroupAdLabels.Async(request, callSettings);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Iso9660
{
using System;
using System.Collections.Generic;
using System.IO;
using DiscUtils.Vfs;
internal class VfsCDReader : VfsReadOnlyFileSystem<ReaderDirEntry, File, ReaderDirectory, IsoContext>, IClusterBasedFileSystem, IUnixFileSystem
{
private static readonly Iso9660Variant[] DefaultVariantsNoJoliet = new Iso9660Variant[] { Iso9660Variant.RockRidge, Iso9660Variant.Iso9660 };
private static readonly Iso9660Variant[] DefaultVariantsWithJoliet = new Iso9660Variant[] { Iso9660Variant.Joliet, Iso9660Variant.RockRidge, Iso9660Variant.Iso9660 };
private Stream _data;
private bool _hideVersions;
private BootVolumeDescriptor _bootVolDesc;
private byte[] _bootCatalog;
private Iso9660Variant _activeVariant;
/// <summary>
/// Initializes a new instance of the VfsCDReader class.
/// </summary>
/// <param name="data">The stream to read the ISO image from.</param>
/// <param name="joliet">Whether to read Joliet extensions.</param>
/// <param name="hideVersions">Hides version numbers (e.g. ";1") from the end of files</param>
public VfsCDReader(Stream data, bool joliet, bool hideVersions)
: this(data, joliet ? DefaultVariantsWithJoliet : DefaultVariantsNoJoliet, hideVersions)
{
}
/// <summary>
/// Initializes a new instance of the VfsCDReader class.
/// </summary>
/// <param name="data">The stream to read the ISO image from.</param>
/// <param name="variantPriorities">Which possible file system variants to use, and with which priority</param>
/// <param name="hideVersions">Hides version numbers (e.g. ";1") from the end of files</param>
/// <remarks>
/// <para>
/// The implementation considers each of the file system variants in <c>variantProperties</c> and selects
/// the first which is determined to be present. In this example Joliet, then Rock Ridge, then vanilla
/// Iso9660 will be considered:
/// </para>
/// <code lang="cs">
/// VfsCDReader(stream, new Iso9660Variant[] {Joliet, RockRidge, Iso9660}, true);
/// </code>
/// <para>The Iso9660 variant should normally be specified as the final entry in the list. Placing it earlier
/// in the list will effectively mask later items and not including it may prevent some ISOs from being read.</para>
/// </remarks>
public VfsCDReader(Stream data, Iso9660Variant[] variantPriorities, bool hideVersions)
: base(new DiscFileSystemOptions())
{
_data = data;
_hideVersions = hideVersions;
long vdpos = 0x8000; // Skip lead-in
byte[] buffer = new byte[IsoUtilities.SectorSize];
long pvdPos = 0;
long svdPos = 0;
BaseVolumeDescriptor bvd;
do
{
data.Position = vdpos;
int numRead = data.Read(buffer, 0, IsoUtilities.SectorSize);
if (numRead != IsoUtilities.SectorSize)
{
break;
}
bvd = new BaseVolumeDescriptor(buffer, 0);
switch (bvd.VolumeDescriptorType)
{
case VolumeDescriptorType.Boot:
_bootVolDesc = new BootVolumeDescriptor(buffer, 0);
if (_bootVolDesc.SystemId != BootVolumeDescriptor.ElToritoSystemIdentifier)
{
_bootVolDesc = null;
}
break;
case VolumeDescriptorType.Primary: // Primary Vol Descriptor
pvdPos = vdpos;
break;
case VolumeDescriptorType.Supplementary: // Supplementary Vol Descriptor
svdPos = vdpos;
break;
case VolumeDescriptorType.Partition: // Volume Partition Descriptor
break;
case VolumeDescriptorType.SetTerminator: // Volume Descriptor Set Terminator
break;
}
vdpos += IsoUtilities.SectorSize;
}
while (bvd.VolumeDescriptorType != VolumeDescriptorType.SetTerminator);
_activeVariant = Iso9660Variant.None;
foreach (var variant in variantPriorities)
{
switch (variant)
{
case Iso9660Variant.Joliet:
if (svdPos != 0)
{
data.Position = svdPos;
data.Read(buffer, 0, IsoUtilities.SectorSize);
var volDesc = new SupplementaryVolumeDescriptor(buffer, 0);
Context = new IsoContext { VolumeDescriptor = volDesc, DataStream = _data };
RootDirectory = new ReaderDirectory(Context, new ReaderDirEntry(Context, volDesc.RootDirectory));
_activeVariant = Iso9660Variant.Iso9660;
}
break;
case Iso9660Variant.RockRidge:
case Iso9660Variant.Iso9660:
if (pvdPos != 0)
{
data.Position = pvdPos;
data.Read(buffer, 0, IsoUtilities.SectorSize);
var volDesc = new PrimaryVolumeDescriptor(buffer, 0);
IsoContext context = new IsoContext { VolumeDescriptor = volDesc, DataStream = _data };
DirectoryRecord rootSelfRecord = ReadRootSelfRecord(context);
InitializeSusp(context, rootSelfRecord);
if (variant == Iso9660Variant.Iso9660
|| (variant == Iso9660Variant.RockRidge && !string.IsNullOrEmpty(context.RockRidgeIdentifier)))
{
Context = context;
RootDirectory = new ReaderDirectory(context, new ReaderDirEntry(context, rootSelfRecord));
_activeVariant = variant;
}
}
break;
}
if (_activeVariant != Iso9660Variant.None)
{
break;
}
}
if (_activeVariant == Iso9660Variant.None)
{
throw new IOException("None of the permitted ISO9660 file system variants was detected");
}
}
/// <summary>
/// Provides the friendly name for the CD filesystem.
/// </summary>
public override string FriendlyName
{
get { return "ISO 9660 (CD-ROM)"; }
}
/// <summary>
/// Gets the Volume Identifier.
/// </summary>
public override string VolumeLabel
{
get { return Context.VolumeDescriptor.VolumeIdentifier; }
}
public bool HasBootImage
{
get
{
if (_bootVolDesc == null)
{
return false;
}
byte[] bootCatalog = GetBootCatalog();
if (bootCatalog == null)
{
return false;
}
BootValidationEntry entry = new BootValidationEntry(bootCatalog, 0);
return entry.ChecksumValid;
}
}
public BootDeviceEmulation BootEmulation
{
get
{
BootInitialEntry initialEntry = GetBootInitialEntry();
if (initialEntry != null)
{
return initialEntry.BootMediaType;
}
return BootDeviceEmulation.NoEmulation;
}
}
public int BootLoadSegment
{
get
{
BootInitialEntry initialEntry = GetBootInitialEntry();
if (initialEntry != null)
{
return initialEntry.LoadSegment;
}
return 0;
}
}
public long BootImageStart
{
get
{
BootInitialEntry initialEntry = GetBootInitialEntry();
if (initialEntry != null)
{
return initialEntry.ImageStart * IsoUtilities.SectorSize;
}
else
{
return 0;
}
}
}
public long ClusterSize
{
get { return IsoUtilities.SectorSize; }
}
public long TotalClusters
{
get { return Context.VolumeDescriptor.VolumeSpaceSize; }
}
public Iso9660Variant ActiveVariant
{
get { return _activeVariant; }
}
public Stream OpenBootImage()
{
BootInitialEntry initialEntry = GetBootInitialEntry();
if (initialEntry != null)
{
return new SubStream(_data, initialEntry.ImageStart * IsoUtilities.SectorSize, initialEntry.SectorCount * Sizes.Sector);
}
else
{
throw new InvalidOperationException("No valid boot image");
}
}
public UnixFileSystemInfo GetUnixFileInfo(string path)
{
File file = GetFile(path);
return file.UnixFileInfo;
}
public long ClusterToOffset(long cluster)
{
return cluster * ClusterSize;
}
public long OffsetToCluster(long offset)
{
return offset / ClusterSize;
}
public Range<long, long>[] PathToClusters(string path)
{
ReaderDirEntry entry = GetDirectoryEntry(path);
if (entry == null)
{
throw new FileNotFoundException("File not found", path);
}
if (entry.Record.FileUnitSize != 0 || entry.Record.InterleaveGapSize != 0)
{
throw new NotSupportedException("Non-contiguous extents not supported");
}
return new Range<long, long>[] { new Range<long, long>(entry.Record.LocationOfExtent, Utilities.Ceil(entry.Record.DataLength, IsoUtilities.SectorSize)) };
}
public StreamExtent[] PathToExtents(string path)
{
ReaderDirEntry entry = GetDirectoryEntry(path);
if (entry == null)
{
throw new FileNotFoundException("File not found", path);
}
if (entry.Record.FileUnitSize != 0 || entry.Record.InterleaveGapSize != 0)
{
throw new NotSupportedException("Non-contiguous extents not supported");
}
return new StreamExtent[] { new StreamExtent(entry.Record.LocationOfExtent * IsoUtilities.SectorSize, entry.Record.DataLength) };
}
public ClusterMap BuildClusterMap()
{
long totalClusters = TotalClusters;
ClusterRoles[] clusterToRole = new ClusterRoles[totalClusters];
object[] clusterToFileId = new object[totalClusters];
Dictionary<object, string[]> fileIdToPaths = new Dictionary<object, string[]>();
ForAllDirEntries(
string.Empty,
(path, entry) =>
{
string[] paths = null;
if (fileIdToPaths.ContainsKey(entry.UniqueCacheId))
{
paths = fileIdToPaths[entry.UniqueCacheId];
}
if (paths == null)
{
fileIdToPaths[entry.UniqueCacheId] = new string[] { path };
}
else
{
string[] newPaths = new string[paths.Length + 1];
Array.Copy(paths, newPaths, paths.Length);
newPaths[paths.Length] = path;
fileIdToPaths[entry.UniqueCacheId] = newPaths;
}
if (entry.Record.FileUnitSize != 0 || entry.Record.InterleaveGapSize != 0)
{
throw new NotSupportedException("Non-contiguous extents not supported");
}
long clusters = Utilities.Ceil(entry.Record.DataLength, IsoUtilities.SectorSize);
for (long i = 0; i < clusters; ++i)
{
clusterToRole[i + entry.Record.LocationOfExtent] = ClusterRoles.DataFile;
clusterToFileId[i + entry.Record.LocationOfExtent] = entry.UniqueCacheId;
}
});
return new ClusterMap(clusterToRole, clusterToFileId, fileIdToPaths);
}
protected override File ConvertDirEntryToFile(ReaderDirEntry dirEntry)
{
if (dirEntry.IsDirectory)
{
return new ReaderDirectory(Context, dirEntry);
}
else
{
return new File(Context, dirEntry);
}
}
protected override string FormatFileName(string name)
{
if (_hideVersions)
{
int pos = name.LastIndexOf(';');
if (pos > 0)
{
return name.Substring(0, pos);
}
}
return name;
}
private static void InitializeSusp(IsoContext context, DirectoryRecord rootSelfRecord)
{
// Stage 1 - SUSP present?
List<SuspExtension> extensions = new List<SuspExtension>();
if (!SuspRecords.DetectSharingProtocol(rootSelfRecord.SystemUseData, 0))
{
context.SuspExtensions = new List<SuspExtension>();
context.SuspDetected = false;
return;
}
else
{
context.SuspDetected = true;
}
SuspRecords suspRecords = new SuspRecords(context, rootSelfRecord.SystemUseData, 0);
// Stage 2 - Init general SUSP params
SharingProtocolSystemUseEntry spEntry = (SharingProtocolSystemUseEntry)suspRecords.GetEntries(null, "SP")[0];
context.SuspSkipBytes = spEntry.SystemAreaSkip;
// Stage 3 - Init extensions
List<SystemUseEntry> extensionEntries = suspRecords.GetEntries(null, "ER");
if (extensionEntries != null)
{
foreach (ExtensionSystemUseEntry extension in extensionEntries)
{
switch (extension.ExtensionIdentifier)
{
case "RRIP_1991A":
case "IEEE_P1282":
case "IEEE_1282":
extensions.Add(new RockRidgeExtension(extension.ExtensionIdentifier));
context.RockRidgeIdentifier = extension.ExtensionIdentifier;
break;
default:
extensions.Add(new GenericSuspExtension(extension.ExtensionIdentifier));
break;
}
}
}
else if (suspRecords.GetEntries(null, "RR") != null)
{
// Some ISO creators don't add the 'ER' record for RockRidge, but write the (legacy)
// RR record anyway
extensions.Add(new RockRidgeExtension("RRIP_1991A"));
context.RockRidgeIdentifier = "RRIP_1991A";
}
context.SuspExtensions = extensions;
}
private static DirectoryRecord ReadRootSelfRecord(IsoContext context)
{
context.DataStream.Position = context.VolumeDescriptor.RootDirectory.LocationOfExtent * context.VolumeDescriptor.LogicalBlockSize;
byte[] firstSector = Utilities.ReadFully(context.DataStream, context.VolumeDescriptor.LogicalBlockSize);
DirectoryRecord rootSelfRecord;
DirectoryRecord.ReadFrom(firstSector, 0, context.VolumeDescriptor.CharacterEncoding, out rootSelfRecord);
return rootSelfRecord;
}
private BootInitialEntry GetBootInitialEntry()
{
byte[] bootCatalog = GetBootCatalog();
if (bootCatalog == null)
{
return null;
}
BootValidationEntry validationEntry = new BootValidationEntry(bootCatalog, 0);
if (!validationEntry.ChecksumValid)
{
return null;
}
return new BootInitialEntry(bootCatalog, 0x20);
}
private byte[] GetBootCatalog()
{
if (_bootCatalog == null && _bootVolDesc != null)
{
_data.Position = _bootVolDesc.CatalogSector * IsoUtilities.SectorSize;
_bootCatalog = Utilities.ReadFully(_data, IsoUtilities.SectorSize);
}
return _bootCatalog;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text;
using System.Globalization;
using System.Management.Automation.Internal;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Writer class to handle Complex Object formatting.
/// </summary>
internal sealed class ComplexWriter
{
/// <summary>
/// Initialization method to be called before any other operation.
/// </summary>
/// <param name="lineOutput">LineOutput interfaces to write to.</param>
/// <param name="numberOfTextColumns">Number of columns used to write out.</param>
internal void Initialize(LineOutput lineOutput, int numberOfTextColumns)
{
_lo = lineOutput;
_textColumns = numberOfTextColumns;
}
/// <summary>
/// Writes a string.
/// </summary>
/// <param name="s"></param>
internal void WriteString(string s)
{
_indentationManager.Clear();
AddToBuffer(s);
WriteToScreen();
}
/// <summary>
/// It interprets a list of format value tokens and outputs it.
/// </summary>
/// <param name="formatValueList">List of FormatValue tokens to interpret.</param>
internal void WriteObject(List<FormatValue> formatValueList)
{
// we always start with no indentation
_indentationManager.Clear();
foreach (FormatEntry fe in formatValueList)
{
// operate on each directive inside the list,
// carrying the indentation from invocation to invocation
GenerateFormatEntryDisplay(fe, 0);
}
// make sure that, if we have pending text in the buffer it gets flushed
WriteToScreen();
}
/// <summary>
/// Operate on a single entry.
/// </summary>
/// <param name="fe">Entry to process.</param>
/// <param name="currentDepth">Current depth of recursion.</param>
private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth)
{
foreach (object obj in fe.formatValueList)
{
FormatEntry feChild = obj as FormatEntry;
if (feChild != null)
{
if (currentDepth < maxRecursionDepth)
{
if (feChild.frameInfo != null)
{
// if we have frame information, we need to push it on the
// indentation stack
using (_indentationManager.StackFrame(feChild.frameInfo))
{
GenerateFormatEntryDisplay(feChild, currentDepth + 1);
}
}
else
{
// no need here of activating an indentation stack frame
GenerateFormatEntryDisplay(feChild, currentDepth + 1);
}
}
continue;
}
if (obj is FormatNewLine)
{
this.WriteToScreen();
continue;
}
FormatTextField ftf = obj as FormatTextField;
if (ftf != null)
{
this.AddToBuffer(ftf.text);
continue;
}
FormatPropertyField fpf = obj as FormatPropertyField;
if (fpf != null)
{
this.AddToBuffer(fpf.propertyValue);
}
}
}
/// <summary>
/// Add a string to the current buffer, waiting for a FlushBuffer()
/// </summary>
/// <param name="s">String to add to buffer.</param>
private void AddToBuffer(string s)
{
_stringBuffer.Append(s);
}
/// <summary>
/// Write to the output interface.
/// </summary>
private void WriteToScreen()
{
int leftIndentation = _indentationManager.LeftIndentation;
int rightIndentation = _indentationManager.RightIndentation;
int firstLineIndentation = _indentationManager.FirstLineIndentation;
// VALIDITY CHECKS:
// check the useful ("active") width
int usefulWidth = _textColumns - rightIndentation - leftIndentation;
if (usefulWidth <= 0)
{
// fatal error, there is nothing to write to the device
// just clear the buffer and return
_stringBuffer = new StringBuilder();
}
// check indentation or hanging is not larger than the active width
int indentationAbsoluteValue = (firstLineIndentation > 0) ? firstLineIndentation : -firstLineIndentation;
if (indentationAbsoluteValue >= usefulWidth)
{
// valu too big, we reset it to zero
firstLineIndentation = 0;
}
// compute the first line indentation or hanging
int firstLineWidth = _textColumns - rightIndentation - leftIndentation;
int followingLinesWidth = firstLineWidth;
if (firstLineIndentation >= 0)
{
// the first line has an indentation
firstLineWidth -= firstLineIndentation;
}
else
{
// the first line is hanging
followingLinesWidth += firstLineIndentation;
}
// error checking on invalid values
// generate the lines using the computed widths
StringCollection sc = StringManipulationHelper.GenerateLines(_lo.DisplayCells, _stringBuffer.ToString(),
firstLineWidth, followingLinesWidth);
// compute padding
int firstLinePadding = leftIndentation;
int followingLinesPadding = leftIndentation;
if (firstLineIndentation >= 0)
{
// the first line has an indentation
firstLinePadding += firstLineIndentation;
}
else
{
// the first line is hanging
followingLinesPadding -= firstLineIndentation;
}
// now write the lines on the screen
bool firstLine = true;
foreach (string s in sc)
{
if (firstLine)
{
firstLine = false;
_lo.WriteLine(StringManipulationHelper.PadLeft(s, firstLinePadding));
}
else
{
_lo.WriteLine(StringManipulationHelper.PadLeft(s, followingLinesPadding));
}
}
_stringBuffer = new StringBuilder();
}
/// <summary>
/// Helper object to manage the frame-based indentation and margins.
/// </summary>
private IndentationManager _indentationManager = new IndentationManager();
/// <summary>
/// Buffer to accumulate partially constructed text.
/// </summary>
private StringBuilder _stringBuffer = new StringBuilder();
/// <summary>
/// Interface to write to.
/// </summary>
private LineOutput _lo;
/// <summary>
/// Number of columns for the output device.
/// </summary>
private int _textColumns;
private const int maxRecursionDepth = 50;
}
internal sealed class IndentationManager
{
private sealed class IndentationStackFrame : IDisposable
{
internal IndentationStackFrame(IndentationManager mgr)
{
_mgr = mgr;
}
public void Dispose()
{
if (_mgr != null)
{
_mgr.RemoveStackFrame();
}
}
private IndentationManager _mgr;
}
internal void Clear()
{
_frameInfoStack.Clear();
}
internal IDisposable StackFrame(FrameInfo frameInfo)
{
IndentationStackFrame frame = new IndentationStackFrame(this);
_frameInfoStack.Push(frameInfo);
return frame;
}
private void RemoveStackFrame()
{
_frameInfoStack.Pop();
}
internal int RightIndentation
{
get
{
return ComputeRightIndentation();
}
}
internal int LeftIndentation
{
get
{
return ComputeLeftIndentation();
}
}
internal int FirstLineIndentation
{
get
{
if (_frameInfoStack.Count == 0)
return 0;
return _frameInfoStack.Peek().firstLine;
}
}
private int ComputeRightIndentation()
{
int val = 0;
foreach (FrameInfo fi in _frameInfoStack)
{
val += fi.rightIndentation;
}
return val;
}
private int ComputeLeftIndentation()
{
int val = 0;
foreach (FrameInfo fi in _frameInfoStack)
{
val += fi.leftIndentation;
}
return val;
}
private Stack<FrameInfo> _frameInfoStack = new Stack<FrameInfo>();
}
/// <summary>
/// Result of GetWords.
/// </summary>
internal struct GetWordsResult
{
internal string Word;
internal string Delim;
}
/// <summary>
/// Collection of helper functions for string formatting.
/// </summary>
internal sealed class StringManipulationHelper
{
private static readonly char s_softHyphen = '\u00AD';
private static readonly char s_hardHyphen = '\u2011';
private static readonly char s_nonBreakingSpace = '\u00A0';
private static Collection<string> s_cultureCollection = new Collection<string>();
static StringManipulationHelper()
{
s_cultureCollection.Add("en"); // English
s_cultureCollection.Add("fr"); // French
s_cultureCollection.Add("de"); // German
s_cultureCollection.Add("it"); // Italian
s_cultureCollection.Add("pt"); // Portuguese
s_cultureCollection.Add("es"); // Spanish
}
/// <summary>
/// Breaks a string into a collection of words
/// TODO: we might be able to improve this function in the future
/// so that we do not break paths etc.
/// </summary>
/// <param name="s">Input string.</param>
/// <returns>A collection of words.</returns>
private static IEnumerable<GetWordsResult> GetWords(string s)
{
StringBuilder sb = new StringBuilder();
GetWordsResult result = new GetWordsResult();
for (int i = 0; i < s.Length; i++)
{
// Soft hyphen = \u00AD - Should break, and add a hyphen if needed. If not needed for a break, hyphen should be absent
if (s[i] == ' ' || s[i] == '\t' || s[i] == s_softHyphen)
{
result.Word = sb.ToString();
sb.Clear();
result.Delim = new String(s[i], 1);
yield return result;
}
// Non-breaking space = \u00A0 - ideally shouldn't wrap
// Hard hyphen = \u2011 - Should not break
else if (s[i] == s_hardHyphen || s[i] == s_nonBreakingSpace)
{
result.Word = sb.ToString();
sb.Clear();
result.Delim = string.Empty;
yield return result;
}
else
{
sb.Append(s[i]);
}
}
result.Word = sb.ToString();
result.Delim = string.Empty;
yield return result;
}
internal static StringCollection GenerateLines(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen)
{
if (s_cultureCollection.Contains(CultureInfo.CurrentCulture.TwoLetterISOLanguageName))
{
return GenerateLinesWithWordWrap(displayCells, val, firstLineLen, followingLinesLen);
}
else
{
return GenerateLinesWithoutWordWrap(displayCells, val, firstLineLen, followingLinesLen);
}
}
private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen)
{
StringCollection retVal = new StringCollection();
if (string.IsNullOrEmpty(val))
{
// if null or empty, just add and we are done
retVal.Add(val);
return retVal;
}
// break string on newlines and process each line separately
string[] lines = SplitLines(val);
for (int k = 0; k < lines.Length; k++)
{
if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen)
{
// we do not need to split further, just add
retVal.Add(lines[k]);
continue;
}
// the string does not fit, so we have to wrap around on multiple lines
// for each of these lines in the string, the first line will have
// a (potentially) different length (indentation or hanging)
// for each line, start a new state
SplitLinesAccumulator accumulator = new SplitLinesAccumulator(retVal, firstLineLen, followingLinesLen);
int offset = 0; // offset into the line we are splitting
while (true)
{
// acquire the current active display line length (it can very from call to call)
int currentDisplayLen = accumulator.ActiveLen;
// determine if the current tail would fit or not
// for the remaining part of the string, determine its display cell count
int currentCellsToFit = displayCells.Length(lines[k], offset);
// determine if we fit into the line
int excessCells = currentCellsToFit - currentDisplayLen;
if (excessCells > 0)
{
// we are not at the end of the string, select a sub string
// that would fit in the remaining display length
int charactersToAdd = displayCells.GetHeadSplitLength(lines[k], offset, currentDisplayLen);
if (charactersToAdd <= 0)
{
// corner case: we have a two cell character and the current
// display length is one.
// add a single cell arbitrary character instead of the original
// one and keep going
charactersToAdd = 1;
accumulator.AddLine("?");
}
else
{
// of the given length, add it to the accumulator
accumulator.AddLine(lines[k].Substring(offset, charactersToAdd));
}
// increase the offset by the # of characters added
offset += charactersToAdd;
}
else
{
// we reached the last (partial) line, we add it all
accumulator.AddLine(lines[k].Substring(offset));
break;
}
}
}
return retVal;
}
private sealed class SplitLinesAccumulator
{
internal SplitLinesAccumulator(StringCollection retVal, int firstLineLen, int followingLinesLen)
{
_retVal = retVal;
_firstLineLen = firstLineLen;
_followingLinesLen = followingLinesLen;
}
internal void AddLine(string s)
{
if (!_addedFirstLine)
{
_addedFirstLine = true;
}
_retVal.Add(s);
}
internal int ActiveLen
{
get
{
if (_addedFirstLine)
return _followingLinesLen;
return _firstLineLen;
}
}
private StringCollection _retVal;
private bool _addedFirstLine;
private int _firstLineLen;
private int _followingLinesLen;
}
private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen)
{
StringCollection retVal = new StringCollection();
if (string.IsNullOrEmpty(val))
{
// if null or empty, just add and we are done
retVal.Add(val);
return retVal;
}
// break string on newlines and process each line separately
string[] lines = SplitLines(val);
for (int k = 0; k < lines.Length; k++)
{
if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen)
{
// we do not need to split further, just add
retVal.Add(lines[k]);
continue;
}
int spacesLeft = firstLineLen;
int lineWidth = firstLineLen;
bool firstLine = true;
StringBuilder singleLine = new StringBuilder();
foreach (GetWordsResult word in GetWords(lines[k]))
{
string wordToAdd = word.Word;
// Handle soft hyphen
if (word.Delim == s_softHyphen.ToString())
{
int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(s_softHyphen.ToString());
// Add hyphen only if necessary
if (wordWidthWithHyphen == spacesLeft)
{
wordToAdd += "-";
}
}
else
{
if (!string.IsNullOrEmpty(word.Delim))
{
wordToAdd += word.Delim;
}
}
int wordWidth = displayCells.Length(wordToAdd);
// Handle zero width
if (lineWidth == 0)
{
if (firstLine)
{
firstLine = false;
lineWidth = followingLinesLen;
}
if (lineWidth == 0)
{
break;
}
spacesLeft = lineWidth;
}
// Word is wider than a single line
if (wordWidth > lineWidth)
{
foreach (char c in wordToAdd)
{
char charToAdd = c;
int charWidth = displayCells.Length(c);
// corner case: we have a two cell character and the current
// display length is one.
// add a single cell arbitrary character instead of the original
// one and keep going
if (charWidth > lineWidth)
{
charToAdd = '?';
charWidth = 1;
}
if (charWidth > spacesLeft)
{
retVal.Add(singleLine.ToString());
singleLine.Clear();
singleLine.Append(charToAdd);
if (firstLine)
{
firstLine = false;
lineWidth = followingLinesLen;
}
spacesLeft = lineWidth - charWidth;
}
else
{
singleLine.Append(charToAdd);
spacesLeft -= charWidth;
}
}
}
else
{
if (wordWidth > spacesLeft)
{
retVal.Add(singleLine.ToString());
singleLine.Clear();
singleLine.Append(wordToAdd);
if (firstLine)
{
firstLine = false;
lineWidth = followingLinesLen;
}
spacesLeft = lineWidth - wordWidth;
}
else
{
singleLine.Append(wordToAdd);
spacesLeft -= wordWidth;
}
}
}
retVal.Add(singleLine.ToString());
}
return retVal;
}
/// <summary>
/// Split a multiline string into an array of strings
/// by honoring both \n and \r\n.
/// </summary>
/// <param name="s">String to split.</param>
/// <returns>String array with the values.</returns>
internal static string[] SplitLines(string s)
{
if (string.IsNullOrEmpty(s))
return new string[1] { s };
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
if (c != '\r')
sb.Append(c);
}
return sb.ToString().Split(s_newLineChar);
}
#if false
internal static string StripNewLines (string s)
{
if (string.IsNullOrEmpty (s))
return s;
string[] lines = SplitLines (s);
if (lines.Length == 0)
return null;
if (lines.Length == 1)
return lines[0];
StringBuilder sb = new StringBuilder ();
for (int k = 0; k < lines.Length; k++)
{
if (k == 0)
sb.Append (lines[k]);
else
sb.Append (" " + lines[k]);
}
return sb.ToString ();
}
#endif
internal static string TruncateAtNewLine(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
int lineBreak = s.IndexOfAny(s_lineBreakChars);
if (lineBreak < 0)
{
return s;
}
return s.Substring(0, lineBreak) + PSObjectHelper.Ellipsis;
}
internal static string PadLeft(string val, int count)
{
return StringUtil.Padding(count) + val;
}
private static readonly char[] s_newLineChar = new char[] { '\n' };
private static readonly char[] s_lineBreakChars = new char[] { '\n', '\r' };
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SchoolBusAPI.Models;
namespace SchoolBusAPI.ViewModels
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class PermitViewModel : IEquatable<PermitViewModel>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public PermitViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PermitViewModel" /> class.
/// </summary>
/// <param name="PermitNumber">PermitNumber.</param>
/// <param name="PermitIssueDate">PermitIssueDate.</param>
/// <param name="SchoolBusOwnerName">SchoolBusOwnerName.</param>
/// <param name="SchoolBusOwnerAddressLine1">SchoolBusOwnerAddressLine1.</param>
/// <param name="SchoolBusOwnerAddressLine2">SchoolBusOwnerAddressLine2.</param>
/// <param name="SchoolBusMobilityAidCapacity">SchoolBusMobilityAidCapacity.</param>
/// <param name="SchoolBusOwnerCity">SchoolBusOwnerCity.</param>
/// <param name="SchoolBusOwnerProvince">SchoolBusOwnerProvince.</param>
/// <param name="SchoolBusOwnerPostalCode">SchoolBusOwnerPostalCode.</param>
/// <param name="IcbcRegistrationNumber">IcbcRegistrationNumber.</param>
/// <param name="VehicleIdentificationNumber">VehicleIdentificationNumber.</param>
/// <param name="IcbcModelYear">IcbcModelYear.</param>
/// <param name="IcbcMake">IcbcMake.</param>
/// <param name="RestrictionsText">RestrictionsText.</param>
/// <param name="SchoolDistrictshortName">SchoolDistrictshortName.</param>
/// <param name="SchoolBusSeatingCapacity">SchoolBusSeatingCapacity.</param>
/// <param name="UnitNumber">The unit number of the Bus as defined by the School Bus owner - freeform text..</param>
/// <param name="PermitClassCode">The enumerated class of School Bus from drop down.</param>
/// <param name="BodyTypeCode">The enumerated body type of the School Bus from drop down.</param>
public PermitViewModel(int? PermitNumber = null, string PermitIssueDate = null, string SchoolBusOwnerName = null, string SchoolBusOwnerAddressLine1 = null, string SchoolBusOwnerAddressLine2 = null, string SchoolBusMobilityAidCapacity = null, string SchoolBusOwnerCity = null, string SchoolBusOwnerProvince = null, string SchoolBusOwnerPostalCode = null, string IcbcRegistrationNumber = null, string VehicleIdentificationNumber = null, int? IcbcModelYear = null, string IcbcMake = null, string RestrictionsText = null, string SchoolDistrictshortName = null, int? SchoolBusSeatingCapacity = null, string UnitNumber = null, string PermitClassCode = null, string BodyTypeCode = null)
{ this.PermitNumber = PermitNumber;
this.PermitIssueDate = PermitIssueDate;
this.SchoolBusOwnerName = SchoolBusOwnerName;
this.SchoolBusOwnerAddressLine1 = SchoolBusOwnerAddressLine1;
this.SchoolBusOwnerAddressLine2 = SchoolBusOwnerAddressLine2;
this.SchoolBusMobilityAidCapacity = SchoolBusMobilityAidCapacity;
this.SchoolBusOwnerCity = SchoolBusOwnerCity;
this.SchoolBusOwnerProvince = SchoolBusOwnerProvince;
this.SchoolBusOwnerPostalCode = SchoolBusOwnerPostalCode;
this.IcbcRegistrationNumber = IcbcRegistrationNumber;
this.VehicleIdentificationNumber = VehicleIdentificationNumber;
this.IcbcModelYear = IcbcModelYear;
this.IcbcMake = IcbcMake;
this.RestrictionsText = RestrictionsText;
this.SchoolDistrictshortName = SchoolDistrictshortName;
this.SchoolBusSeatingCapacity = SchoolBusSeatingCapacity;
this.UnitNumber = UnitNumber;
this.PermitClassCode = PermitClassCode;
this.BodyTypeCode = BodyTypeCode;
}
/// <summary>
/// Gets or Sets PermitNumber
/// </summary>
[DataMember(Name="permitNumber")]
public int? PermitNumber { get; set; }
/// <summary>
/// Gets or Sets PermitIssueDate
/// </summary>
[DataMember(Name="permitIssueDate")]
public string PermitIssueDate { get; set; }
/// <summary>
/// Gets or Sets SchoolBusOwnerName
/// </summary>
[DataMember(Name="schoolBusOwnerName")]
public string SchoolBusOwnerName { get; set; }
/// <summary>
/// Gets or Sets SchoolBusOwnerAddressLine1
/// </summary>
[DataMember(Name="schoolBusOwnerAddressLine1")]
public string SchoolBusOwnerAddressLine1 { get; set; }
/// <summary>
/// Gets or Sets SchoolBusOwnerAddressLine2
/// </summary>
[DataMember(Name="schoolBusOwnerAddressLine2")]
public string SchoolBusOwnerAddressLine2 { get; set; }
/// <summary>
/// Gets or Sets SchoolBusMobilityAidCapacity
/// </summary>
[DataMember(Name="schoolBusMobilityAidCapacity")]
public string SchoolBusMobilityAidCapacity { get; set; }
/// <summary>
/// Gets or Sets SchoolBusOwnerCity
/// </summary>
[DataMember(Name="schoolBusOwnerCity")]
public string SchoolBusOwnerCity { get; set; }
/// <summary>
/// Gets or Sets SchoolBusOwnerProvince
/// </summary>
[DataMember(Name="schoolBusOwnerProvince")]
public string SchoolBusOwnerProvince { get; set; }
/// <summary>
/// Gets or Sets SchoolBusOwnerPostalCode
/// </summary>
[DataMember(Name="schoolBusOwnerPostalCode")]
public string SchoolBusOwnerPostalCode { get; set; }
/// <summary>
/// Gets or Sets IcbcRegistrationNumber
/// </summary>
[DataMember(Name="icbcRegistrationNumber")]
public string IcbcRegistrationNumber { get; set; }
/// <summary>
/// Gets or Sets VehicleIdentificationNumber
/// </summary>
[DataMember(Name="vehicleIdentificationNumber")]
public string VehicleIdentificationNumber { get; set; }
/// <summary>
/// Gets or Sets IcbcModelYear
/// </summary>
[DataMember(Name="icbcModelYear")]
public int? IcbcModelYear { get; set; }
/// <summary>
/// Gets or Sets IcbcMake
/// </summary>
[DataMember(Name="icbcMake")]
public string IcbcMake { get; set; }
/// <summary>
/// Gets or Sets RestrictionsText
/// </summary>
[DataMember(Name="restrictionsText")]
public string RestrictionsText { get; set; }
/// <summary>
/// Gets or Sets SchoolDistrictshortName
/// </summary>
[DataMember(Name="schoolDistrictshortName")]
public string SchoolDistrictshortName { get; set; }
/// <summary>
/// Gets or Sets SchoolBusSeatingCapacity
/// </summary>
[DataMember(Name="schoolBusSeatingCapacity")]
public int? SchoolBusSeatingCapacity { get; set; }
/// <summary>
/// The unit number of the Bus as defined by the School Bus owner - freeform text.
/// </summary>
/// <value>The unit number of the Bus as defined by the School Bus owner - freeform text.</value>
[DataMember(Name="unitNumber")]
[MetaDataExtension (Description = "The unit number of the Bus as defined by the School Bus owner - freeform text.")]
public string UnitNumber { get; set; }
/// <summary>
/// The enumerated class of School Bus from drop down
/// </summary>
/// <value>The enumerated class of School Bus from drop down</value>
[DataMember(Name="permitClassCode")]
[MetaDataExtension (Description = "The enumerated class of School Bus from drop down")]
public string PermitClassCode { get; set; }
/// <summary>
/// The enumerated body type of the School Bus from drop down
/// </summary>
/// <value>The enumerated body type of the School Bus from drop down</value>
[DataMember(Name="bodyTypeCode")]
[MetaDataExtension (Description = "The enumerated body type of the School Bus from drop down")]
public string BodyTypeCode { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PermitViewModel {\n");
sb.Append(" PermitNumber: ").Append(PermitNumber).Append("\n");
sb.Append(" PermitIssueDate: ").Append(PermitIssueDate).Append("\n");
sb.Append(" SchoolBusOwnerName: ").Append(SchoolBusOwnerName).Append("\n");
sb.Append(" SchoolBusOwnerAddressLine1: ").Append(SchoolBusOwnerAddressLine1).Append("\n");
sb.Append(" SchoolBusOwnerAddressLine2: ").Append(SchoolBusOwnerAddressLine2).Append("\n");
sb.Append(" SchoolBusMobilityAidCapacity: ").Append(SchoolBusMobilityAidCapacity).Append("\n");
sb.Append(" SchoolBusOwnerCity: ").Append(SchoolBusOwnerCity).Append("\n");
sb.Append(" SchoolBusOwnerProvince: ").Append(SchoolBusOwnerProvince).Append("\n");
sb.Append(" SchoolBusOwnerPostalCode: ").Append(SchoolBusOwnerPostalCode).Append("\n");
sb.Append(" IcbcRegistrationNumber: ").Append(IcbcRegistrationNumber).Append("\n");
sb.Append(" VehicleIdentificationNumber: ").Append(VehicleIdentificationNumber).Append("\n");
sb.Append(" IcbcModelYear: ").Append(IcbcModelYear).Append("\n");
sb.Append(" IcbcMake: ").Append(IcbcMake).Append("\n");
sb.Append(" RestrictionsText: ").Append(RestrictionsText).Append("\n");
sb.Append(" SchoolDistrictshortName: ").Append(SchoolDistrictshortName).Append("\n");
sb.Append(" SchoolBusSeatingCapacity: ").Append(SchoolBusSeatingCapacity).Append("\n");
sb.Append(" UnitNumber: ").Append(UnitNumber).Append("\n");
sb.Append(" PermitClassCode: ").Append(PermitClassCode).Append("\n");
sb.Append(" BodyTypeCode: ").Append(BodyTypeCode).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((PermitViewModel)obj);
}
/// <summary>
/// Returns true if PermitViewModel instances are equal
/// </summary>
/// <param name="other">Instance of PermitViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PermitViewModel other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.PermitNumber == other.PermitNumber ||
this.PermitNumber != null &&
this.PermitNumber.Equals(other.PermitNumber)
) &&
(
this.PermitIssueDate == other.PermitIssueDate ||
this.PermitIssueDate != null &&
this.PermitIssueDate.Equals(other.PermitIssueDate)
) &&
(
this.SchoolBusOwnerName == other.SchoolBusOwnerName ||
this.SchoolBusOwnerName != null &&
this.SchoolBusOwnerName.Equals(other.SchoolBusOwnerName)
) &&
(
this.SchoolBusOwnerAddressLine1 == other.SchoolBusOwnerAddressLine1 ||
this.SchoolBusOwnerAddressLine1 != null &&
this.SchoolBusOwnerAddressLine1.Equals(other.SchoolBusOwnerAddressLine1)
) &&
(
this.SchoolBusOwnerAddressLine2 == other.SchoolBusOwnerAddressLine2 ||
this.SchoolBusOwnerAddressLine2 != null &&
this.SchoolBusOwnerAddressLine2.Equals(other.SchoolBusOwnerAddressLine2)
) &&
(
this.SchoolBusMobilityAidCapacity == other.SchoolBusMobilityAidCapacity ||
this.SchoolBusMobilityAidCapacity != null &&
this.SchoolBusMobilityAidCapacity.Equals(other.SchoolBusMobilityAidCapacity)
) &&
(
this.SchoolBusOwnerCity == other.SchoolBusOwnerCity ||
this.SchoolBusOwnerCity != null &&
this.SchoolBusOwnerCity.Equals(other.SchoolBusOwnerCity)
) &&
(
this.SchoolBusOwnerProvince == other.SchoolBusOwnerProvince ||
this.SchoolBusOwnerProvince != null &&
this.SchoolBusOwnerProvince.Equals(other.SchoolBusOwnerProvince)
) &&
(
this.SchoolBusOwnerPostalCode == other.SchoolBusOwnerPostalCode ||
this.SchoolBusOwnerPostalCode != null &&
this.SchoolBusOwnerPostalCode.Equals(other.SchoolBusOwnerPostalCode)
) &&
(
this.IcbcRegistrationNumber == other.IcbcRegistrationNumber ||
this.IcbcRegistrationNumber != null &&
this.IcbcRegistrationNumber.Equals(other.IcbcRegistrationNumber)
) &&
(
this.VehicleIdentificationNumber == other.VehicleIdentificationNumber ||
this.VehicleIdentificationNumber != null &&
this.VehicleIdentificationNumber.Equals(other.VehicleIdentificationNumber)
) &&
(
this.IcbcModelYear == other.IcbcModelYear ||
this.IcbcModelYear != null &&
this.IcbcModelYear.Equals(other.IcbcModelYear)
) &&
(
this.IcbcMake == other.IcbcMake ||
this.IcbcMake != null &&
this.IcbcMake.Equals(other.IcbcMake)
) &&
(
this.RestrictionsText == other.RestrictionsText ||
this.RestrictionsText != null &&
this.RestrictionsText.Equals(other.RestrictionsText)
) &&
(
this.SchoolDistrictshortName == other.SchoolDistrictshortName ||
this.SchoolDistrictshortName != null &&
this.SchoolDistrictshortName.Equals(other.SchoolDistrictshortName)
) &&
(
this.SchoolBusSeatingCapacity == other.SchoolBusSeatingCapacity ||
this.SchoolBusSeatingCapacity != null &&
this.SchoolBusSeatingCapacity.Equals(other.SchoolBusSeatingCapacity)
) &&
(
this.UnitNumber == other.UnitNumber ||
this.UnitNumber != null &&
this.UnitNumber.Equals(other.UnitNumber)
) &&
(
this.PermitClassCode == other.PermitClassCode ||
this.PermitClassCode != null &&
this.PermitClassCode.Equals(other.PermitClassCode)
) &&
(
this.BodyTypeCode == other.BodyTypeCode ||
this.BodyTypeCode != null &&
this.BodyTypeCode.Equals(other.BodyTypeCode)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
if (this.PermitNumber != null)
{
hash = hash * 59 + this.PermitNumber.GetHashCode();
}
if (this.PermitIssueDate != null)
{
hash = hash * 59 + this.PermitIssueDate.GetHashCode();
}
if (this.SchoolBusOwnerName != null)
{
hash = hash * 59 + this.SchoolBusOwnerName.GetHashCode();
}
if (this.SchoolBusOwnerAddressLine1 != null)
{
hash = hash * 59 + this.SchoolBusOwnerAddressLine1.GetHashCode();
}
if (this.SchoolBusOwnerAddressLine2 != null)
{
hash = hash * 59 + this.SchoolBusOwnerAddressLine2.GetHashCode();
}
if (this.SchoolBusMobilityAidCapacity != null)
{
hash = hash * 59 + this.SchoolBusMobilityAidCapacity.GetHashCode();
}
if (this.SchoolBusOwnerCity != null)
{
hash = hash * 59 + this.SchoolBusOwnerCity.GetHashCode();
}
if (this.SchoolBusOwnerProvince != null)
{
hash = hash * 59 + this.SchoolBusOwnerProvince.GetHashCode();
}
if (this.SchoolBusOwnerPostalCode != null)
{
hash = hash * 59 + this.SchoolBusOwnerPostalCode.GetHashCode();
}
if (this.IcbcRegistrationNumber != null)
{
hash = hash * 59 + this.IcbcRegistrationNumber.GetHashCode();
}
if (this.VehicleIdentificationNumber != null)
{
hash = hash * 59 + this.VehicleIdentificationNumber.GetHashCode();
}
if (this.IcbcModelYear != null)
{
hash = hash * 59 + this.IcbcModelYear.GetHashCode();
}
if (this.IcbcMake != null)
{
hash = hash * 59 + this.IcbcMake.GetHashCode();
}
if (this.RestrictionsText != null)
{
hash = hash * 59 + this.RestrictionsText.GetHashCode();
}
if (this.SchoolDistrictshortName != null)
{
hash = hash * 59 + this.SchoolDistrictshortName.GetHashCode();
}
if (this.SchoolBusSeatingCapacity != null)
{
hash = hash * 59 + this.SchoolBusSeatingCapacity.GetHashCode();
}
if (this.UnitNumber != null)
{
hash = hash * 59 + this.UnitNumber.GetHashCode();
}
if (this.PermitClassCode != null)
{
hash = hash * 59 + this.PermitClassCode.GetHashCode();
}
if (this.BodyTypeCode != null)
{
hash = hash * 59 + this.BodyTypeCode.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(PermitViewModel left, PermitViewModel right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(PermitViewModel left, PermitViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Transport Modes Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class TRPMODEDataSet : EduHubDataSet<TRPMODE>
{
/// <inheritdoc />
public override string Name { get { return "TRPMODE"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal TRPMODEDataSet(EduHubContext Context)
: base(Context)
{
Index_TRANSPORT_MODE_ID = new Lazy<Dictionary<int, TRPMODE>>(() => this.ToDictionary(i => i.TRANSPORT_MODE_ID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="TRPMODE" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="TRPMODE" /> fields for each CSV column header</returns>
internal override Action<TRPMODE, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<TRPMODE, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TRANSPORT_MODE_ID":
mapper[i] = (e, v) => e.TRANSPORT_MODE_ID = int.Parse(v);
break;
case "TRANSPORT_MODE_DESC":
mapper[i] = (e, v) => e.TRANSPORT_MODE_DESC = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="TRPMODE" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="TRPMODE" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="TRPMODE" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{TRPMODE}"/> of entities</returns>
internal override IEnumerable<TRPMODE> ApplyDeltaEntities(IEnumerable<TRPMODE> Entities, List<TRPMODE> DeltaEntities)
{
HashSet<int> Index_TRANSPORT_MODE_ID = new HashSet<int>(DeltaEntities.Select(i => i.TRANSPORT_MODE_ID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TRANSPORT_MODE_ID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TRANSPORT_MODE_ID.Remove(entity.TRANSPORT_MODE_ID);
if (entity.TRANSPORT_MODE_ID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, TRPMODE>> Index_TRANSPORT_MODE_ID;
#endregion
#region Index Methods
/// <summary>
/// Find TRPMODE by TRANSPORT_MODE_ID field
/// </summary>
/// <param name="TRANSPORT_MODE_ID">TRANSPORT_MODE_ID value used to find TRPMODE</param>
/// <returns>Related TRPMODE entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public TRPMODE FindByTRANSPORT_MODE_ID(int TRANSPORT_MODE_ID)
{
return Index_TRANSPORT_MODE_ID.Value[TRANSPORT_MODE_ID];
}
/// <summary>
/// Attempt to find TRPMODE by TRANSPORT_MODE_ID field
/// </summary>
/// <param name="TRANSPORT_MODE_ID">TRANSPORT_MODE_ID value used to find TRPMODE</param>
/// <param name="Value">Related TRPMODE entity</param>
/// <returns>True if the related TRPMODE entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTRANSPORT_MODE_ID(int TRANSPORT_MODE_ID, out TRPMODE Value)
{
return Index_TRANSPORT_MODE_ID.Value.TryGetValue(TRANSPORT_MODE_ID, out Value);
}
/// <summary>
/// Attempt to find TRPMODE by TRANSPORT_MODE_ID field
/// </summary>
/// <param name="TRANSPORT_MODE_ID">TRANSPORT_MODE_ID value used to find TRPMODE</param>
/// <returns>Related TRPMODE entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public TRPMODE TryFindByTRANSPORT_MODE_ID(int TRANSPORT_MODE_ID)
{
TRPMODE value;
if (Index_TRANSPORT_MODE_ID.Value.TryGetValue(TRANSPORT_MODE_ID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a TRPMODE table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TRPMODE]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[TRPMODE](
[TRANSPORT_MODE_ID] int IDENTITY NOT NULL,
[TRANSPORT_MODE_DESC] varchar(60) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [TRPMODE_Index_TRANSPORT_MODE_ID] PRIMARY KEY CLUSTERED (
[TRANSPORT_MODE_ID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="TRPMODEDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="TRPMODEDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="TRPMODE"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="TRPMODE"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<TRPMODE> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TRANSPORT_MODE_ID = new List<int>();
foreach (var entity in Entities)
{
Index_TRANSPORT_MODE_ID.Add(entity.TRANSPORT_MODE_ID);
}
builder.AppendLine("DELETE [dbo].[TRPMODE] WHERE");
// Index_TRANSPORT_MODE_ID
builder.Append("[TRANSPORT_MODE_ID] IN (");
for (int index = 0; index < Index_TRANSPORT_MODE_ID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TRANSPORT_MODE_ID
var parameterTRANSPORT_MODE_ID = $"@p{parameterIndex++}";
builder.Append(parameterTRANSPORT_MODE_ID);
command.Parameters.Add(parameterTRANSPORT_MODE_ID, SqlDbType.Int).Value = Index_TRANSPORT_MODE_ID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the TRPMODE data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the TRPMODE data set</returns>
public override EduHubDataSetDataReader<TRPMODE> GetDataSetDataReader()
{
return new TRPMODEDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the TRPMODE data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the TRPMODE data set</returns>
public override EduHubDataSetDataReader<TRPMODE> GetDataSetDataReader(List<TRPMODE> Entities)
{
return new TRPMODEDataReader(new EduHubDataSetLoadedReader<TRPMODE>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class TRPMODEDataReader : EduHubDataSetDataReader<TRPMODE>
{
public TRPMODEDataReader(IEduHubDataSetReader<TRPMODE> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 5; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TRANSPORT_MODE_ID
return Current.TRANSPORT_MODE_ID;
case 1: // TRANSPORT_MODE_DESC
return Current.TRANSPORT_MODE_DESC;
case 2: // LW_DATE
return Current.LW_DATE;
case 3: // LW_TIME
return Current.LW_TIME;
case 4: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // TRANSPORT_MODE_DESC
return Current.TRANSPORT_MODE_DESC == null;
case 2: // LW_DATE
return Current.LW_DATE == null;
case 3: // LW_TIME
return Current.LW_TIME == null;
case 4: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TRANSPORT_MODE_ID
return "TRANSPORT_MODE_ID";
case 1: // TRANSPORT_MODE_DESC
return "TRANSPORT_MODE_DESC";
case 2: // LW_DATE
return "LW_DATE";
case 3: // LW_TIME
return "LW_TIME";
case 4: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TRANSPORT_MODE_ID":
return 0;
case "TRANSPORT_MODE_DESC":
return 1;
case "LW_DATE":
return 2;
case "LW_TIME":
return 3;
case "LW_USER":
return 4;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
#region [ license and copyright boilerplate ]
/*
MiscCorLib
FormatString.cs
Copyright (c) 2016 Jim Kropa (https://github.com/jimkropa)
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
namespace MiscCorLib
{
using System;
using System.Text.RegularExpressions;
/// <summary>
/// A set of static methods for manipulating strings.
/// </summary>
[CLSCompliant(true)]
public static class FormatString
{
#region [ Private String Constants for Character Escape Sequences ]
/// <summary>
/// An escape sequence representing a carriage return.
/// </summary>
public const string Cr = "\r";
/// <summary>
/// An escape sequence representing a line break.
/// </summary>
public const string Lf = "\n";
/// <summary>
/// An escape sequence representing a
/// carriage return followed by a line break.
/// </summary>
public const string CrLf = "\r\n";
/// <summary>
/// An escape sequence representing two carriage returns.
/// </summary>
public const string DoubleCr = "\r\r";
/// <summary>
/// An escape sequence representing two line breaks.
/// </summary>
public const string DoubleLf = "\n\n";
/// <summary>
/// An escape sequence representing a
/// carriage return followed by a line break,
/// followed by another carriage return
/// and another line break.
/// </summary>
public const string DoubleCrLf = "\r\n\r\n";
/// <summary>
/// A concatenation of two <see cref="Environment.NewLine"/> strings.
/// </summary>
public static readonly string DoubleNewLine = Environment.NewLine + Environment.NewLine;
/// <summary>
/// An string with two spaces.
/// </summary>
public const string DoubleSpace = " ";
/// <summary>
/// A string with a single space.
/// </summary>
public const string SingleSpace = " ";
/// <summary>
/// An escape sequence representing a tab character.
/// </summary>
public const string Tab = "\t";
/// <summary>
/// Static allocation of an array for splitting a string using the
/// <see cref="string.Split(string[],StringSplitOptions)"/> method,
/// to avoid the expensive allocation each time it is used by the
/// <see cref="ToCompactWhiteSpace"/> method.
/// </summary>
public static readonly string[] TabSplitter = { Tab };
/// <summary>
/// Static allocation of an array for splitting a string using the
/// <see cref="string.Split(string[],StringSplitOptions)"/> method,
/// to avoid the expensive allocation each time it is used by the
/// <see cref="ToCompactWhiteSpace"/> method.
/// </summary>
public static readonly string[] NewLineSplitter = { Environment.NewLine, CrLf, Cr, Lf };
/// <summary>
/// Static allocation of an array for splitting a string using the
/// <see cref="string.Split(string[],StringSplitOptions)"/> method,
/// to avoid the expensive allocation each time it is used by the
/// <see cref="ToCompactWhiteSpace"/> method.
/// </summary>
public static readonly string[] DoubleSpaceSplitter = { DoubleSpace };
private static readonly string[] ExcessNewLineSplitter = { DoubleNewLine + Environment.NewLine, DoubleCrLf + CrLf, DoubleCr + Cr, DoubleLf + Lf, DoubleNewLine, DoubleCrLf, DoubleCr, DoubleLf };
private static readonly string[] ExcessSpacesSplitter = { " ", " ", " ", DoubleSpace };
private const string HtmlParagraphStart = @"<p>";
private const string HtmlParagraphEnd = @"</p>";
private const string HtmlParagraphDelimiter = @"</p><p>";
private const string HtmlLineDelimiter = @"<br />";
private static readonly string[] HtmlParagraphSplitter = { @" </p><p> ", @" </p><p>", @"</p><p> ", HtmlParagraphDelimiter };
private static readonly string[] HtmlLineSplitter = { @" <br /> ", @" <br />", @"<br /> ", HtmlLineDelimiter };
private static readonly string HtmlParagraphBreak = string.Concat(
Environment.NewLine,
HtmlParagraphEnd,
Environment.NewLine,
HtmlParagraphStart,
Environment.NewLine);
private static readonly string HtmlLineBreak = string.Concat(
Environment.NewLine,
HtmlLineDelimiter,
Environment.NewLine);
#endregion
#region [ Public Static ToEmptyIfNull and ToNullIfEmpty Extension Methods ]
/// <summary>
/// Returns an empty string if the string value is null.
/// </summary>
/// <param name="value">
/// A string which may be a null reference.
/// </param>
/// <returns>
/// The <paramref name="value"/> parameter,
/// or an empty string if the value is null.
/// </returns>
public static string ToEmptyIfNull(this string value)
{
// If the value is null, we're done.
// Otherwise, return the original value.
return string.IsNullOrWhiteSpace(value) ? string.Empty : value.Trim();
}
/// <summary>
/// Returns null if the string value is empty.
/// </summary>
/// <param name="value">
/// A string which may be a null reference.
/// </param>
/// <returns>
/// The <paramref name="value"/> parameter,
/// or null if the value is null or empty.
/// </returns>
public static string ToNullIfEmpty(this string value)
{
// If the value is null, we're done.
// Otherwise, return the original value.
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
#endregion
#region [ Public Static ToCompactWhiteSpace Extension Method ]
/// <summary>
/// Removes all tabs, carriage returns, line breaks from a string of text.
/// </summary>
/// <param name="value">
/// A multiple-line string.
/// </param>
/// <param name="returnNullIfEmptyOrNull">
///
/// </param>
/// <returns>
/// A string based on the <paramref name="value"/> parameter
/// with all of the white space compacted to single spaces.
/// </returns>
public static string ToCompactWhiteSpace(
this string value, bool returnNullIfEmptyOrNull = false)
{
// If the value is null, we're done.
if (string.IsNullOrWhiteSpace(value))
{
return returnNullIfEmptyOrNull ? null : string.Empty;
}
// Create and initialize a value to return.
string singleLine = value.Trim();
// Remove any tabs, line breaks, and extra characters.
singleLine = string.Join(SingleSpace, singleLine.Split(TabSplitter, StringSplitOptions.RemoveEmptyEntries));
singleLine = string.Join(SingleSpace, singleLine.Split(NewLineSplitter, StringSplitOptions.RemoveEmptyEntries));
singleLine = string.Join(SingleSpace, singleLine.Split(ExcessSpacesSplitter, StringSplitOptions.RemoveEmptyEntries));
// Compact any remaining internal spaces.
while (singleLine.IndexOf(DoubleSpace, StringComparison.Ordinal) >= 0)
{
singleLine = string.Join(SingleSpace, singleLine.Split(DoubleSpaceSplitter, StringSplitOptions.RemoveEmptyEntries));
}
// Finally, return the formatted string.
return returnNullIfEmptyOrNull ? singleLine.Trim().ToNullIfEmpty() : singleLine.Trim();
}
#endregion
#region [ Public Static ToHtmlParagraph Extension Method ]
/// <summary>
/// Changes a string of text into HTML markup,
/// replacing double carriage returns with <p> tags
/// and single carriage returns with <br/> tags,
/// and optionally enclosing the whole string within a <p> tag.
/// </summary>
/// <param name="value">
/// A string to convert to HTML markup.
/// </param>
/// <param name="includeContainerElement">
/// Whether to enclose the HTML markup within an outer <p> paragraph element.
/// If setting the InnerHtml property of a server-side <p> element,
/// for instance, send "false" to this parameter.
/// </param>
/// <param name="returnNullIfEmptyOrNull">
///
/// </param>
/// <returns>
/// A string containing the HTML marked-up version
/// of the <paramref name="value"/> parameter.
/// </returns>
public static string ToHtmlParagraph(
this string value, bool includeContainerElement = true, bool returnNullIfEmptyOrNull = false)
{
// If the value is null, we're done.
if (string.IsNullOrWhiteSpace(value))
{
return returnNullIfEmptyOrNull ? null : string.Empty;
}
// Create and initialize a value to return.
string html = value.Trim();
// Replace line breaks with Html tags.
html = string.Join(HtmlParagraphDelimiter, html.Split(ExcessNewLineSplitter, StringSplitOptions.RemoveEmptyEntries));
html = string.Join(HtmlLineBreak, html.Split(NewLineSplitter, StringSplitOptions.RemoveEmptyEntries));
html = html.ToCompactWhiteSpace();
// Insert line breaks between Html tags.
html = string.Join(HtmlParagraphBreak, html.Split(HtmlParagraphSplitter, StringSplitOptions.RemoveEmptyEntries));
html = string.Join(HtmlLineBreak, html.Split(HtmlLineSplitter, StringSplitOptions.RemoveEmptyEntries));
// Check whether an additional <p> tag
// should be included surrounding the string.
if (includeContainerElement && html.Length > 0)
{
html = string.Concat(HtmlParagraphStart, Environment.NewLine, html, Environment.NewLine, HtmlParagraphEnd);
}
// Finally, return the markup string.
return returnNullIfEmptyOrNull ? html.Trim().ToNullIfEmpty() : html.Trim();
}
#endregion
/// <summary>
/// Removes any special characters from the string,
/// leaving only alphanumeric characters.
/// </summary>
/// <param name="value">
/// A <see cref="string"/> that needs to be cleaned up.
/// </param>
/// <param name="returnNullIfEmptyOrNull">
///
/// </param>
/// <returns>
/// A string which contains only alphanumeric characters.
/// </returns>
public static string ToAlphanumeric(this string value, bool returnNullIfEmptyOrNull = false)
{
// Replace invalid characters with empty strings.
return string.IsNullOrWhiteSpace(value) ? returnNullIfEmptyOrNull ? null : string.Empty
: Regex.Replace(value, @"[^\w]", string.Empty).Replace("_", string.Empty);
}
}
}
| |
/* MIT License
Copyright (c) 2016 JetBrains http://www.jetbrains.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */
using System;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace JetBrains.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage.
/// </summary>
/// <example><code>
/// [CanBeNull] object Test() => null;
///
/// void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)]
internal sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>.
/// </summary>
/// <example><code>
/// [NotNull] object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)]
internal sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task
/// and Lazy classes to indicate that the value of a collection item, of the Task.Result property
/// or of the Lazy.Value property can never be null.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
internal sealed class ItemNotNullAttribute : Attribute { }
/// <summary>
/// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task
/// and Lazy classes to indicate that the value of a collection item, of the Task.Result property
/// or of the Lazy.Value property can be null.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
internal sealed class ItemCanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form.
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// void ShowError(string message, params object[] args) { /* do something */ }
///
/// void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Delegate)]
internal sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute([NotNull] string formatParameterName)
{
FormatParameterName = formatParameterName;
}
[NotNull] public string FormatParameterName { get; private set; }
}
/// <summary>
/// For a parameter that is expected to be one of the limited set of values.
/// Specify fields of which type should be used as values for this parameter.
/// </summary>
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field,
AllowMultiple = true)]
internal sealed class ValueProviderAttribute : Attribute
{
public ValueProviderAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>.
/// </summary>
/// <example><code>
/// void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method
/// is used to notify that some property value changed.
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
///
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// string _name;
///
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
internal sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName)
{
ParameterName = parameterName;
}
[CanBeNull] public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output.
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output
/// means that the methos doesn't return normally (throws or terminates the process).<br/>
/// Value <c>canbenull</c> is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute
/// with rows separated by semicolon. There is no notion of order rows, all rows are checked
/// for applicability and applied per each program state tracked by R# analysis.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null,
/// // and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("=> true, result: notnull; => false, result: null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
internal sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
[NotNull] public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not.
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// class Foo {
/// string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All)]
internal sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true) { }
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
///
/// class UsesNoEquality {
/// void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
internal sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// class ComponentAttribute : Attribute { }
///
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[BaseTypeRequired(typeof(Attribute))]
internal sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull] public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections).
/// </summary>
[AttributeUsage(AttributeTargets.All)]
internal sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes
/// as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)]
internal sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
internal enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used.</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member.</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type.</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly when marked
/// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>.
/// </summary>
[Flags]
internal enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used.</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used.</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used.
/// </summary>
[MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)]
internal sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
[CanBeNull] public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack.
/// If the parameter is a delegate, indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>.
/// </summary>
/// <example><code>
/// [Pure] int Multiply(int x, int y) => x * y;
///
/// void M() {
/// Multiply(123, 42); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method)]
internal sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that the return value of method invocation must be used.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
internal sealed class MustUseReturnValueAttribute : Attribute
{
public MustUseReturnValueAttribute() { }
public MustUseReturnValueAttribute([NotNull] string justification)
{
Justification = justification;
}
[CanBeNull] public string Justification { get; private set; }
}
/// <summary>
/// Indicates the type member or parameter of some type, that should be used instead of all other ways
/// to get the value that type. This annotation is useful when you have some "context" value evaluated
/// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one.
/// </summary>
/// <example><code>
/// class Foo {
/// [ProvidesContext] IBarService _barService = ...;
///
/// void ProcessNode(INode node) {
/// DoSomething(node, node.GetGlobalServices().Bar);
/// // ^ Warning: use value of '_barService' field
/// }
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)]
internal sealed class ProvidesContextAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder within a web project.
/// Path can be relative or absolute, starting from web root (~).
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
public PathReferenceAttribute([NotNull, PathReference] string basePath)
{
BasePath = basePath;
}
[CanBeNull] public string BasePath { get; private set; }
}
/// <summary>
/// An extension method marked with this attribute is processed by ReSharper code completion
/// as a 'Source Template'. When extension method is completed over some expression, it's source code
/// is automatically expanded like a template at call site.
/// </summary>
/// <remarks>
/// Template method body can contain valid source code and/or special comments starting with '$'.
/// Text inside these comments is added as source code when the template is applied. Template parameters
/// can be used either as additional method parameters or as identifiers wrapped in two '$' signs.
/// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters.
/// </remarks>
/// <example>
/// In this example, the 'forEach' method is a source template available over all values
/// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block:
/// <code>
/// [SourceTemplate]
/// public static void forEach<T>(this IEnumerable<T> xs) {
/// foreach (var x in xs) {
/// //$ $END$
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
internal sealed class SourceTemplateAttribute : Attribute { }
/// <summary>
/// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>.
/// </summary>
/// <remarks>
/// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression
/// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target
/// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently
/// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1.
/// </remarks>
/// <example>
/// Applying the attribute on a source template method:
/// <code>
/// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")]
/// public static void forEach<T>(this IEnumerable<T> collection) {
/// foreach (var item in collection) {
/// //$ $END$
/// }
/// }
/// </code>
/// Applying the attribute on a template method parameter:
/// <code>
/// [SourceTemplate]
/// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) {
/// /*$ var $x$Id = "$newguid$" + x.ToString();
/// x.DoSomething($x$Id); */
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)]
internal sealed class MacroAttribute : Attribute
{
/// <summary>
/// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see>
/// parameter when the template is expanded.
/// </summary>
[CanBeNull] public string Expression { get; set; }
/// <summary>
/// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed.
/// </summary>
/// <remarks>
/// If the target parameter is used several times in the template, only one occurrence becomes editable;
/// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence,
/// use values >= 0. To make the parameter non-editable when the template is expanded, use -1.
/// </remarks>>
public int Editable { get; set; }
/// <summary>
/// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the
/// <see cref="MacroAttribute"/> is applied on a template method.
/// </summary>
[CanBeNull] public string Target { get; set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
internal sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
internal sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
internal sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
internal sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
internal sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
internal sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
internal sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute() { }
public AspMvcActionAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[CanBeNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class AspMvcAreaAttribute : Attribute
{
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[CanBeNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is
/// an MVC controller. If applied to a method, the MVC controller name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
internal sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[CanBeNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC
/// partial view. If applied to a method, the MVC partial view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
internal sealed class AspMvcPartialViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
internal sealed class AspMvcSuppressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class AspMvcTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
internal sealed class AspMvcViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component name.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class AspMvcViewComponentAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view component view. If applied to a method, the MVC view component view name is default.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
internal sealed class AspMvcViewComponentViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name.
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
internal sealed class AspMvcActionSelectorAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
internal sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute() { }
public HtmlElementAttributesAttribute([NotNull] string name)
{
Name = name;
}
[CanBeNull] public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)]
internal sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
internal sealed class RazorSectionAttribute : Attribute { }
/// <summary>
/// Indicates how method, constructor invocation or property access
/// over collection type affects content of the collection.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)]
internal sealed class CollectionAccessAttribute : Attribute
{
public CollectionAccessAttribute(CollectionAccessType collectionAccessType)
{
CollectionAccessType = collectionAccessType;
}
public CollectionAccessType CollectionAccessType { get; private set; }
}
[Flags]
internal enum CollectionAccessType
{
/// <summary>Method does not use or modify content of the collection.</summary>
None = 0,
/// <summary>Method only reads content of the collection but does not modify it.</summary>
Read = 1,
/// <summary>Method can change content of the collection but does not add new elements.</summary>
ModifyExistingContent = 2,
/// <summary>Method can add new elements to the collection.</summary>
UpdatedContent = ModifyExistingContent | 4
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if
/// one of the conditions is satisfied. To set the condition, mark one of the parameters with
/// <see cref="AssertionConditionAttribute"/> attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
internal sealed class AssertionMethodAttribute : Attribute { }
/// <summary>
/// Indicates the condition parameter of the assertion method. The method itself should be
/// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of
/// the attribute is the assertion type.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class AssertionConditionAttribute : Attribute
{
public AssertionConditionAttribute(AssertionConditionType conditionType)
{
ConditionType = conditionType;
}
public AssertionConditionType ConditionType { get; private set; }
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisfies the condition,
/// then the execution continues. Otherwise, execution is assumed to be halted.
/// </summary>
internal enum AssertionConditionType
{
/// <summary>Marked parameter should be evaluated to true.</summary>
IS_TRUE = 0,
/// <summary>Marked parameter should be evaluated to false.</summary>
IS_FALSE = 1,
/// <summary>Marked parameter should be evaluated to null value.</summary>
IS_NULL = 2,
/// <summary>Marked parameter should be evaluated to not null value.</summary>
IS_NOT_NULL = 3,
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception.
/// </summary>
[Obsolete("Use [ContractAnnotation('=> halt')] instead")]
[AttributeUsage(AttributeTargets.Method)]
internal sealed class TerminatesProgramAttribute : Attribute { }
/// <summary>
/// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select,
/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters
/// of delegate type by analyzing LINQ method chains.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
internal sealed class LinqTunnelAttribute : Attribute { }
/// <summary>
/// Indicates that IEnumerable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class NoEnumerationAttribute : Attribute { }
/// <summary>
/// Indicates that parameter is regular expression pattern.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class RegexPatternAttribute : Attribute { }
/// <summary>
/// Prevents the Member Reordering feature from tossing members of the marked class.
/// </summary>
/// <remarks>
/// The attribute must be mentioned in your member reordering patterns
/// </remarks>
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)]
internal sealed class NoReorderAttribute : Attribute { }
/// <summary>
/// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated
/// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
internal sealed class XamlItemsControlAttribute : Attribute { }
/// <summary>
/// XAML attribute. Indicates the property of some <c>BindingBase</c>-derived type, that
/// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will
/// enable the <c>DataContext</c> type resolve for XAML bindings for such properties.
/// </summary>
/// <remarks>
/// Property should have the tree ancestor of the <c>ItemsControl</c> type or
/// marked with the <see cref="XamlItemsControlAttribute"/> attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
internal sealed class XamlItemBindingOfItemsControlAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal sealed class AspChildControlTypeAttribute : Attribute
{
public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType)
{
TagName = tagName;
ControlType = controlType;
}
[NotNull] public string TagName { get; private set; }
[NotNull] public Type ControlType { get; private set; }
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
internal sealed class AspDataFieldAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
internal sealed class AspDataFieldsAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
internal sealed class AspMethodPropertyAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal sealed class AspRequiredAttributeAttribute : Attribute
{
public AspRequiredAttributeAttribute([NotNull] string attribute)
{
Attribute = attribute;
}
[NotNull] public string Attribute { get; private set; }
}
[AttributeUsage(AttributeTargets.Property)]
internal sealed class AspTypePropertyAttribute : Attribute
{
public bool CreateConstructorReferences { get; private set; }
public AspTypePropertyAttribute(bool createConstructorReferences)
{
CreateConstructorReferences = createConstructorReferences;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
internal sealed class RazorImportNamespaceAttribute : Attribute
{
public RazorImportNamespaceAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
internal sealed class RazorInjectionAttribute : Attribute
{
public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName)
{
Type = type;
FieldName = fieldName;
}
[NotNull] public string Type { get; private set; }
[NotNull] public string FieldName { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
internal sealed class RazorDirectiveAttribute : Attribute
{
public RazorDirectiveAttribute([NotNull] string directive)
{
Directive = directive;
}
[NotNull] public string Directive { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
internal sealed class RazorPageBaseTypeAttribute : Attribute
{
public RazorPageBaseTypeAttribute([NotNull] string baseType)
{
BaseType = baseType;
}
public RazorPageBaseTypeAttribute([NotNull] string baseType, string pageName)
{
BaseType = baseType;
PageName = pageName;
}
[NotNull] public string BaseType { get; private set; }
[CanBeNull] public string PageName { get; private set; }
}
[AttributeUsage(AttributeTargets.Method)]
internal sealed class RazorHelperCommonAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
internal sealed class RazorLayoutAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
internal sealed class RazorWriteLiteralMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
internal sealed class RazorWriteMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class RazorWriteMethodParameterAttribute : Attribute { }
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using SharpDX;
using static System.Math;
using static MathExtensions;
public class HarmonicInverseKinematicsSolver : IInverseKinematicsSolver {
private const int Iterations = 10;
private readonly RigidBoneSystem boneSystem;
private readonly BoneAttributes[] boneAttributes;
private readonly bool[] areOrientable;
public HarmonicInverseKinematicsSolver(RigidBoneSystem boneSystem, BoneAttributes[] boneAttributes) {
this.boneSystem = boneSystem;
this.boneAttributes = boneAttributes;
areOrientable = MakeAreOrientable(boneSystem);
}
private static bool[] MakeAreOrientable(RigidBoneSystem boneSystem) {
bool[] areOrientable = new bool[boneSystem.Bones.Length];
areOrientable[boneSystem.BonesByName["lHand"].Index] = true;
areOrientable[boneSystem.BonesByName["rHand"].Index] = true;
areOrientable[boneSystem.BonesByName["lFoot"].Index] = true;
areOrientable[boneSystem.BonesByName["rFoot"].Index] = true;
return areOrientable;
}
private IEnumerable<RigidBone> GetBoneChain(RigidBone sourceBone, bool hasOrientationGoal) {
for (var bone = sourceBone; bone != null; bone = bone.Parent) {
if (areOrientable[bone.Index] && hasOrientationGoal) {
//omit orientable bones if there's a orientation goal since rotation for those bone is already set
continue;
}
yield return bone;
}
}
private struct RootTranslationPartialSolution {
public Vector3 linearVelocity;
public float time;
}
private RootTranslationPartialSolution SolveRootTranslation(
Vector3 worldSource, Vector3 worldTarget) {
var force = (worldTarget - worldSource);
float mass = boneAttributes[0].MassIncludingDescendants;
var linearVelocity = force / mass;
var time = mass;
return new RootTranslationPartialSolution {
linearVelocity = linearVelocity,
time = time,
};
}
private void ApplyPartialSolution(RootTranslationPartialSolution partialSolution, RigidBoneSystemInputs inputs, float time) {
inputs.RootTranslation += time * partialSolution.linearVelocity;
}
private struct BonePartialSolution {
public static BonePartialSolution Zero => new BonePartialSolution { angularVelocity = Vector3.Zero, time = float.PositiveInfinity };
public Vector3 angularVelocity;
public float time;
}
private BonePartialSolution SolveSingleBone(
RigidBone bone,
Vector3 worldSource, Vector3 worldTarget, MassMoment[] massMoments, Vector3 figureCenterOverride,
RigidBoneSystemInputs inputs, RigidTransform[] boneTransforms) {
if (bone.Parent == boneSystem.RootBone) {
//skip the hip bone because it's the same as the root bone but with a different center
return BonePartialSolution.Zero;
}
var center = bone != boneSystem.RootBone ? boneTransforms[bone.Index].Transform(bone.CenterPoint) : figureCenterOverride;
var parentTotalRotation = bone.Parent != null ? boneTransforms[bone.Parent.Index].Rotation : Quaternion.Identity;
var boneToWorldSpaceRotation = bone.OrientationSpace.Orientation.Chain(parentTotalRotation);
var worldToBoneSpaceRotation = Quaternion.Invert(boneToWorldSpaceRotation);
var boneSpaceSource = Vector3.Transform(worldSource - center, worldToBoneSpaceRotation);
var boneSpaceTarget = Vector3.Transform(worldTarget - center, worldToBoneSpaceRotation);
var force = boneSpaceTarget - boneSpaceSource;
var torque = Vector3.Cross(boneSpaceSource, force);
float mass = boneAttributes[bone.Index].MassIncludingDescendants;
Vector3 unnormalizedAxisOfRotation = Vector3.Cross(worldSource - center, worldTarget - center);
float unnormalizedAxisOfRotationLength = unnormalizedAxisOfRotation.Length();
if (MathUtil.IsZero(unnormalizedAxisOfRotationLength)) {
return BonePartialSolution.Zero;
}
Vector3 axisOfRotation = unnormalizedAxisOfRotation / unnormalizedAxisOfRotationLength;
float momentOfInertia = massMoments[bone.Index].GetMomentOfInertia(axisOfRotation, center);
var angularVelocity = torque / momentOfInertia;
var twistAxis = bone.RotationOrder.TwistAxis;
var existingRotation = bone.GetOrientedSpaceRotation(inputs).AsQuaternion(twistAxis);
var relaxedRotation = bone.Constraint.Center.AsQuaternion(twistAxis);
float relaxationBias = InverseKinematicsUtilities.CalculateRelaxationBias(relaxedRotation, existingRotation, angularVelocity);
angularVelocity *= relaxationBias;
var linearVelocity = Vector3.Cross(angularVelocity, boneSpaceSource);
var rotation = QuaternionExtensions.RotateBetween(
Vector3.Normalize(boneSpaceSource),
Vector3.Normalize(boneSpaceTarget));
var radius = boneSpaceSource.Length();
var distance = rotation.AccurateAngle() * radius;
float time = distance == 0 ? 0 : distance / linearVelocity.Length();
DebugUtilities.AssertFinite(angularVelocity);
return new BonePartialSolution {
angularVelocity = angularVelocity,
time = time
};
}
private void ApplyPartialSolution(RigidBone bone, BonePartialSolution partialSolution, RigidTransform[] boneTransforms, Vector3 figureCenterOverride, RigidBoneSystemInputs inputs, float time) {
var twistAxis = bone.RotationOrder.TwistAxis;
var originalRotationQ = inputs.Rotations[bone.Index].AsQuaternion(twistAxis);
var rotationDelta = QuaternionExtensions.FromRotationVector(time * partialSolution.angularVelocity);
var newRotationQ = originalRotationQ.Chain(rotationDelta);
var newRotation = TwistSwing.Decompose(twistAxis, newRotationQ);
inputs.Rotations[bone.Index] = bone.Constraint.Clamp(newRotation);
if (bone == boneSystem.RootBone) {
var preTotalTransform = boneTransforms[bone.Index];
var postTotalTransform = bone.GetChainedTransform(inputs);
var unposedFigureCenterOverride = preTotalTransform.InverseTransform(figureCenterOverride);
var postFigureCenterOverride = postTotalTransform.Transform(unposedFigureCenterOverride);
var centerDisplacement = figureCenterOverride - postFigureCenterOverride;
inputs.RootTranslation += centerDisplacement;
}
}
private Vector3[] GetCentersOfMass(RigidTransform[] totalTransforms) {
float[] descendantMasses = new float[boneSystem.Bones.Length];
Vector3[] descendantMassPositions = new Vector3[boneSystem.Bones.Length];
Vector3[] centersOfMass = new Vector3[boneSystem.Bones.Length];
foreach (var bone in boneSystem.Bones.Reverse()) {
float mass = boneAttributes[bone.Index].MassMoment.Mass;
var position = totalTransforms[bone.Index].Transform(bone.CenterPoint + boneAttributes[bone.Index].MassMoment.GetCenterOfMass());
var massPosition = mass * position;
var totalMass = descendantMasses[bone.Index] + mass;
var totalMassPosition = descendantMassPositions[bone.Index] + massPosition;
centersOfMass[bone.Index] = descendantMassPositions[bone.Index] / descendantMasses[bone.Index];
var parent = bone.Parent;
if (parent != null) {
descendantMasses[parent.Index] += totalMass;
descendantMassPositions[parent.Index] += totalMassPosition;
}
}
return centersOfMass;
}
private MassMoment[] GetMassMoments(RigidTransform[] totalTransforms, RigidBone[] boneChain) {
MassMoment[] accumulators = new MassMoment[boneSystem.Bones.Length];
bool[] areOnChain = new bool[boneSystem.Bones.Length];
foreach (var bone in boneChain) {
areOnChain[bone.Index] = true;
}
foreach (var bone in boneSystem.Bones.Reverse()) {
var unposedBoneCenteredMassMoment = boneAttributes[bone.Index].MassMoment;
var unposedMassMoment = unposedBoneCenteredMassMoment.Translate(bone.CenterPoint);
var totalTransform = totalTransforms[bone.Index];
var massMoment = unposedMassMoment.Rotate(totalTransform.Rotation).Translate(totalTransform.Translation);
var centerOfRation = totalTransform.Transform(bone.CenterPoint);
accumulators[bone.Index].AddInplace(massMoment);
var parent = bone.Parent;
if (parent != null) {
float counterRotationRatio;
if (areOnChain[bone.Index]) {
counterRotationRatio = 0;
} else {
counterRotationRatio = boneAttributes[bone.Index].MassMoment.Mass / boneAttributes[0].MassIncludingDescendants;
}
accumulators[parent.Index].AddFlexibleInPlace(accumulators[bone.Index], counterRotationRatio, centerOfRation);
}
}
return accumulators;
}
private void CountertransformOffChainBones(RigidTransform[] preTotalTransforms, Vector3[] preCentersOfMass, RigidBoneSystemInputs inputs, RigidBone[] boneChain) {
bool[] areOnChain = new bool[boneSystem.Bones.Length];
foreach (var bone in boneChain) {
areOnChain[bone.Index] = true;
}
var rootTransform = RigidTransform.FromTranslation(inputs.RootTranslation);
RigidTransform[] postTotalTransforms = new RigidTransform[preTotalTransforms.Length];
foreach (var bone in boneSystem.Bones) {
if (!boneAttributes[bone.Index].IsIkable) {
//don't even bother to update postTotalTransforms because non-Ikable bones never have Ikable children
continue;
}
var parentPostTotalTransform = bone.Parent != null ? postTotalTransforms[bone.Parent.Index] : rootTransform;
if (!areOnChain[bone.Index]) {
var preTotalTransform = preTotalTransforms[bone.Index];
var postTotalTransform = bone.GetChainedTransform(inputs, parentPostTotalTransform);
var preCenterOfRotation = preTotalTransform.Transform(bone.CenterPoint);
var postCenterOfRotation = postTotalTransform.Transform(bone.CenterPoint);
var originalWorldRotation = preTotalTransform.Rotation;
Quaternion centerOfMassRestoringRotation;
var preChildCenterOfMass = preCentersOfMass[bone.Index];
if (!float.IsNaN(preChildCenterOfMass.X)) {
var counterRotationDelta = QuaternionExtensions.RotateBetween(
Vector3.Normalize(preChildCenterOfMass - preCenterOfRotation),
Vector3.Normalize(preChildCenterOfMass - postCenterOfRotation));
centerOfMassRestoringRotation = counterRotationDelta;
} else {
//no child center of mass to restore
centerOfMassRestoringRotation = Quaternion.Identity;
}
var worldCounterRotation = originalWorldRotation.Chain(centerOfMassRestoringRotation);
var counterRotation = worldCounterRotation.Chain(Quaternion.Invert(parentPostTotalTransform.Rotation));
var originalRotation = bone.GetRotation(inputs);
float shrinkRatio = boneAttributes[bone.Index].MassMoment.Mass / boneAttributes[0].MassIncludingDescendants;
var shrunkCounterRotation = Quaternion.Lerp(originalRotation, counterRotation, shrinkRatio);
bone.SetRotation(inputs, shrunkCounterRotation, true);
}
var finalPostTotalTransform = bone.GetChainedTransform(inputs, parentPostTotalTransform);
postTotalTransforms[bone.Index] = finalPostTotalTransform;
}
}
private void ApplyOrientationGoal(InverseKinematicsGoal goal, RigidBoneSystemInputs inputs) {
if (!areOrientable[goal.SourceBone.Index] || !goal.HasOrientation) {
return;
}
var bone = goal.SourceBone;
var parentBone = bone.Parent;
var grandparentBone = parentBone.Parent;
var grandparentTotalTransform = grandparentBone.GetChainedTransform(inputs);
var parentTotalTransform = parentBone.GetChainedTransform(inputs, grandparentTotalTransform);
var goalTotalRotation = Quaternion.Invert(goal.UnposedSourceOrientation).Chain(goal.TargetOrientation);
var newLocalRotation = goalTotalRotation.Chain(Quaternion.Invert(parentTotalTransform.Rotation));
bone.SetRotation(inputs, newLocalRotation, true);
var clampedNewLocalRotation = bone.GetRotation(inputs);
var residualGoalTotalRotation = Quaternion.Invert(clampedNewLocalRotation).Chain(goalTotalRotation);
var parentNewLocalRotation = residualGoalTotalRotation.Chain(Quaternion.Invert(grandparentTotalTransform.Rotation));
parentBone.SetTwistOnly(inputs, parentNewLocalRotation);
}
private void ApplyPositionGoal(InverseKinematicsGoal goal, RigidBoneSystemInputs inputs) {
var boneTransforms = boneSystem.GetBoneTransforms(inputs);
var centersOfMass = GetCentersOfMass(boneTransforms);
var sourcePosition = boneTransforms[goal.SourceBone.Index].Transform(goal.SourceBone.CenterPoint + goal.UnposedSourcePosition);
var bones = GetBoneChain(goal.SourceBone, goal.HasOrientation).ToArray();
//var bones = new RigidBone[] { boneSystem.BonesByName["lForearmBend"], boneSystem.BonesByName["lShldrBend"] };
var massMoments = GetMassMoments(boneTransforms, bones);
var figureCenterOverride = massMoments[0].GetCenterOfMass();
float totalRate = 0;
var bonePartialSolutions = new BonePartialSolution[bones.Length];
for (int i = 0; i < bones.Length; ++i) {
var partialSolution = SolveSingleBone(bones[i], sourcePosition, goal.TargetPosition, massMoments, figureCenterOverride, inputs, boneTransforms);
bonePartialSolutions[i] = partialSolution;
totalRate += 1 / partialSolution.time;
}
var rootTranslationPartialSolution = SolveRootTranslation(sourcePosition, goal.TargetPosition);
totalRate += 1 / rootTranslationPartialSolution.time;
float time = 1 / totalRate;
for (int i = 0; i < bones.Length; ++i) {
ApplyPartialSolution(bones[i], bonePartialSolutions[i], boneTransforms, figureCenterOverride, inputs, time);
}
ApplyPartialSolution(rootTranslationPartialSolution, inputs, time);
CountertransformOffChainBones(boneTransforms, centersOfMass, inputs, bones);
}
private void DoIteration(int iteration, InverseKinematicsGoal goal, RigidBoneSystemInputs inputs) {
ApplyOrientationGoal(goal, inputs);
ApplyPositionGoal(goal, inputs);
}
public void Solve(RigidBoneSystem boneSystem, List<InverseKinematicsGoal> goals, RigidBoneSystemInputs inputs) {
for (int i = 0; i < Iterations; ++i) {
foreach (var goal in goals) {
DoIteration(i, goal, inputs);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.