context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using Workbench.Core.Models;
namespace Workbench.Core
{
/// <summary>
/// Builder for creating a workspace.
/// </summary>
public sealed class WorkspaceBuilder
{
private readonly WorkspaceModel _workspace;
private readonly BundleModel _model;
/// <summary>
/// Initialize a workspace builder with a model name.
/// </summary>
public WorkspaceBuilder(string theModelName)
{
if (string.IsNullOrWhiteSpace(theModelName))
throw new ArgumentException(nameof(theModelName));
_workspace = new WorkspaceModel(new ModelName(theModelName));
_model = _workspace.Model;
}
/// <summary>
/// Initialize a workspace builder with a model name.
/// </summary>
public WorkspaceBuilder(ModelName theModelName)
{
_workspace = new WorkspaceModel(theModelName);
_model = _workspace.Model;
}
/// <summary>
/// Initialize a workspace builder with default values.
/// </summary>
public WorkspaceBuilder()
{
_workspace = new WorkspaceModel();
_model = _workspace.Model;
}
/// <summary>
/// Add a singleton variable.
/// </summary>
/// <param name="theVariableName">Variable name.</param>
/// <param name="theDomainExpression">Variable domain.</param>
/// <returns>Workspace context.</returns>
public WorkspaceBuilder AddSingleton(string theVariableName, string theDomainExpression)
{
if (string.IsNullOrWhiteSpace(theVariableName))
throw new ArgumentException(nameof(theVariableName));
if (string.IsNullOrWhiteSpace(theDomainExpression))
throw new ArgumentException(nameof(theDomainExpression));
var newVariable = new SingletonVariableModel(_model, new ModelName(theVariableName), new InlineDomainModel(theDomainExpression));
_model.AddVariable(newVariable);
return this;
}
/// <summary>
/// Add an aggregate variable.
/// </summary>
/// <param name="newAggregateName">Variable name.</param>
/// <param name="aggregateSize">Size.</param>
/// <param name="newDomainExpression">Variable domain.</param>
/// <returns>Workspace context.</returns>
public WorkspaceBuilder AddAggregate(string newAggregateName, int aggregateSize, string newDomainExpression)
{
if (string.IsNullOrWhiteSpace(newAggregateName))
throw new ArgumentException(nameof(newAggregateName));
if (aggregateSize <= 0)
throw new ArgumentOutOfRangeException(nameof(aggregateSize));
if (string.IsNullOrWhiteSpace(newDomainExpression))
throw new ArgumentException(nameof(newDomainExpression));
var newVariable = new AggregateVariableModel(_model, new ModelName(newAggregateName), aggregateSize, new InlineDomainModel(newDomainExpression));
_model.AddVariable(newVariable);
return this;
}
/// <summary>
/// Add an aggregate variable.
/// </summary>
/// <param name="action">User supplied action.</param>
/// <returns>Workspace context.</returns>
public WorkspaceBuilder AddAggregate(Action<AggregateVariableConfiguration> action)
{
var variableConfig = CreateDefaultAggregateVariableConfig();
action(variableConfig);
var newVariable = variableConfig.Build();
_model.AddVariable(newVariable);
return this;
}
public WorkspaceBuilder WithSharedDomain(string newDomainName, string newDomainExpression)
{
if (string.IsNullOrWhiteSpace(newDomainName))
throw new ArgumentException(nameof(newDomainName));
if (string.IsNullOrWhiteSpace(newDomainExpression))
throw new ArgumentException(nameof(newDomainExpression));
var newDomain = new SharedDomainModel(_model, new ModelName(newDomainName), new SharedDomainExpressionModel(newDomainExpression));
_model.AddSharedDomain(newDomain);
return this;
}
public WorkspaceBuilder WithConstraintExpression(string theConstraintExpression)
{
if (string.IsNullOrWhiteSpace(theConstraintExpression))
throw new ArgumentException(nameof(theConstraintExpression));
var constraintModel = new ExpressionConstraintModel(_model, new ConstraintExpressionModel(theConstraintExpression));
_model.AddConstraint(constraintModel);
return this;
}
public WorkspaceBuilder WithConstraintAllDifferent(string theExpression)
{
if (string.IsNullOrWhiteSpace(theExpression))
throw new ArgumentException(nameof(theExpression));
var newConstraint = new AllDifferentConstraintModel(_model, new AllDifferentConstraintExpressionModel(theExpression));
_model.AddConstraint(newConstraint);
return this;
}
public WorkspaceBuilder WithChessboard(string theVisualizerName)
{
if (string.IsNullOrWhiteSpace(theVisualizerName))
throw new ArgumentException(nameof(theVisualizerName));
var chessboard = new ChessboardModel(new ModelName(theVisualizerName));
var chessboardVisualizer = new ChessboardTabModel(chessboard, new WorkspaceTabTitle());
_workspace.AddVisualizer(chessboardVisualizer);
return this;
}
public WorkspaceBuilder WithBinding(string theBindingExpression)
{
if (string.IsNullOrWhiteSpace(theBindingExpression))
throw new ArgumentException(nameof(theBindingExpression));
_workspace.AddBindingExpression(new VisualizerBindingExpressionModel(theBindingExpression));
return this;
}
public WorkspaceBuilder WithTable(TableTabModel theTab)
{
_workspace.AddVisualizer(theTab);
return this;
}
public WorkspaceBuilder AddBundle(Action<BundleConfiguration> action)
{
var bundleConfiguration = new BundleConfiguration(_workspace);
action(bundleConfiguration);
var newBundle = bundleConfiguration.Build();
_model.AddBundle(newBundle);
return this;
}
private AggregateVariableConfiguration CreateDefaultAggregateVariableConfig()
{
return new AggregateVariableConfiguration(_workspace);
}
public WorkspaceBuilder AddBucket(Action<BucketConfiguration> action)
{
var bucketConfiguration = new BucketConfiguration(_workspace);
action(bucketConfiguration);
var newBucket = bucketConfiguration.Build();
_model.AddBucket(newBucket);
return this;
}
public WorkspaceModel Build()
{
return _workspace;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Xunit;
using System.Text;
using System.ComponentModel;
using System.Security;
using System.Threading;
namespace System.Diagnostics.Tests
{
public partial class ProcessStartInfoTests : ProcessTestBase
{
[Fact]
public void TestEnvironmentProperty()
{
Assert.NotEqual(0, new Process().StartInfo.Environment.Count);
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
// with current environmental variables.
IDictionary<string, string> environment = psi.Environment;
Assert.NotEqual(0, environment.Count);
int countItems = environment.Count;
environment.Add("NewKey", "NewValue");
environment.Add("NewKey2", "NewValue2");
Assert.Equal(countItems + 2, environment.Count);
environment.Remove("NewKey");
Assert.Equal(countItems + 1, environment.Count);
environment.Add("NewKey2", "NewValue2Overridden");
Assert.Equal("NewValue2Overridden", environment["NewKey2"]);
//Clear
environment.Clear();
Assert.Equal(0, environment.Count);
//ContainsKey
environment.Add("NewKey", "NewValue");
environment.Add("NewKey2", "NewValue2");
Assert.True(environment.ContainsKey("NewKey"));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.ContainsKey("newkey"));
Assert.False(environment.ContainsKey("NewKey99"));
//Iterating
string result = null;
int index = 0;
foreach (string e1 in environment.Values.OrderBy(p => p))
{
index++;
result += e1;
}
Assert.Equal(2, index);
Assert.Equal("NewValueNewValue2", result);
result = null;
index = 0;
foreach (string e1 in environment.Keys.OrderBy(p => p))
{
index++;
result += e1;
}
Assert.Equal("NewKeyNewKey2", result);
Assert.Equal(2, index);
result = null;
index = 0;
foreach (KeyValuePair<string, string> e1 in environment.OrderBy(p => p.Key))
{
index++;
result += e1.Key;
}
Assert.Equal("NewKeyNewKey2", result);
Assert.Equal(2, index);
//Contains
Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey", "NewValue")));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("nEwKeY", "NewValue")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey99", "NewValue99")));
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() => environment.Contains(new KeyValuePair<string, string>(null, "NewValue99")));
environment.Add(new KeyValuePair<string, string>("NewKey98", "NewValue98"));
//Indexed
string newIndexItem = environment["NewKey98"];
Assert.Equal("NewValue98", newIndexItem);
//TryGetValue
string stringout = null;
Assert.True(environment.TryGetValue("NewKey", out stringout));
Assert.Equal("NewValue", stringout);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.True(environment.TryGetValue("NeWkEy", out stringout));
Assert.Equal("NewValue", stringout);
}
stringout = null;
Assert.False(environment.TryGetValue("NewKey99", out stringout));
Assert.Equal(null, stringout);
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() =>
{
string stringout1 = null;
environment.TryGetValue(null, out stringout1);
});
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() => environment.Add(null, "NewValue2"));
environment.Add("NewKey2", "NewValue2OverriddenAgain");
Assert.Equal("NewValue2OverriddenAgain", environment["NewKey2"]);
//Remove Item
environment.Remove("NewKey98");
environment.Remove("NewKey98"); //2nd occurrence should not assert
//Exception not thrown with null key
Assert.Throws<ArgumentNullException>(() => { environment.Remove(null); });
//"Exception not thrown with null key"
Assert.Throws<KeyNotFoundException>(() => environment["1bB"]);
Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey2", "NewValue2OverriddenAgain")));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("NEWKeY2", "NewValue2OverriddenAgain")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey2", "newvalue2Overriddenagain")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("newkey2", "newvalue2Overriddenagain")));
//Use KeyValuePair Enumerator
string[] results = new string[2];
var x = environment.GetEnumerator();
x.MoveNext();
results[0] = x.Current.Key + " " + x.Current.Value;
x.MoveNext();
results[1] = x.Current.Key + " " + x.Current.Value;
Assert.Equal(new string[] { "NewKey NewValue", "NewKey2 NewValue2OverriddenAgain" }, results.OrderBy(s => s));
//IsReadonly
Assert.False(environment.IsReadOnly);
environment.Add(new KeyValuePair<string, string>("NewKey3", "NewValue3"));
environment.Add(new KeyValuePair<string, string>("NewKey4", "NewValue4"));
//CopyTo - the order is undefined.
KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10];
environment.CopyTo(kvpa, 0);
KeyValuePair<string, string>[] kvpaOrdered = kvpa.OrderByDescending(k => k.Value).ToArray();
Assert.Equal("NewKey4", kvpaOrdered[0].Key);
Assert.Equal("NewKey2", kvpaOrdered[2].Key);
environment.CopyTo(kvpa, 6);
Assert.Equal(default(KeyValuePair<string, string>), kvpa[5]);
Assert.StartsWith("NewKey", kvpa[6].Key);
Assert.NotEqual(kvpa[6].Key, kvpa[7].Key);
Assert.StartsWith("NewKey", kvpa[7].Key);
Assert.NotEqual(kvpa[7].Key, kvpa[8].Key);
Assert.StartsWith("NewKey", kvpa[8].Key);
//Exception not thrown with null key
Assert.Throws<ArgumentOutOfRangeException>(() => { environment.CopyTo(kvpa, -1); });
//Exception not thrown with null key
AssertExtensions.Throws<ArgumentException>(null, () => { environment.CopyTo(kvpa, 9); });
//Exception not thrown with null key
Assert.Throws<ArgumentNullException>(() =>
{
KeyValuePair<string, string>[] kvpanull = null;
environment.CopyTo(kvpanull, 0);
});
}
[Fact]
public void TestEnvironmentOfChildProcess()
{
const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings
const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff";
Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output
try
{
// Schedule a process to see what env vars it gets. Have it write out those variables
// to its output stream so we can read them.
Process p = CreateProcess(() =>
{
Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => Convert.ToBase64String(Encoding.UTF8.GetBytes(e.Key + "=" + e.Value)))));
return SuccessExitCode;
});
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Assert.True(p.WaitForExit(WaitInMS));
// Parse the env vars from the child process
var actualEnv = new HashSet<string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None).Select(s => Encoding.UTF8.GetString(Convert.FromBase64String(s))));
// Validate against StartInfo.Environment.
var startInfoEnv = new HashSet<string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value));
Assert.True(startInfoEnv.SetEquals(actualEnv),
string.Format("Expected: {0}{1}Actual: {2}",
string.Join(", ", startInfoEnv.Except(actualEnv)),
Environment.NewLine,
string.Join(", ", actualEnv.Except(startInfoEnv))));
// Validate against current process. (Profilers / code coverage tools can add own environment variables
// but we start child process without them. Thus the set of variables from the child process could
// be a subset of variables from current process.)
var envEnv = new HashSet<string>(Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value));
Assert.True(envEnv.IsSupersetOf(actualEnv),
string.Format("Expected: {0}{1}Actual: {2}",
string.Join(", ", envEnv.Except(actualEnv)),
Environment.NewLine,
string.Join(", ", actualEnv.Except(envEnv))));
}
finally
{
Environment.SetEnvironmentVariable(ExtraEnvVar, null);
}
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Uap, "Only UAP blocks setting ShellExecute to true")]
public void UseShellExecute_GetSetWindows_Success_Uap()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.False(psi.UseShellExecute);
// Calling the setter
Assert.Throws<PlatformNotSupportedException>(() => { psi.UseShellExecute = true; });
psi.UseShellExecute = false;
// Calling the getter
Assert.False(psi.UseShellExecute, "UseShellExecute=true is not supported on onecore.");
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Desktop UseShellExecute is set to true by default")]
public void UseShellExecute_GetSetWindows_Success_Netfx()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.True(psi.UseShellExecute);
psi.UseShellExecute = false;
Assert.False(psi.UseShellExecute);
psi.UseShellExecute = true;
Assert.True(psi.UseShellExecute);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.NetFramework)]
public void TestUseShellExecuteProperty_SetAndGet_NotUapOrNetFX()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.False(psi.UseShellExecute);
psi.UseShellExecute = true;
Assert.True(psi.UseShellExecute);
psi.UseShellExecute = false;
Assert.False(psi.UseShellExecute);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void TestUseShellExecuteProperty_Redirects_NotSupported(int std)
{
Process p = CreateProcessLong();
p.StartInfo.UseShellExecute = true;
switch (std)
{
case 0: p.StartInfo.RedirectStandardInput = true; break;
case 1: p.StartInfo.RedirectStandardOutput = true; break;
case 2: p.StartInfo.RedirectStandardError = true; break;
}
Assert.Throws<InvalidOperationException>(() => p.Start());
}
[Fact]
public void TestArgumentsProperty()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.Equal(string.Empty, psi.Arguments);
psi = new ProcessStartInfo("filename", "-arg1 -arg2");
Assert.Equal("-arg1 -arg2", psi.Arguments);
psi.Arguments = "-arg3 -arg4";
Assert.Equal("-arg3 -arg4", psi.Arguments);
}
[Theory, InlineData(true), InlineData(false)]
public void TestCreateNoWindowProperty(bool value)
{
Process testProcess = CreateProcessLong();
try
{
testProcess.StartInfo.CreateNoWindow = value;
testProcess.Start();
Assert.Equal(value, testProcess.StartInfo.CreateNoWindow);
}
finally
{
if (!testProcess.HasExited)
testProcess.Kill();
Assert.True(testProcess.WaitForExit(WaitInMS));
}
}
[Fact]
public void TestWorkingDirectoryProperty()
{
CreateDefaultProcess();
// check defaults
Assert.Equal(string.Empty, _process.StartInfo.WorkingDirectory);
Process p = CreateProcessLong();
p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
try
{
p.Start();
Assert.Equal(Directory.GetCurrentDirectory(), p.StartInfo.WorkingDirectory);
}
finally
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
[ActiveIssue(12696)]
[Fact, PlatformSpecific(TestPlatforms.Windows), OuterLoop] // Uses P/Invokes, Requires admin privileges
public void TestUserCredentialsPropertiesOnWindows()
{
string username = "test", password = "PassWord123!!";
try
{
Interop.NetUserAdd(username, password);
}
catch (Exception exc)
{
Console.Error.WriteLine("TestUserCredentialsPropertiesOnWindows: NetUserAdd failed: {0}", exc.Message);
return; // test is irrelevant if we can't add a user
}
bool hasStarted = false;
SafeProcessHandle handle = null;
Process p = null;
try
{
p = CreateProcessLong();
p.StartInfo.LoadUserProfile = true;
p.StartInfo.UserName = username;
p.StartInfo.PasswordInClearText = password;
hasStarted = p.Start();
if (Interop.OpenProcessToken(p.SafeHandle, 0x8u, out handle))
{
SecurityIdentifier sid;
if (Interop.ProcessTokenToSid(handle, out sid))
{
string actualUserName = sid.Translate(typeof(NTAccount)).ToString();
int indexOfDomain = actualUserName.IndexOf('\\');
if (indexOfDomain != -1)
actualUserName = actualUserName.Substring(indexOfDomain + 1);
bool isProfileLoaded = GetNamesOfUserProfiles().Any(profile => profile.Equals(username));
Assert.Equal(username, actualUserName);
Assert.True(isProfileLoaded);
}
}
}
finally
{
IEnumerable<uint> collection = new uint[] { 0 /* NERR_Success */, 2221 /* NERR_UserNotFound */ };
Assert.Contains<uint>(Interop.NetUserDel(null, username), collection);
if (handle != null)
handle.Dispose();
if (hasStarted)
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
}
private static List<string> GetNamesOfUserProfiles()
{
List<string> userNames = new List<string>();
string[] names = Registry.Users.GetSubKeyNames();
for (int i = 1; i < names.Length; i++)
{
try
{
SecurityIdentifier sid = new SecurityIdentifier(names[i]);
string userName = sid.Translate(typeof(NTAccount)).ToString();
int indexofDomain = userName.IndexOf('\\');
if (indexofDomain != -1)
{
userName = userName.Substring(indexofDomain + 1);
userNames.Add(userName);
}
}
catch (Exception) { }
}
return userNames;
}
[Fact]
public void TestEnvironmentVariables_Environment_DataRoundTrips()
{
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
// with current environmental variables.
psi.Environment.Clear();
psi.EnvironmentVariables.Add("NewKey", "NewValue");
psi.Environment.Add("NewKey2", "NewValue2");
Assert.Equal(psi.Environment["NewKey"], psi.EnvironmentVariables["NewKey"]);
Assert.Equal(psi.Environment["NewKey2"], psi.EnvironmentVariables["NewKey2"]);
Assert.Equal(2, psi.EnvironmentVariables.Count);
Assert.Equal(psi.Environment.Count, psi.EnvironmentVariables.Count);
AssertExtensions.Throws<ArgumentException>(null, () => psi.EnvironmentVariables.Add("NewKey2", "NewValue2"));
psi.EnvironmentVariables.Add("NewKey3", "NewValue3");
psi.Environment.Add("NewKey3", "NewValue3Overridden");
Assert.Equal("NewValue3Overridden", psi.Environment["NewKey3"]);
psi.EnvironmentVariables.Clear();
Assert.Equal(0, psi.Environment.Count);
psi.EnvironmentVariables.Add("NewKey", "NewValue");
psi.EnvironmentVariables.Add("NewKey2", "NewValue2");
// Environment and EnvironmentVariables should be equal, but have different enumeration types.
IEnumerable<KeyValuePair<string, string>> allEnvironment = psi.Environment.OrderBy(k => k.Key);
IEnumerable<DictionaryEntry> allDictionary = psi.EnvironmentVariables.Cast<DictionaryEntry>().OrderBy(k => k.Key);
Assert.Equal(allEnvironment.Select(k => new DictionaryEntry(k.Key, k.Value)), allDictionary);
psi.EnvironmentVariables.Add("NewKey3", "NewValue3");
KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[5];
psi.Environment.CopyTo(kvpa, 0);
KeyValuePair<string, string>[] kvpaOrdered = kvpa.OrderByDescending(k => k.Key).ToArray();
Assert.Equal("NewKey", kvpaOrdered[2].Key);
Assert.Equal("NewValue", kvpaOrdered[2].Value);
psi.EnvironmentVariables.Remove("NewKey3");
Assert.False(psi.Environment.Contains(new KeyValuePair<string,string>("NewKey3", "NewValue3")));
}
[PlatformSpecific(TestPlatforms.Windows)] // Test case is specific to Windows
[Fact]
public void Verbs_GetWithExeExtension_ReturnsExpected()
{
var psi = new ProcessStartInfo { FileName = $"{Process.GetCurrentProcess().ProcessName}.exe" };
if (PlatformDetection.IsNetNative)
{
// UapAot doesn't have RegistryKey apis available so ProcessStartInfo.Verbs returns Array<string>.Empty().
Assert.Equal(0, psi.Verbs.Length);
return;
}
Assert.Contains("open", psi.Verbs, StringComparer.OrdinalIgnoreCase);
if (PlatformDetection.IsNotWindowsNanoServer)
{
Assert.Contains("runas", psi.Verbs, StringComparer.OrdinalIgnoreCase);
Assert.Contains("runasuser", psi.Verbs, StringComparer.OrdinalIgnoreCase);
}
Assert.DoesNotContain("printto", psi.Verbs, StringComparer.OrdinalIgnoreCase);
Assert.DoesNotContain("closed", psi.Verbs, StringComparer.OrdinalIgnoreCase);
}
[Theory]
[InlineData("")]
[InlineData("nofileextension")]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNoExtension_ReturnsEmpty(string fileName)
{
var info = new ProcessStartInfo { FileName = fileName };
Assert.Empty(info.Verbs);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNoRegisteredExtension_ReturnsEmpty()
{
var info = new ProcessStartInfo { FileName = "file.nosuchextension" };
Assert.Empty(info.Verbs);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNoEmptyStringKey_ReturnsEmpty()
{
const string Extension = ".noemptykeyextension";
const string FileName = "file" + Extension;
using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
{
if (tempKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
var info = new ProcessStartInfo { FileName = FileName };
Assert.Empty(info.Verbs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithEmptyStringValue_ReturnsEmpty()
{
const string Extension = ".emptystringextension";
const string FileName = "file" + Extension;
using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
{
if (tempKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
tempKey.Key.SetValue("", "");
var info = new ProcessStartInfo { FileName = FileName };
Assert.Empty(info.Verbs);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework throws an InvalidCastException for non-string keys. See https://github.com/dotnet/corefx/issues/18187.")]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNonStringValue_ReturnsEmpty()
{
const string Extension = ".nonstringextension";
const string FileName = "file" + Extension;
using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
{
if (tempKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
tempKey.Key.SetValue("", 123);
var info = new ProcessStartInfo { FileName = FileName };
Assert.Empty(info.Verbs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNoShellSubKey_ReturnsEmpty()
{
const string Extension = ".noshellsubkey";
const string FileName = "file" + Extension;
using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
{
if (tempKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
tempKey.Key.SetValue("", "nosuchshell");
var info = new ProcessStartInfo { FileName = FileName };
Assert.Empty(info.Verbs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithSubkeys_ReturnsEmpty()
{
const string Extension = ".customregistryextension";
const string FileName = "file" + Extension;
const string SubKeyValue = "customregistryextensionshell";
using (TempRegistryKey extensionKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
using (TempRegistryKey shellKey = new TempRegistryKey(Registry.ClassesRoot, SubKeyValue + "\\shell"))
{
if (extensionKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
extensionKey.Key.SetValue("", SubKeyValue);
shellKey.Key.CreateSubKey("verb1");
shellKey.Key.CreateSubKey("NEW");
shellKey.Key.CreateSubKey("new");
shellKey.Key.CreateSubKey("verb2");
var info = new ProcessStartInfo { FileName = FileName };
Assert.Equal(new string[] { "verb1", "verb2" }, info.Verbs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetUnix_ReturnsEmpty()
{
var info = new ProcessStartInfo();
Assert.Empty(info.Verbs);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Test case is specific to Unix
[Fact]
public void TestEnvironmentVariablesPropertyUnix(){
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
// with current environmental variables.
StringDictionary environmentVariables = psi.EnvironmentVariables;
Assert.NotEqual(0, environmentVariables.Count);
int CountItems = environmentVariables.Count;
environmentVariables.Add("NewKey", "NewValue");
environmentVariables.Add("NewKey2", "NewValue2");
Assert.Equal(CountItems + 2, environmentVariables.Count);
environmentVariables.Remove("NewKey");
Assert.Equal(CountItems + 1, environmentVariables.Count);
//Exception not thrown with invalid key
AssertExtensions.Throws<ArgumentException>(null, () => { environmentVariables.Add("NewKey2", "NewValue2"); });
Assert.False(environmentVariables.ContainsKey("NewKey"));
environmentVariables.Add("newkey2", "newvalue2");
Assert.True(environmentVariables.ContainsKey("newkey2"));
Assert.Equal("newvalue2", environmentVariables["newkey2"]);
Assert.Equal("NewValue2", environmentVariables["NewKey2"]);
environmentVariables.Clear();
Assert.Equal(0, environmentVariables.Count);
environmentVariables.Add("NewKey", "newvalue");
environmentVariables.Add("newkey2", "NewValue2");
Assert.False(environmentVariables.ContainsKey("newkey"));
Assert.False(environmentVariables.ContainsValue("NewValue"));
string result = null;
int index = 0;
foreach (string e1 in environmentVariables.Values)
{
index++;
result += e1;
}
Assert.Equal(2, index);
Assert.Equal("newvalueNewValue2", result);
result = null;
index = 0;
foreach (string e1 in environmentVariables.Keys)
{
index++;
result += e1;
}
Assert.Equal("NewKeynewkey2", result);
Assert.Equal(2, index);
result = null;
index = 0;
foreach (DictionaryEntry e1 in environmentVariables)
{
index++;
result += e1.Key;
}
Assert.Equal("NewKeynewkey2", result);
Assert.Equal(2, index);
//Key not found
Assert.Throws<KeyNotFoundException>(() =>
{
string stringout = environmentVariables["NewKey99"];
});
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() =>
{
string stringout = environmentVariables[null];
});
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() => environmentVariables.Add(null, "NewValue2"));
AssertExtensions.Throws<ArgumentException>(null, () => environmentVariables.Add("newkey2", "NewValue2"));
//Use DictionaryEntry Enumerator
var x = environmentVariables.GetEnumerator() as IEnumerator;
x.MoveNext();
var y1 = (DictionaryEntry)x.Current;
Assert.Equal("NewKey newvalue", y1.Key + " " + y1.Value);
x.MoveNext();
y1 = (DictionaryEntry)x.Current;
Assert.Equal("newkey2 NewValue2", y1.Key + " " + y1.Value);
environmentVariables.Add("newkey3", "newvalue3");
KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10];
environmentVariables.CopyTo(kvpa, 0);
Assert.Equal("NewKey", kvpa[0].Key);
Assert.Equal("newkey3", kvpa[2].Key);
Assert.Equal("newvalue3", kvpa[2].Value);
string[] kvp = new string[10];
AssertExtensions.Throws<ArgumentException>(null, () => { environmentVariables.CopyTo(kvp, 6); });
environmentVariables.CopyTo(kvpa, 6);
Assert.Equal("NewKey", kvpa[6].Key);
Assert.Equal("newvalue", kvpa[6].Value);
Assert.Throws<ArgumentOutOfRangeException>(() => { environmentVariables.CopyTo(kvpa, -1); });
AssertExtensions.Throws<ArgumentException>(null, () => { environmentVariables.CopyTo(kvpa, 9); });
Assert.Throws<ArgumentNullException>(() =>
{
KeyValuePair<string, string>[] kvpanull = null;
environmentVariables.CopyTo(kvpanull, 0);
});
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("domain")]
[PlatformSpecific(TestPlatforms.Windows)]
public void Domain_SetWindows_GetReturnsExpected(string domain)
{
var info = new ProcessStartInfo { Domain = domain };
Assert.Equal(domain ?? string.Empty, info.Domain);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Domain_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.Domain);
Assert.Throws<PlatformNotSupportedException>(() => info.Domain = "domain");
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("filename")]
public void FileName_Set_GetReturnsExpected(string fileName)
{
var info = new ProcessStartInfo { FileName = fileName };
Assert.Equal(fileName ?? string.Empty, info.FileName);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[PlatformSpecific(TestPlatforms.Windows)]
public void LoadUserProfile_SetWindows_GetReturnsExpected(bool loadUserProfile)
{
var info = new ProcessStartInfo { LoadUserProfile = loadUserProfile };
Assert.Equal(loadUserProfile, info.LoadUserProfile);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void LoadUserProfile_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile);
Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile = false);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("passwordInClearText")]
[PlatformSpecific(TestPlatforms.Windows)]
public void PasswordInClearText_SetWindows_GetReturnsExpected(string passwordInClearText)
{
var info = new ProcessStartInfo { PasswordInClearText = passwordInClearText };
Assert.Equal(passwordInClearText, info.PasswordInClearText);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void PasswordInClearText_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText);
Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText = "passwordInClearText");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Password_SetWindows_GetReturnsExpected()
{
using (SecureString password = new SecureString())
{
password.AppendChar('a');
var info = new ProcessStartInfo { Password = password };
Assert.Equal(password, info.Password);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Password_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.Password);
Assert.Throws<PlatformNotSupportedException>(() => info.Password = new SecureString());
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("domain")]
[PlatformSpecific(TestPlatforms.Windows)]
public void UserName_SetWindows_GetReturnsExpected(string userName)
{
var info = new ProcessStartInfo { UserName = userName };
Assert.Equal(userName ?? string.Empty, info.UserName);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void UserName_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.UserName);
Assert.Throws<PlatformNotSupportedException>(() => info.UserName = "username");
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("verb")]
public void Verb_Set_GetReturnsExpected(string verb)
{
var info = new ProcessStartInfo { Verb = verb };
Assert.Equal(verb ?? string.Empty, info.Verb);
}
[Theory]
[InlineData(ProcessWindowStyle.Normal - 1)]
[InlineData(ProcessWindowStyle.Maximized + 1)]
public void WindowStyle_SetNoSuchWindowStyle_ThrowsInvalidEnumArgumentException(ProcessWindowStyle style)
{
var info = new ProcessStartInfo();
Assert.Throws<InvalidEnumArgumentException>(() => info.WindowStyle = style);
}
[Theory]
[InlineData(ProcessWindowStyle.Hidden)]
[InlineData(ProcessWindowStyle.Maximized)]
[InlineData(ProcessWindowStyle.Minimized)]
[InlineData(ProcessWindowStyle.Normal)]
public void WindowStyle_Set_GetReturnsExpected(ProcessWindowStyle style)
{
var info = new ProcessStartInfo { WindowStyle = style };
Assert.Equal(style, info.WindowStyle);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("workingdirectory")]
public void WorkingDirectory_Set_GetReturnsExpected(string workingDirectory)
{
var info = new ProcessStartInfo { WorkingDirectory = workingDirectory };
Assert.Equal(workingDirectory ?? string.Empty, info.WorkingDirectory);
}
[Fact(Skip = "Manual test")]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void StartInfo_WebPage()
{
ProcessStartInfo info = new ProcessStartInfo
{
UseShellExecute = true,
FileName = @"http://www.microsoft.com"
};
Process.Start(info); // Returns null after navigating browser
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] // No Notepad on Nano
[MemberData(nameof(UseShellExecute))]
[OuterLoop("Launches notepad")]
[PlatformSpecific(TestPlatforms.Windows)]
public void StartInfo_NotepadWithContent(bool useShellExecute)
{
string tempFile = GetTestFilePath() + ".txt";
File.WriteAllText(tempFile, $"StartInfo_NotepadWithContent({useShellExecute})");
ProcessStartInfo info = new ProcessStartInfo
{
UseShellExecute = useShellExecute,
FileName = @"notepad.exe",
Arguments = tempFile,
WindowStyle = ProcessWindowStyle.Minimized
};
using (var process = Process.Start(info))
{
Assert.True(process != null, $"Could not start {info.FileName} {info.Arguments} UseShellExecute={info.UseShellExecute}");
try
{
process.WaitForInputIdle(); // Give the file a chance to load
Assert.Equal("notepad", process.ProcessName);
if (PlatformDetection.IsUap)
{
Assert.Throws<PlatformNotSupportedException>(() => process.MainWindowTitle);
}
else
{
// On some Windows versions, the file extension is not included in the title
Assert.StartsWith(Path.GetFileNameWithoutExtension(tempFile), process.MainWindowTitle);
}
}
finally
{
if (process != null && !process.HasExited)
process.Kill();
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer), // Nano does not support UseShellExecute
nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindows8x))] // https://github.com/dotnet/corefx/issues/20388
[OuterLoop("Launches notepad")]
[PlatformSpecific(TestPlatforms.Windows)]
// Re-enabling with extra diagnostic info
// [ActiveIssue("https://github.com/dotnet/corefx/issues/20388")]
// We don't have the ability yet for UseShellExecute in UAP
[ActiveIssue("https://github.com/dotnet/corefx/issues/20204", TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)]
public void StartInfo_TextFile_ShellExecute()
{
string tempFile = GetTestFilePath() + ".txt";
File.WriteAllText(tempFile, $"StartInfo_TextFile_ShellExecute");
ProcessStartInfo info = new ProcessStartInfo
{
UseShellExecute = true,
FileName = tempFile,
WindowStyle = ProcessWindowStyle.Minimized
};
using (var process = Process.Start(info))
{
Assert.True(process != null, $"Could not start {info.FileName} UseShellExecute={info.UseShellExecute}\r\n{GetAssociationDetails()}");
try
{
process.WaitForInputIdle(); // Give the file a chance to load
Assert.Equal("notepad", process.ProcessName);
if (PlatformDetection.IsUap)
{
Assert.Throws<PlatformNotSupportedException>(() => process.MainWindowTitle);
}
else
{
// On some Windows versions, the file extension is not included in the title
Assert.StartsWith(Path.GetFileNameWithoutExtension(tempFile), process.MainWindowTitle);
}
}
finally
{
if (process != null && !process.HasExited)
process.Kill();
}
}
}
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private unsafe static extern int AssocQueryStringW(
int flags,
int str,
string pszAssoc,
string pszExtra,
char* pszOut,
ref uint pcchOut);
private unsafe static string GetAssociationString(int flags, int str, string pszAssoc, string pszExtra)
{
uint count = 0;
int result = AssocQueryStringW(flags, str, pszAssoc, pszExtra, null, ref count);
if (result != 1)
return $"Didn't get expected HRESULT (1) when getting char count. HRESULT was 0x{result:x8}";
string value = new string((char)0, (int)count - 1);
fixed(char* s = value)
{
result = AssocQueryStringW(flags, str, pszAssoc, pszExtra, s, ref count);
}
if (result != 0)
return $"Didn't get expected HRESULT (0), when getting char count. HRESULT was 0x{result:x8}";
return value;
}
private static string GetAssociationDetails()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Association details for '.txt'");
sb.AppendLine("------------------------------");
string open = GetAssociationString(0, 1 /* ASSOCSTR_COMMAND */, ".txt", "open");
sb.AppendFormat("Open command: {0}", open);
sb.AppendLine();
string progId = GetAssociationString(0, 20 /* ASSOCSTR_PROGID */, ".txt", null);
sb.AppendFormat("ProgID: {0}", progId);
sb.AppendLine();
return sb.ToString();
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsWindowsNanoServer))]
public void ShellExecute_Nano_Fails_Start()
{
string tempFile = GetTestFilePath() + ".txt";
File.Create(tempFile).Dispose();
ProcessStartInfo info = new ProcessStartInfo
{
UseShellExecute = true,
FileName = tempFile
};
Assert.Throws<PlatformNotSupportedException>(() => Process.Start(info));
}
public static TheoryData<bool> UseShellExecute
{
get
{
TheoryData<bool> data = new TheoryData<bool> { false };
if ( !PlatformDetection.IsUap // https://github.com/dotnet/corefx/issues/20204
&& !PlatformDetection.IsWindowsNanoServer) // By design
data.Add(true);
return data;
}
}
private const int ERROR_SUCCESS = 0x0;
private const int ERROR_FILE_NOT_FOUND = 0x2;
private const int ERROR_BAD_EXE_FORMAT = 0xC1;
[MemberData(nameof(UseShellExecute))]
[PlatformSpecific(TestPlatforms.Windows)]
public void StartInfo_BadVerb(bool useShellExecute)
{
ProcessStartInfo info = new ProcessStartInfo
{
UseShellExecute = useShellExecute,
FileName = @"foo.txt",
Verb = "Zlorp"
};
Assert.Equal(ERROR_FILE_NOT_FOUND, Assert.Throws<Win32Exception>(() => Process.Start(info)).NativeErrorCode);
}
[MemberData(nameof(UseShellExecute))]
[PlatformSpecific(TestPlatforms.Windows)]
public void StartInfo_BadExe(bool useShellExecute)
{
string tempFile = GetTestFilePath() + ".exe";
File.Create(tempFile).Dispose();
ProcessStartInfo info = new ProcessStartInfo
{
UseShellExecute = useShellExecute,
FileName = tempFile
};
int expected = ERROR_BAD_EXE_FORMAT;
// Windows Nano bug see #10290
if (PlatformDetection.IsWindowsNanoServer)
expected = ERROR_SUCCESS;
Assert.Equal(expected, Assert.Throws<Win32Exception>(() => Process.Start(info)).NativeErrorCode);
}
}
}
| |
// Copyright ?2004, 2013, Oracle and/or its affiliates. All rights reserved.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using MySql.Data.Common;
using System.Collections.Generic;
using System.Text;
using System;
using System.Data;
using System.Globalization;
using System.IO;
using MySql.Data.MySqlClient.Properties;
#if NET_40_OR_GREATER
using System.Threading.Tasks;
#endif
namespace MySql.Data.MySqlClient
{
/// <summary>
/// Provides a class capable of executing a SQL script containing
/// multiple SQL statements including CREATE PROCEDURE statements
/// that require changing the delimiter
/// </summary>
public class MySqlScript
{
private MySqlConnection connection;
private string query;
private string delimiter;
public event MySqlStatementExecutedEventHandler StatementExecuted;
public event MySqlScriptErrorEventHandler Error;
public event EventHandler ScriptCompleted;
#region Constructors
/// <summary>
/// Initializes a new instance of the
/// <see cref="MySqlScript"/> class.
/// </summary>
public MySqlScript()
{
Delimiter = ";";
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="MySqlScript"/> class.
/// </summary>
/// <param name="connection">The connection.</param>
public MySqlScript(MySqlConnection connection)
: this()
{
this.connection = connection;
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="MySqlScript"/> class.
/// </summary>
/// <param name="query">The query.</param>
public MySqlScript(string query)
: this()
{
this.query = query;
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="MySqlScript"/> class.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="query">The query.</param>
public MySqlScript(MySqlConnection connection, string query)
: this()
{
this.connection = connection;
this.query = query;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the connection.
/// </summary>
/// <value>The connection.</value>
public MySqlConnection Connection
{
get { return connection; }
set { connection = value; }
}
/// <summary>
/// Gets or sets the query.
/// </summary>
/// <value>The query.</value>
public string Query
{
get { return query; }
set { query = value; }
}
/// <summary>
/// Gets or sets the delimiter.
/// </summary>
/// <value>The delimiter.</value>
public string Delimiter
{
get { return delimiter; }
set { delimiter = value; }
}
#endregion
#region Public Methods
/// <summary>
/// Executes this instance.
/// </summary>
/// <returns>The number of statements executed as part of the script.</returns>
public int Execute()
{
bool openedConnection = false;
if (connection == null)
throw new InvalidOperationException(Resources.ConnectionNotSet);
if (query == null || query.Length == 0)
return 0;
// next we open up the connetion if it is not already open
if (connection.State != ConnectionState.Open)
{
openedConnection = true;
connection.Open();
}
// since we don't allow setting of parameters on a script we can
// therefore safely allow the use of user variables. no one should be using
// this connection while we are using it so we can temporarily tell it
// to allow the use of user variables
bool allowUserVars = connection.Settings.AllowUserVariables;
connection.Settings.AllowUserVariables = true;
try
{
string mode = connection.driver.Property("sql_mode");
mode = StringUtility.ToUpperInvariant(mode);
bool ansiQuotes = mode.IndexOf("ANSI_QUOTES") != -1;
bool noBackslashEscapes = mode.IndexOf("NO_BACKSLASH_ESCAPES") != -1;
// first we break the query up into smaller queries
List<ScriptStatement> statements = BreakIntoStatements(ansiQuotes, noBackslashEscapes);
int count = 0;
MySqlCommand cmd = new MySqlCommand(null, connection);
foreach (ScriptStatement statement in statements)
{
if (String.IsNullOrEmpty(statement.text)) continue;
cmd.CommandText = statement.text;
try
{
cmd.ExecuteNonQuery();
count++;
OnQueryExecuted(statement);
}
catch (Exception ex)
{
if (Error == null)
throw;
if (!OnScriptError(ex))
break;
}
}
OnScriptCompleted();
return count;
}
finally
{
connection.Settings.AllowUserVariables = allowUserVars;
if (openedConnection)
{
connection.Close();
}
}
}
#endregion
private void OnQueryExecuted(ScriptStatement statement)
{
if (StatementExecuted != null)
{
MySqlScriptEventArgs args = new MySqlScriptEventArgs();
args.Statement = statement;
StatementExecuted(this, args);
}
}
private void OnScriptCompleted()
{
if (ScriptCompleted != null)
ScriptCompleted(this, EventArgs.Empty);
}
private bool OnScriptError(Exception ex)
{
if (Error != null)
{
MySqlScriptErrorEventArgs args = new MySqlScriptErrorEventArgs(ex);
Error(this, args);
return args.Ignore;
}
return false;
}
private List<int> BreakScriptIntoLines()
{
List<int> lineNumbers = new List<int>();
StringReader sr = new StringReader(query);
string line = sr.ReadLine();
int pos = 0;
while (line != null)
{
lineNumbers.Add(pos);
pos += line.Length;
line = sr.ReadLine();
}
return lineNumbers;
}
private static int FindLineNumber(int position, List<int> lineNumbers)
{
int i = 0;
while (i < lineNumbers.Count && position < lineNumbers[i])
i++;
return i;
}
private List<ScriptStatement> BreakIntoStatements(bool ansiQuotes, bool noBackslashEscapes)
{
string currentDelimiter = Delimiter;
int startPos = 0;
List<ScriptStatement> statements = new List<ScriptStatement>();
List<int> lineNumbers = BreakScriptIntoLines();
MySqlTokenizer tokenizer = new MySqlTokenizer(query);
tokenizer.AnsiQuotes = ansiQuotes;
tokenizer.BackslashEscapes = !noBackslashEscapes;
string token = tokenizer.NextToken();
while (token != null)
{
if (!tokenizer.Quoted)
{
if (token.ToLower(CultureInfo.InvariantCulture) == "delimiter")
{
tokenizer.NextToken();
AdjustDelimiterEnd(tokenizer);
currentDelimiter = query.Substring(tokenizer.StartIndex,
tokenizer.StopIndex - tokenizer.StartIndex).Trim();
startPos = tokenizer.StopIndex;
}
else
{
// this handles the case where our tokenizer reads part of the
// delimiter
if (currentDelimiter.StartsWith(token, StringComparison.OrdinalIgnoreCase))
{
if ((tokenizer.StartIndex + currentDelimiter.Length) <= query.Length)
{
if (query.Substring(tokenizer.StartIndex, currentDelimiter.Length) == currentDelimiter)
{
token = currentDelimiter;
tokenizer.Position = tokenizer.StartIndex + currentDelimiter.Length;
tokenizer.StopIndex = tokenizer.Position;
}
}
}
int delimiterPos = token.IndexOf(currentDelimiter, StringComparison.OrdinalIgnoreCase);
if (delimiterPos != -1)
{
int endPos = tokenizer.StopIndex - token.Length + delimiterPos;
if (tokenizer.StopIndex == query.Length - 1)
endPos++;
string currentQuery = query.Substring(startPos, endPos - startPos);
ScriptStatement statement = new ScriptStatement();
statement.text = currentQuery.Trim();
statement.line = FindLineNumber(startPos, lineNumbers);
statement.position = startPos - lineNumbers[statement.line];
statements.Add(statement);
startPos = endPos + currentDelimiter.Length;
}
}
}
token = tokenizer.NextToken();
}
// now clean up the last statement
if (startPos < query.Length - 1)
{
string sqlLeftOver = query.Substring(startPos).Trim();
if (!String.IsNullOrEmpty(sqlLeftOver))
{
ScriptStatement statement = new ScriptStatement();
statement.text = sqlLeftOver;
statement.line = FindLineNumber(startPos, lineNumbers);
statement.position = startPos - lineNumbers[statement.line];
statements.Add(statement);
}
}
return statements;
}
private void AdjustDelimiterEnd(MySqlTokenizer tokenizer)
{
if (tokenizer.StopIndex < query.Length)
{
int pos = tokenizer.StopIndex;
char c = query[pos];
while (!Char.IsWhiteSpace(c) && pos < (query.Length - 1))
{
c = query[++pos];
}
tokenizer.StopIndex = pos;
tokenizer.Position = pos;
}
}
#if NET_40_OR_GREATER
#region Async
/// <summary>
/// Async version of Execute
/// </summary>
/// <returns>The number of statements executed as part of the script inside.</returns>
public Task<int> ExecuteAsync()
{
return Task.Factory.StartNew(() =>
{
return Execute();
});
}
#endregion
#endif
}
/// <summary>
///
/// </summary>
public delegate void MySqlStatementExecutedEventHandler(object sender, MySqlScriptEventArgs args);
/// <summary>
///
/// </summary>
public delegate void MySqlScriptErrorEventHandler(object sender, MySqlScriptErrorEventArgs args);
/// <summary>
///
/// </summary>
public class MySqlScriptEventArgs : EventArgs
{
private ScriptStatement statement;
internal ScriptStatement Statement
{
set { this.statement = value; }
}
/// <summary>
/// Gets the statement text.
/// </summary>
/// <value>The statement text.</value>
public string StatementText
{
get { return statement.text; }
}
/// <summary>
/// Gets the line.
/// </summary>
/// <value>The line.</value>
public int Line
{
get { return statement.line; }
}
/// <summary>
/// Gets the position.
/// </summary>
/// <value>The position.</value>
public int Position
{
get { return statement.position; }
}
}
/// <summary>
///
/// </summary>
public class MySqlScriptErrorEventArgs : MySqlScriptEventArgs
{
private Exception exception;
private bool ignore;
/// <summary>
/// Initializes a new instance of the <see cref="MySqlScriptErrorEventArgs"/> class.
/// </summary>
/// <param name="exception">The exception.</param>
public MySqlScriptErrorEventArgs(Exception exception)
: base()
{
this.exception = exception;
}
/// <summary>
/// Gets the exception.
/// </summary>
/// <value>The exception.</value>
public Exception Exception
{
get { return exception; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="MySqlScriptErrorEventArgs"/> is ignore.
/// </summary>
/// <value><c>true</c> if ignore; otherwise, <c>false</c>.</value>
public bool Ignore
{
get { return ignore; }
set { ignore = value; }
}
}
struct ScriptStatement
{
public string text;
public int line;
public int position;
}
}
| |
/*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using Box2D.XNA.TestBed.Framework;
using Box2D.XNA.TestBed.Tests;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Box2D.XNA.TestBed
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferMultiSampling = true;
this.IsMouseVisible = true;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
base.Initialize();
et = new EventTrace(this);
TraceEvents.Register(et);
testCount = 0;
while (TestEntries.g_testEntries[testCount].createFcn != null)
{
++testCount;
}
testIndex = MathUtils.Clamp(testIndex, 0, testCount - 1);
testSelection = testIndex;
entry = TestEntries.g_testEntries[testIndex];
test = entry.createFcn();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
spriteFont = Content.Load<SpriteFont>("font");
basicEffect = new BasicEffect(GraphicsDevice);
basicEffect.VertexColorEnabled = true;
Framework.DebugDraw._device = GraphicsDevice;
Framework.DebugDraw._batch = spriteBatch;
Framework.DebugDraw._font = spriteFont;
oldState = Keyboard.GetState();
oldGamePad = GamePad.GetState(PlayerIndex.One);
Resize(GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
et.BeginTrace(TraceEvents.UpdateEventId);
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
KeyboardState newState = Keyboard.GetState();
GamePadState newGamePad = GamePad.GetState(PlayerIndex.One);
MouseState newMouse = Mouse.GetState();
HandleMouse(ref newMouse, ref oldMouse, newState.IsKeyDown(Keys.LeftShift));
// Press 'z' to zoom out.
if (newState.IsKeyDown(Keys.Z) && oldState.IsKeyUp(Keys.Z))
{
viewZoom = Math.Min(1.1f * viewZoom, 20.0f);
Resize(width, height);
}
// Press 'x' to zoom in.
else if (newState.IsKeyDown(Keys.X) && oldState.IsKeyUp(Keys.X))
{
viewZoom = Math.Max(0.9f * viewZoom, 0.02f);
Resize(width, height);
}
// Press 'r' to reset.
else if (newState.IsKeyDown(Keys.R) && oldState.IsKeyUp(Keys.R))
{
test = entry.createFcn();
}
// Press space to launch a bomb.
else if ((newState.IsKeyDown(Keys.Space) && oldState.IsKeyUp(Keys.Space)) ||
newGamePad.IsButtonDown(Buttons.B) && oldGamePad.IsButtonUp(Buttons.B))
{
if (test != null)
{
test.LaunchBomb();
}
}
else if ((newState.IsKeyDown(Keys.P) && oldState.IsKeyUp(Keys.P)) ||
newGamePad.IsButtonDown(Buttons.Start) && oldGamePad.IsButtonUp(Buttons.Start))
{
settings.pause = settings.pause > (uint)0 ? (uint)1 : (uint)0;
}
// Press [ to prev test.
else if ((newState.IsKeyDown(Keys.OemOpenBrackets) && oldState.IsKeyUp(Keys.OemOpenBrackets)) ||
newGamePad.IsButtonDown(Buttons.LeftShoulder) && oldGamePad.IsButtonUp(Buttons.LeftShoulder))
{
--testSelection;
if (testSelection < 0)
{
testSelection = testCount - 1;
}
}
// Press ] to next test.
else if ((newState.IsKeyDown(Keys.OemCloseBrackets) && oldState.IsKeyUp(Keys.OemCloseBrackets)) ||
newGamePad.IsButtonDown(Buttons.RightShoulder) && oldGamePad.IsButtonUp(Buttons.RightShoulder))
{
++testSelection;
if (testSelection == testCount)
{
testSelection = 0;
}
}
// Press left to pan left.
else if (newState.IsKeyDown(Keys.Left) && oldState.IsKeyUp(Keys.Left))
{
viewCenter.X -= 0.5f;
Resize(width, height);
}
// Press right to pan right.
else if (newState.IsKeyDown(Keys.Right) && oldState.IsKeyUp(Keys.Right))
{
viewCenter.X += 0.5f;
Resize(width, height);
}
// Press down to pan down.
else if (newState.IsKeyDown(Keys.Down) && oldState.IsKeyUp(Keys.Down))
{
viewCenter.Y -= 0.5f;
Resize(width, height);
}
// Press up to pan up.
else if (newState.IsKeyDown(Keys.Up) && oldState.IsKeyUp(Keys.Up))
{
viewCenter.Y += 0.5f;
Resize(width, height);
}
// Press home to reset the view.
else if (newState.IsKeyDown(Keys.Home) && oldState.IsKeyUp(Keys.Home))
{
viewZoom = 1.0f;
viewCenter = new Vector2(0.0f, 20.0f);
Resize(width, height);
}
else
{
if (test != null)
{
test.Keyboard(newState, oldState);
}
}
base.Update(gameTime);
oldState = newState;
oldGamePad = newGamePad;
oldMouse = newMouse;
et.EndTrace(TraceEvents.UpdateEventId);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
et.BeginTrace(TraceEvents.DrawEventId);
GraphicsDevice.Clear(Color.Black);
basicEffect.Techniques[0].Passes[0].Apply();
test.SetTextLine(30);
settings.hz = settingsHz;
et.BeginTrace(TraceEvents.PhysicsEventId);
test.Step(settings);
et.EndTrace(TraceEvents.PhysicsEventId);
test.DrawTitle(50, 15, entry.name);
if (testSelection != testIndex)
{
testIndex = testSelection;
entry = TestEntries.g_testEntries[testIndex];
test = entry.createFcn();
viewZoom = 1.0f;
viewCenter = new Vector2(0.0f, 20.0f);
Resize(width, height);
}
test._debugDraw.FinishDrawShapes();
if (test != null)
{
spriteBatch.Begin();
test._debugDraw.FinishDrawString();
spriteBatch.End();
}
base.Draw(gameTime);
et.EndTrace(TraceEvents.DrawEventId);
et.EndTrace(TraceEvents.FrameEventId);
et.ResetFrame();
et.BeginTrace(TraceEvents.FrameEventId);
}
void Resize(int w, int h)
{
width = w;
height = h;
tw = GraphicsDevice.Viewport.Width;
th = GraphicsDevice.Viewport.Height;
int x = GraphicsDevice.Viewport.X;
int y = GraphicsDevice.Viewport.Y;
float ratio = (float)tw / (float)th;
Vector2 extents = new Vector2(ratio * 25.0f, 25.0f);
extents *= viewZoom;
Vector2 lower = viewCenter - extents;
Vector2 upper = viewCenter + extents;
// L/R/B/T
basicEffect.Projection = Matrix.CreateOrthographicOffCenter(lower.X, upper.X, lower.Y, upper.Y, -1, 1);
}
Vector2 ConvertScreenToWorld(int x, int y)
{
float u = x / (float)tw;
float v = (th - y) / (float)th;
float ratio = (float)tw / (float)th;
Vector2 extents = new Vector2(ratio * 25.0f, 25.0f);
extents *= viewZoom;
Vector2 lower = viewCenter - extents;
Vector2 upper = viewCenter + extents;
Vector2 p = new Vector2();
p.X = (1.0f - u) * lower.X + u * upper.X;
p.Y = (1.0f - v) * lower.Y + v * upper.Y;
return p;
}
void HandleMouse(ref MouseState state, ref MouseState oldState, bool shift)
{
Vector2 p = ConvertScreenToWorld(state.X, state.Y);
Vector2 oldp = ConvertScreenToWorld(oldState.X, oldState.Y);
if (state.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released)
{
if (shift)
test.ShiftMouseDown(p);
else
test.MouseDown(p);
}
if (p != oldp)
test.MouseMove(p);
if (state.LeftButton == ButtonState.Released && oldState.LeftButton == ButtonState.Pressed)
{
test.MouseUp(p);
}
if (state.RightButton == ButtonState.Pressed && oldState.RightButton == ButtonState.Released)
{
lastp = p;
rMouseDown = true;
}
else if (state.RightButton == ButtonState.Released && oldState.RightButton == ButtonState.Pressed)
{
rMouseDown = false;
}
if (rMouseDown)
{
Vector2 diff = p - lastp;
viewCenter.X -= diff.X;
viewCenter.Y -= diff.Y;
Resize(width, height);
}
else if (state.ScrollWheelValue != oldState.ScrollWheelValue)
{
var direction = state.ScrollWheelValue - oldState.ScrollWheelValue;
if (direction > 0)
{
viewZoom /= 1.1f;
}
else
{
viewZoom *= 1.1f;
}
Resize(width, height);
}
lastp = ConvertScreenToWorld(state.X, state.Y);
}
void Restart()
{
entry = TestEntries.g_testEntries[testIndex];
test = entry.createFcn();
Resize(width, height);
}
void Pause()
{
settings.pause = (uint)(settings.pause > 0 ? 0 : 1);
}
void SingleStep()
{
settings.pause = 1;
settings.singleStep = 1;
}
int testIndex = 0;
int testSelection = 0;
int testCount = 0;
TestEntry entry;
Test test;
Framework.Settings settings = new Framework.Settings();
int width = 640;
int height = 480;
int framePeriod = 16;
float settingsHz = 60.0f;
float viewZoom = 1.0f;
Vector2 viewCenter = new Vector2(0.0f, 20.0f);
int tx, ty, tw, th;
bool rMouseDown;
Vector2 lastp;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
BasicEffect basicEffect;
SpriteFont spriteFont;
KeyboardState oldState;
GamePadState oldGamePad;
MouseState oldMouse;
IEventTrace et;
}
}
| |
/***************************************************************************
* TargetService.cs
*
* Copyright (C) 2007 Novell, Inc.
* Written by Calvin Gaisford <calvinrg@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using Gtk;
namespace Giver
{
///<summary>
/// TargetWindow
/// Window holding all drop targets for giver
///</summary>
public enum DragTargetType
{
UriList,
TomBoyNote
};
/// <summary>
/// Widget used to show Avahi Services for Giver
/// </summary>
public class TargetService : Gtk.Button
{
private ServiceInfo serviceInfo;
private bool isManual;
private Gtk.Image image;
private double progressFraction;
private bool updateProgress;
private ProgressBar progressBar;
private Label progressLabel;
public TargetService(ServiceInfo serviceInfo)
{
this.serviceInfo = serviceInfo;
isManual = false;
Init();
}
public TargetService()
{
isManual = true;
Init();
}
private void Init()
{
this.BorderWidth = 0;
this.Relief = Gtk.ReliefStyle.None;
this.CanFocus = false;
progressFraction = 0;
updateProgress = false;
VBox outerVBox = new VBox (false, 4);
HBox hbox = new HBox(false, 10);
if(isManual) {
image = new Gtk.Image(Utilities.GetIcon("computer", 48));
} else {
if(serviceInfo.Photo != null)
image = new Gtk.Image(serviceInfo.Photo);
else
image = new Gtk.Image(Utilities.GetIcon("giver-48", 48));
}
hbox.PackStart(image, false, false, 0);
VBox vbox = new VBox();
hbox.PackStart(vbox, false, false, 0);
Label label = new Label();
label.Justify = Gtk.Justification.Left;
label.SetAlignment (0.0f, 0.5f);
label.LineWrap = false;
label.UseMarkup = true;
label.UseUnderline = false;
if(isManual)
label.Markup = "<span weight=\"bold\" size=\"large\">User Specified</span>";
else
label.Markup = string.Format ("<span weight=\"bold\" size=\"large\">{0}</span>",
serviceInfo.UserName);
vbox.PackStart(label, true, true, 0);
label = new Label();
label.Justify = Gtk.Justification.Left;
label.SetAlignment (0.0f, 0.5f);
label.UseMarkup = true;
label.UseUnderline = false;
if(isManual) {
label.LineWrap = true;
label.Markup = "<span style=\"italic\" size=\"small\">Use this recipient to enter\ninformation manually.</span>";
} else {
label.LineWrap = false;
label.Markup = string.Format ("<span size=\"small\">{0}</span>",
serviceInfo.MachineName);
}
vbox.PackStart(label, true, true, 0);
if(!isManual) {
label = new Label();
label.Justify = Gtk.Justification.Left;
label.SetAlignment (0.0f, 0.5f);
label.LineWrap = false;
label.UseMarkup = true;
label.UseUnderline = false;
label.Markup = string.Format ("<span style=\"italic\" size=\"small\">{0}:{1}</span>",
serviceInfo.Address, serviceInfo.Port);
vbox.PackStart(label, true, true, 0);
}
hbox.ShowAll();
outerVBox.PackStart (hbox, true, true, 0);
progressBar = new ProgressBar ();
progressBar.Orientation = ProgressBarOrientation.LeftToRight;
progressBar.BarStyle = ProgressBarStyle.Continuous;
progressBar.NoShowAll = true;
outerVBox.PackStart (progressBar, true, false, 0);
progressLabel = new Label ();
progressLabel.UseMarkup = true;
progressLabel.Xalign = 0;
progressLabel.UseUnderline = false;
progressLabel.LineWrap = true;
progressLabel.Wrap = true;
progressLabel.NoShowAll = true;
progressLabel.Ellipsize = Pango.EllipsizeMode.End;
outerVBox.PackStart (progressLabel, false, false, 0);
outerVBox.ShowAll ();
Add(outerVBox);
TargetEntry[] targets = new TargetEntry[] {
new TargetEntry ("text/uri-list", 0, (uint) DragTargetType.UriList) };
this.DragDataReceived += DragDataReceivedHandler;
Gtk.Drag.DestSet(this,
DestDefaults.All | DestDefaults.Highlight,
targets,
Gdk.DragAction.Copy | Gdk.DragAction.Move );
}
private void DragDataReceivedHandler (object o, DragDataReceivedArgs args)
{
//args.Context.
switch(args.Info) {
case (uint) DragTargetType.UriList:
{
UriList uriList = new UriList(args.SelectionData);
string[] paths = uriList.ToLocalPaths();
if(paths.Length > 0)
{
if(!isManual) {
Application.EnqueueFileSend(serviceInfo, uriList.ToLocalPaths());
} else {
// Prompt for the info to send here
}
} else {
// check for a tomboy notes
foreach(Uri uri in uriList) {
if( (uri.Scheme.CompareTo("note") == 0) &&
(uri.Host.CompareTo("tomboy") == 0) ) {
string[] files = new string[1];
string tomboyID = uri.AbsolutePath.Substring(1);
string homeFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string path = System.IO.Path.Combine(homeFolder, ".tomboy");
path = System.IO.Path.Combine(path, tomboyID + ".note");
files[0] = path;
Logger.Debug("Go and get the tomboy note {0}", path);
Application.EnqueueFileSend(serviceInfo, files);
}
else if(uri.Scheme.CompareTo("tasque") == 0) {
string[] files = new string[1];
string taskFile = uri.AbsolutePath.Substring(1);
string path = System.IO.Path.Combine("/", taskFile);
files[0] = path;
Logger.Debug("Go and get the task file {0}", path);
Application.EnqueueFileSend(serviceInfo, files);
}
}
}
break;
}
default:
break;
}
//Logger.Debug("DragDataReceivedHandler called");
Gtk.Drag.Finish (args.Context, true, false, args.Time);
}
private void OnSendFile (object sender, EventArgs args)
{
FileChooserDialog chooser = new FileChooserDialog(
Services.PlatformService.GetString("File to Give"),
null,
FileChooserAction.Open
);
chooser.SetCurrentFolder(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
chooser.AddButton(Stock.Cancel, ResponseType.Cancel);
chooser.AddButton(Services.PlatformService.GetString("Give"), ResponseType.Ok);
chooser.DefaultResponse = ResponseType.Ok;
chooser.LocalOnly = true;
if(chooser.Run() == (int)ResponseType.Ok) {
Logger.Debug("Giving file {0}", chooser.Filename);
if(!isManual) {
Application.EnqueueFileSend(serviceInfo, chooser.Filenames);
} else {
// Prompt for the info to send here
}
}
chooser.Destroy();
}
private void OnSendFolder (object sender, EventArgs args)
{
FileChooserDialog chooser = new FileChooserDialog(
Services.PlatformService.GetString("Folder to Give"),
null,
FileChooserAction.SelectFolder
);
chooser.SetCurrentFolder(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
chooser.AddButton(Stock.Cancel, ResponseType.Cancel);
chooser.AddButton(Services.PlatformService.GetString("Give"), ResponseType.Ok);
chooser.DefaultResponse = ResponseType.Ok;
chooser.LocalOnly = true;
if(chooser.Run() == (int)ResponseType.Ok) {
if(!isManual) {
Giver.Application.EnqueueFileSend(serviceInfo, chooser.Filenames);
} else {
// Prompt for the info to send here
}
}
chooser.Destroy();
}
#region Overrides
protected override void OnClicked ()
{
Menu popupMenu = new Menu ();
ImageMenuItem item;
item = new ImageMenuItem ("Give a File...");
item.Image = new Image(Gtk.Stock.File, IconSize.Button);
item.Activated += OnSendFile;
popupMenu.Add (item);
item = new ImageMenuItem("Give a Folder...");
item.Image = new Image(Gtk.Stock.Directory, IconSize.Button);
item.Activated += OnSendFolder;
popupMenu.Add (item);
popupMenu.ShowAll();
popupMenu.Popup ();
}
#endregion
#region Event Handlers
private void FileTransferStartedHandler (TransferStatusArgs args)
{
Gtk.Application.Invoke ( delegate {
ProgressText = Services.PlatformService.GetString ("Giving: {0}",
args.Name);
progressBar.Text = Services.PlatformService.GetString ("{0} of {1}",
args.CurrentCount,
args.TotalCount);
});
if(!updateProgress) {
updateProgress = true;
GLib.Timeout.Add(50, UpdateProgressBar);
}
}
private void TransferProgressHandler (TransferStatusArgs args)
{
progressFraction = ((double)args.TotalBytesTransferred) / ((double)args.TotalBytes);
}
private bool UpdateProgressBar()
{
if(updateProgress) {
Gtk.Application.Invoke (delegate {
progressBar.Fraction = progressFraction;
});
}
return updateProgress;
}
private void TransferEndedHandler (TransferStatusArgs args)
{
updateProgress = false;
Giver.Application.Instance.FileTransferStarted -= FileTransferStartedHandler;
Giver.Application.Instance.TransferProgress -= TransferProgressHandler;
Giver.Application.Instance.TransferEnded -= TransferEndedHandler;
Gtk.Application.Invoke (delegate {
progressBar.Hide ();
ProgressText = string.Empty;
progressLabel.Hide ();
});
}
#endregion
#region Public Properties
public string ProgressText
{
set {
progressLabel.Markup =
string.Format ("<span size=\"small\" style=\"italic\">{0}</span>",
value);
}
}
#endregion
#region Public Methods
public void UpdateImage (Gdk.Pixbuf newImage)
{
Logger.Debug ("TargetService::UpdateImage called");
this.image.FromPixbuf = newImage;
}
public void SetupTransferEventHandlers ()
{
Gtk.Application.Invoke ( delegate {
progressBar.Show ();
progressLabel.Show ();
});
Giver.Application.Instance.FileTransferStarted += FileTransferStartedHandler;
Giver.Application.Instance.TransferProgress += TransferProgressHandler;
Giver.Application.Instance.TransferEnded += TransferEndedHandler;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Util.Fst
{
/*
* 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 DataInput = Lucene.Net.Store.DataInput;
using DataOutput = Lucene.Net.Store.DataOutput;
// TODO: merge with PagedBytes, except PagedBytes doesn't
// let you read while writing which FST needs
internal class BytesStore : DataOutput
{
private readonly List<byte[]> blocks = new List<byte[]>();
private readonly int blockSize;
private readonly int blockBits;
private readonly int blockMask;
private byte[] current;
private int nextWrite;
public BytesStore(int blockBits)
{
this.blockBits = blockBits;
blockSize = 1 << blockBits;
blockMask = blockSize - 1;
nextWrite = blockSize;
}
/// <summary>
/// Pulls bytes from the provided <see cref="Store.IndexInput"/>. </summary>
public BytesStore(DataInput @in, long numBytes, int maxBlockSize)
{
int blockSize = 2;
int blockBits = 1;
while (blockSize < numBytes && blockSize < maxBlockSize)
{
blockSize *= 2;
blockBits++;
}
this.blockBits = blockBits;
this.blockSize = blockSize;
this.blockMask = blockSize - 1;
long left = numBytes;
while (left > 0)
{
int chunk = (int)Math.Min(blockSize, left);
byte[] block = new byte[chunk];
@in.ReadBytes(block, 0, block.Length);
blocks.Add(block);
left -= chunk;
}
// So .getPosition still works
nextWrite = blocks[blocks.Count - 1].Length;
}
/// <summary>
/// Absolute write byte; you must ensure dest is < max
/// position written so far.
/// </summary>
public virtual void WriteByte(int dest, byte b)
{
int blockIndex = dest >> blockBits;
byte[] block = blocks[blockIndex];
block[dest & blockMask] = b;
}
public override void WriteByte(byte b)
{
if (nextWrite == blockSize)
{
current = new byte[blockSize];
blocks.Add(current);
nextWrite = 0;
}
current[nextWrite++] = b;
}
public override void WriteBytes(byte[] b, int offset, int len)
{
while (len > 0)
{
int chunk = blockSize - nextWrite;
if (len <= chunk)
{
System.Buffer.BlockCopy(b, offset, current, nextWrite, len);
nextWrite += len;
break;
}
else
{
if (chunk > 0)
{
Array.Copy(b, offset, current, nextWrite, chunk);
offset += chunk;
len -= chunk;
}
current = new byte[blockSize];
blocks.Add(current);
nextWrite = 0;
}
}
}
internal virtual int BlockBits
{
get
{
return blockBits;
}
}
/// <summary>
/// Absolute writeBytes without changing the current
/// position. Note: this cannot "grow" the bytes, so you
/// must only call it on already written parts.
/// </summary>
internal virtual void WriteBytes(long dest, byte[] b, int offset, int len)
{
//System.out.println(" BS.writeBytes dest=" + dest + " offset=" + offset + " len=" + len);
Debug.Assert(dest + len <= Position, "dest=" + dest + " pos=" + Position + " len=" + len);
// Note: weird: must go "backwards" because copyBytes
// calls us with overlapping src/dest. If we
// go forwards then we overwrite bytes before we can
// copy them:
/*
int blockIndex = dest >> blockBits;
int upto = dest & blockMask;
byte[] block = blocks.get(blockIndex);
while (len > 0) {
int chunk = blockSize - upto;
System.out.println(" cycle chunk=" + chunk + " len=" + len);
if (len <= chunk) {
System.arraycopy(b, offset, block, upto, len);
break;
} else {
System.arraycopy(b, offset, block, upto, chunk);
offset += chunk;
len -= chunk;
blockIndex++;
block = blocks.get(blockIndex);
upto = 0;
}
}
*/
long end = dest + len;
int blockIndex = (int)(end >> blockBits);
int downTo = (int)(end & blockMask);
if (downTo == 0)
{
blockIndex--;
downTo = blockSize;
}
byte[] block = blocks[blockIndex];
while (len > 0)
{
//System.out.println(" cycle downTo=" + downTo + " len=" + len);
if (len <= downTo)
{
//System.out.println(" final: offset=" + offset + " len=" + len + " dest=" + (downTo-len));
Array.Copy(b, offset, block, downTo - len, len);
break;
}
else
{
len -= downTo;
//System.out.println(" partial: offset=" + (offset + len) + " len=" + downTo + " dest=0");
Array.Copy(b, offset + len, block, 0, downTo);
blockIndex--;
block = blocks[blockIndex];
downTo = blockSize;
}
}
}
/// <summary>
/// Absolute copy bytes self to self, without changing the
/// position. Note: this cannot "grow" the bytes, so must
/// only call it on already written parts.
/// </summary>
public virtual void CopyBytes(long src, long dest, int len)
{
//System.out.println("BS.copyBytes src=" + src + " dest=" + dest + " len=" + len);
Debug.Assert(src < dest);
// Note: weird: must go "backwards" because copyBytes
// calls us with overlapping src/dest. If we
// go forwards then we overwrite bytes before we can
// copy them:
/*
int blockIndex = src >> blockBits;
int upto = src & blockMask;
byte[] block = blocks.get(blockIndex);
while (len > 0) {
int chunk = blockSize - upto;
System.out.println(" cycle: chunk=" + chunk + " len=" + len);
if (len <= chunk) {
writeBytes(dest, block, upto, len);
break;
} else {
writeBytes(dest, block, upto, chunk);
blockIndex++;
block = blocks.get(blockIndex);
upto = 0;
len -= chunk;
dest += chunk;
}
}
*/
long end = src + len;
int blockIndex = (int)(end >> blockBits);
int downTo = (int)(end & blockMask);
if (downTo == 0)
{
blockIndex--;
downTo = blockSize;
}
byte[] block = blocks[blockIndex];
while (len > 0)
{
//System.out.println(" cycle downTo=" + downTo);
if (len <= downTo)
{
//System.out.println(" finish");
WriteBytes(dest, block, downTo - len, len);
break;
}
else
{
//System.out.println(" partial");
len -= downTo;
WriteBytes(dest + len, block, 0, downTo);
blockIndex--;
block = blocks[blockIndex];
downTo = blockSize;
}
}
}
/// <summary>
/// Writes an <see cref="int"/> at the absolute position without
/// changing the current pointer.
/// <para/>
/// NOTE: This was writeInt() in Lucene
/// </summary>
public virtual void WriteInt32(long pos, int value)
{
int blockIndex = (int)(pos >> blockBits);
int upto = (int)(pos & blockMask);
byte[] block = blocks[blockIndex];
int shift = 24;
for (int i = 0; i < 4; i++)
{
block[upto++] = (byte)(value >> shift);
shift -= 8;
if (upto == blockSize)
{
upto = 0;
blockIndex++;
block = blocks[blockIndex];
}
}
}
/// <summary>
/// Reverse from <paramref name="srcPos"/>, inclusive, to <paramref name="destPos"/>, inclusive. </summary>
public virtual void Reverse(long srcPos, long destPos)
{
Debug.Assert(srcPos < destPos);
Debug.Assert(destPos < Position);
//System.out.println("reverse src=" + srcPos + " dest=" + destPos);
int srcBlockIndex = (int)(srcPos >> blockBits);
int src = (int)(srcPos & blockMask);
byte[] srcBlock = blocks[srcBlockIndex];
int destBlockIndex = (int)(destPos >> blockBits);
int dest = (int)(destPos & blockMask);
byte[] destBlock = blocks[destBlockIndex];
//System.out.println(" srcBlock=" + srcBlockIndex + " destBlock=" + destBlockIndex);
int limit = (int)(destPos - srcPos + 1) / 2;
for (int i = 0; i < limit; i++)
{
//System.out.println(" cycle src=" + src + " dest=" + dest);
byte b = srcBlock[src];
srcBlock[src] = destBlock[dest];
destBlock[dest] = b;
src++;
if (src == blockSize)
{
srcBlockIndex++;
srcBlock = blocks[srcBlockIndex];
//System.out.println(" set destBlock=" + destBlock + " srcBlock=" + srcBlock);
src = 0;
}
dest--;
if (dest == -1)
{
destBlockIndex--;
destBlock = blocks[destBlockIndex];
//System.out.println(" set destBlock=" + destBlock + " srcBlock=" + srcBlock);
dest = blockSize - 1;
}
}
}
public virtual void SkipBytes(int len)
{
while (len > 0)
{
int chunk = blockSize - nextWrite;
if (len <= chunk)
{
nextWrite += len;
break;
}
else
{
len -= chunk;
current = new byte[blockSize];
blocks.Add(current);
nextWrite = 0;
}
}
}
public virtual long Position
{
get
{
return ((long)blocks.Count - 1) * blockSize + nextWrite;
}
}
/// <summary>
/// Pos must be less than the max position written so far!
/// i.e., you cannot "grow" the file with this!
/// </summary>
public virtual void Truncate(long newLen)
{
Debug.Assert(newLen <= Position);
Debug.Assert(newLen >= 0);
int blockIndex = (int)(newLen >> blockBits);
nextWrite = (int)(newLen & blockMask);
if (nextWrite == 0)
{
blockIndex--;
nextWrite = blockSize;
}
blocks.RemoveRange(blockIndex + 1, blocks.Count - (blockIndex + 1));
if (newLen == 0)
{
current = null;
}
else
{
current = blocks[blockIndex];
}
Debug.Assert(newLen == Position);
}
public virtual void Finish()
{
if (current != null)
{
byte[] lastBuffer = new byte[nextWrite];
Array.Copy(current, 0, lastBuffer, 0, nextWrite);
blocks[blocks.Count - 1] = lastBuffer;
current = null;
}
}
/// <summary>
/// Writes all of our bytes to the target <see cref="DataOutput"/>. </summary>
public virtual void WriteTo(DataOutput @out)
{
foreach (byte[] block in blocks)
{
@out.WriteBytes(block, 0, block.Length);
}
}
public virtual FST.BytesReader GetForwardReader()
{
if (blocks.Count == 1)
{
return new ForwardBytesReader(blocks[0]);
}
return new ForwardBytesReaderAnonymousInner(this);
}
private class ForwardBytesReaderAnonymousInner : FST.BytesReader
{
private readonly BytesStore outerInstance;
public ForwardBytesReaderAnonymousInner(BytesStore outerInstance)
{
this.outerInstance = outerInstance;
nextRead = outerInstance.blockSize;
}
private byte[] current;
private int nextBuffer;
private int nextRead;
public override byte ReadByte()
{
if (nextRead == outerInstance.blockSize)
{
current = outerInstance.blocks[nextBuffer++];
nextRead = 0;
}
return current[nextRead++];
}
public override void SkipBytes(int count)
{
Position = Position + count;
}
public override void ReadBytes(byte[] b, int offset, int len)
{
while (len > 0)
{
int chunkLeft = outerInstance.blockSize - nextRead;
if (len <= chunkLeft)
{
Array.Copy(current, nextRead, b, offset, len);
nextRead += len;
break;
}
else
{
if (chunkLeft > 0)
{
Array.Copy(current, nextRead, b, offset, chunkLeft);
offset += chunkLeft;
len -= chunkLeft;
}
current = outerInstance.blocks[nextBuffer++];
nextRead = 0;
}
}
}
public override long Position
{
get
{
return ((long)nextBuffer - 1) * outerInstance.blockSize + nextRead;
}
set
{
int bufferIndex = (int)(value >> outerInstance.blockBits);
nextBuffer = bufferIndex + 1;
current = outerInstance.blocks[bufferIndex];
nextRead = (int)(value & outerInstance.blockMask);
Debug.Assert(this.Position == value, "pos=" + value + " Position=" + this.Position);
}
}
public override bool IsReversed
{
get { return false; }
}
}
public virtual FST.BytesReader GetReverseReader()
{
return GetReverseReader(true);
}
internal virtual FST.BytesReader GetReverseReader(bool allowSingle)
{
if (allowSingle && blocks.Count == 1)
{
return new ReverseBytesReader(blocks[0]);
}
return new ReverseBytesReaderAnonymousInner(this);
}
private class ReverseBytesReaderAnonymousInner : FST.BytesReader
{
private readonly BytesStore outerInstance;
public ReverseBytesReaderAnonymousInner(BytesStore outerInstance)
{
this.outerInstance = outerInstance;
current = outerInstance.blocks.Count == 0 ? null : outerInstance.blocks[0];
nextBuffer = -1;
nextRead = 0;
}
private byte[] current;
private int nextBuffer;
private int nextRead;
public override byte ReadByte()
{
if (nextRead == -1)
{
current = outerInstance.blocks[nextBuffer--];
nextRead = outerInstance.blockSize - 1;
}
return current[nextRead--];
}
public override void SkipBytes(int count)
{
Position = Position - count;
}
public override void ReadBytes(byte[] b, int offset, int len)
{
for (int i = 0; i < len; i++)
{
b[offset + i] = ReadByte();
}
}
public override long Position
{
get
{
return ((long)nextBuffer + 1) * outerInstance.blockSize + nextRead;
}
set
{
// NOTE: a little weird because if you
// setPosition(0), the next byte you read is
// bytes[0] ... but I would expect bytes[-1] (ie,
// EOF)...?
int bufferIndex = (int)(value >> outerInstance.blockBits);
nextBuffer = bufferIndex - 1;
current = outerInstance.blocks[bufferIndex];
nextRead = (int)(value & outerInstance.blockMask);
Debug.Assert(this.Position == value, "value=" + value + " this.Position=" + this.Position);
}
}
public override bool IsReversed
{
get { return true; }
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
#if MS_IO_REDIST
using Microsoft.IO.Enumeration;
namespace Microsoft.IO
#else
using System.IO.Enumeration;
namespace System.IO
#endif
{
public sealed partial class DirectoryInfo : FileSystemInfo
{
public DirectoryInfo(string path)
{
Init(originalPath: path,
fullPath: Path.GetFullPath(path),
isNormalized: true);
}
internal DirectoryInfo(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
{
Init(originalPath, fullPath, fileName, isNormalized);
}
private void Init(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
{
// Want to throw the original argument name
OriginalPath = originalPath ?? throw new ArgumentNullException("path");
fullPath = fullPath ?? originalPath;
fullPath = isNormalized ? fullPath : Path.GetFullPath(fullPath);
_name = fileName ?? (PathInternal.IsRoot(fullPath.AsSpan()) ?
fullPath.AsSpan() :
Path.GetFileName(PathInternal.TrimEndingDirectorySeparator(fullPath.AsSpan()))).ToString();
FullPath = fullPath;
}
public DirectoryInfo Parent
{
get
{
// FullPath might end in either "parent\child" or "parent\child\", and in either case we want
// the parent of child, not the child. Trim off an ending directory separator if there is one,
// but don't mangle the root.
string parentName = Path.GetDirectoryName(PathInternal.IsRoot(FullPath.AsSpan()) ? FullPath : PathInternal.TrimEndingDirectorySeparator(FullPath));
return parentName != null ?
new DirectoryInfo(parentName, isNormalized: true) :
null;
}
}
public DirectoryInfo CreateSubdirectory(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (PathInternal.IsEffectivelyEmpty(path.AsSpan()))
throw new ArgumentException(SR.Argument_PathEmpty, nameof(path));
if (Path.IsPathRooted(path))
throw new ArgumentException(SR.Arg_Path2IsRooted, nameof(path));
string newPath = Path.GetFullPath(Path.Combine(FullPath, path));
ReadOnlySpan<char> trimmedNewPath = PathInternal.TrimEndingDirectorySeparator(newPath.AsSpan());
ReadOnlySpan<char> trimmedCurrentPath = PathInternal.TrimEndingDirectorySeparator(FullPath.AsSpan());
// We want to make sure the requested directory is actually under the subdirectory.
if (trimmedNewPath.StartsWith(trimmedCurrentPath, PathInternal.StringComparison)
// Allow the exact same path, but prevent allowing "..\FooBar" through when the directory is "Foo"
&& ((trimmedNewPath.Length == trimmedCurrentPath.Length) || PathInternal.IsDirectorySeparator(newPath[trimmedCurrentPath.Length])))
{
FileSystem.CreateDirectory(newPath);
return new DirectoryInfo(newPath);
}
// We weren't nested
throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, FullPath), nameof(path));
}
public void Create() => FileSystem.CreateDirectory(FullPath);
// Returns an array of Files in the DirectoryInfo specified by path
public FileInfo[] GetFiles() => GetFiles("*", enumerationOptions: EnumerationOptions.Compatible);
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
public FileInfo[] GetFiles(string searchPattern) => GetFiles(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption)
=> GetFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public FileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions)
=> ((IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions)).ToArray();
// Returns an array of strongly typed FileSystemInfo entries which will contain a listing
// of all the files and directories.
public FileSystemInfo[] GetFileSystemInfos() => GetFileSystemInfos("*", enumerationOptions: EnumerationOptions.Compatible);
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
public FileSystemInfo[] GetFileSystemInfos(string searchPattern)
=> GetFileSystemInfos(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption)
=> GetFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public FileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions).ToArray();
// Returns an array of Directories in the current directory.
public DirectoryInfo[] GetDirectories() => GetDirectories("*", enumerationOptions: EnumerationOptions.Compatible);
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32 directories).
public DirectoryInfo[] GetDirectories(string searchPattern) => GetDirectories(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption)
=> GetDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public DirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions)
=> ((IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Directories, enumerationOptions)).ToArray();
public IEnumerable<DirectoryInfo> EnumerateDirectories()
=> EnumerateDirectories("*", enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern)
=> EnumerateDirectories(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption)
=> EnumerateDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions)
=> (IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Directories, enumerationOptions);
public IEnumerable<FileInfo> EnumerateFiles()
=> EnumerateFiles("*", enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern) => EnumerateFiles(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption)
=> EnumerateFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions)
=> (IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions);
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() => EnumerateFileSystemInfos("*", enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern)
=> EnumerateFileSystemInfos(searchPattern, enumerationOptions: EnumerationOptions.Compatible);
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption)
=> EnumerateFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions)
=> InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions);
internal static IEnumerable<FileSystemInfo> InternalEnumerateInfos(
string path,
string searchPattern,
SearchTarget searchTarget,
EnumerationOptions options)
{
Debug.Assert(path != null);
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options);
switch (searchTarget)
{
case SearchTarget.Directories:
return FileSystemEnumerableFactory.DirectoryInfos(path, searchPattern, options);
case SearchTarget.Files:
return FileSystemEnumerableFactory.FileInfos(path, searchPattern, options);
case SearchTarget.Both:
return FileSystemEnumerableFactory.FileSystemInfos(path, searchPattern, options);
default:
throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget));
}
}
public DirectoryInfo Root => new DirectoryInfo(Path.GetPathRoot(FullPath));
public void MoveTo(string destDirName)
{
if (destDirName == null)
throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName));
string destination = Path.GetFullPath(destDirName);
string destinationWithSeparator = PathInternal.EnsureTrailingSeparator(destination);
string sourceWithSeparator = PathInternal.EnsureTrailingSeparator(FullPath);
if (string.Equals(sourceWithSeparator, destinationWithSeparator, PathInternal.StringComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
string sourceRoot = Path.GetPathRoot(sourceWithSeparator);
string destinationRoot = Path.GetPathRoot(destinationWithSeparator);
if (!string.Equals(sourceRoot, destinationRoot, PathInternal.StringComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
// Windows will throw if the source file/directory doesn't exist, we preemptively check
// to make sure our cross platform behavior matches NetFX behavior.
if (!Exists && !FileSystem.FileExists(FullPath))
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath));
if (FileSystem.DirectoryExists(destination))
throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator));
FileSystem.MoveDirectory(FullPath, destination);
Init(originalPath: destDirName,
fullPath: destinationWithSeparator,
fileName: null,
isNormalized: true);
// Flush any cached information about the directory.
Invalidate();
}
public override void Delete() => FileSystem.RemoveDirectory(FullPath, recursive: false);
public void Delete(bool recursive) => FileSystem.RemoveDirectory(FullPath, recursive);
}
}
| |
using System;
using Raksha.Crypto.Parameters;
namespace Raksha.Crypto.Engines
{
/**
* an implementation of Rijndael, based on the documentation and reference implementation
* by Paulo Barreto, Vincent Rijmen, for v2.0 August '99.
* <p>
* Note: this implementation is based on information prior to readonly NIST publication.
* </p>
*/
public class RijndaelEngine
: IBlockCipher
{
private static readonly int MAXROUNDS = 14;
private static readonly int MAXKC = (256/4);
private static readonly byte[] Logtable =
{
0, 0, 25, 1, 50, 2, 26, 198,
75, 199, 27, 104, 51, 238, 223, 3,
100, 4, 224, 14, 52, 141, 129, 239,
76, 113, 8, 200, 248, 105, 28, 193,
125, 194, 29, 181, 249, 185, 39, 106,
77, 228, 166, 114, 154, 201, 9, 120,
101, 47, 138, 5, 33, 15, 225, 36,
18, 240, 130, 69, 53, 147, 218, 142,
150, 143, 219, 189, 54, 208, 206, 148,
19, 92, 210, 241, 64, 70, 131, 56,
102, 221, 253, 48, 191, 6, 139, 98,
179, 37, 226, 152, 34, 136, 145, 16,
126, 110, 72, 195, 163, 182, 30, 66,
58, 107, 40, 84, 250, 133, 61, 186,
43, 121, 10, 21, 155, 159, 94, 202,
78, 212, 172, 229, 243, 115, 167, 87,
175, 88, 168, 80, 244, 234, 214, 116,
79, 174, 233, 213, 231, 230, 173, 232,
44, 215, 117, 122, 235, 22, 11, 245,
89, 203, 95, 176, 156, 169, 81, 160,
127, 12, 246, 111, 23, 196, 73, 236,
216, 67, 31, 45, 164, 118, 123, 183,
204, 187, 62, 90, 251, 96, 177, 134,
59, 82, 161, 108, 170, 85, 41, 157,
151, 178, 135, 144, 97, 190, 220, 252,
188, 149, 207, 205, 55, 63, 91, 209,
83, 57, 132, 60, 65, 162, 109, 71,
20, 42, 158, 93, 86, 242, 211, 171,
68, 17, 146, 217, 35, 32, 46, 137,
180, 124, 184, 38, 119, 153, 227, 165,
103, 74, 237, 222, 197, 49, 254, 24,
13, 99, 140, 128, 192, 247, 112, 7
};
private static readonly byte[] Alogtable =
{
0, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53,
95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170,
229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49,
83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205,
76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136,
131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154,
181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163,
254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160,
251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65,
195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117,
159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128,
155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84,
252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202,
69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14,
18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23,
57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1,
3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53,
95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170,
229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49,
83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205,
76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136,
131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154,
181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163,
254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160,
251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65,
195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117,
159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128,
155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84,
252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202,
69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14,
18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23,
57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1,
};
private static readonly byte[] S =
{
99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118,
202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192,
183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21,
4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117,
9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132,
83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207,
208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168,
81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210,
205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115,
96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121,
231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8,
186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138,
112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158,
225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22,
};
private static readonly byte[] Si =
{
82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251,
124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203,
84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78,
8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37,
114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146,
108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132,
144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6,
208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107,
58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115,
150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110,
71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27,
252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244,
31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95,
96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239,
160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97,
23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125,
};
private static readonly byte[] rcon =
{
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91
};
static readonly byte[][] shifts0 = new byte [][]
{
new byte[]{ 0, 8, 16, 24 },
new byte[]{ 0, 8, 16, 24 },
new byte[]{ 0, 8, 16, 24 },
new byte[]{ 0, 8, 16, 32 },
new byte[]{ 0, 8, 24, 32 }
};
static readonly byte[][] shifts1 =
{
new byte[]{ 0, 24, 16, 8 },
new byte[]{ 0, 32, 24, 16 },
new byte[]{ 0, 40, 32, 24 },
new byte[]{ 0, 48, 40, 24 },
new byte[]{ 0, 56, 40, 32 }
};
/**
* multiply two elements of GF(2^m)
* needed for MixColumn and InvMixColumn
*/
private byte Mul0x2(
int b)
{
if (b != 0)
{
return Alogtable[25 + (Logtable[b] & 0xff)];
}
else
{
return 0;
}
}
private byte Mul0x3(
int b)
{
if (b != 0)
{
return Alogtable[1 + (Logtable[b] & 0xff)];
}
else
{
return 0;
}
}
private byte Mul0x9(
int b)
{
if (b >= 0)
{
return Alogtable[199 + b];
}
else
{
return 0;
}
}
private byte Mul0xb(
int b)
{
if (b >= 0)
{
return Alogtable[104 + b];
}
else
{
return 0;
}
}
private byte Mul0xd(
int b)
{
if (b >= 0)
{
return Alogtable[238 + b];
}
else
{
return 0;
}
}
private byte Mul0xe(
int b)
{
if (b >= 0)
{
return Alogtable[223 + b];
}
else
{
return 0;
}
}
/**
* xor corresponding text input and round key input bytes
*/
private void KeyAddition(
long[] rk)
{
A0 ^= rk[0];
A1 ^= rk[1];
A2 ^= rk[2];
A3 ^= rk[3];
}
private long Shift(
long r,
int shift)
{
//return (((long)((ulong) r >> shift) | (r << (BC - shift)))) & BC_MASK;
ulong temp = (ulong) r >> shift;
// NB: This corrects for Mono Bug #79087 (fixed in 1.1.17)
if (shift > 31)
{
temp &= 0xFFFFFFFFUL;
}
return ((long) temp | (r << (BC - shift))) & BC_MASK;
}
/**
* Row 0 remains unchanged
* The other three rows are shifted a variable amount
*/
private void ShiftRow(
byte[] shiftsSC)
{
A1 = Shift(A1, shiftsSC[1]);
A2 = Shift(A2, shiftsSC[2]);
A3 = Shift(A3, shiftsSC[3]);
}
private long ApplyS(
long r,
byte[] box)
{
long res = 0;
for (int j = 0; j < BC; j += 8)
{
res |= (long)(box[(int)((r >> j) & 0xff)] & 0xff) << j;
}
return res;
}
/**
* Replace every byte of the input by the byte at that place
* in the nonlinear S-box
*/
private void Substitution(
byte[] box)
{
A0 = ApplyS(A0, box);
A1 = ApplyS(A1, box);
A2 = ApplyS(A2, box);
A3 = ApplyS(A3, box);
}
/**
* Mix the bytes of every column in a linear way
*/
private void MixColumn()
{
long r0, r1, r2, r3;
r0 = r1 = r2 = r3 = 0;
for (int j = 0; j < BC; j += 8)
{
int a0 = (int)((A0 >> j) & 0xff);
int a1 = (int)((A1 >> j) & 0xff);
int a2 = (int)((A2 >> j) & 0xff);
int a3 = (int)((A3 >> j) & 0xff);
r0 |= (long)((Mul0x2(a0) ^ Mul0x3(a1) ^ a2 ^ a3) & 0xff) << j;
r1 |= (long)((Mul0x2(a1) ^ Mul0x3(a2) ^ a3 ^ a0) & 0xff) << j;
r2 |= (long)((Mul0x2(a2) ^ Mul0x3(a3) ^ a0 ^ a1) & 0xff) << j;
r3 |= (long)((Mul0x2(a3) ^ Mul0x3(a0) ^ a1 ^ a2) & 0xff) << j;
}
A0 = r0;
A1 = r1;
A2 = r2;
A3 = r3;
}
/**
* Mix the bytes of every column in a linear way
* This is the opposite operation of Mixcolumn
*/
private void InvMixColumn()
{
long r0, r1, r2, r3;
r0 = r1 = r2 = r3 = 0;
for (int j = 0; j < BC; j += 8)
{
int a0 = (int)((A0 >> j) & 0xff);
int a1 = (int)((A1 >> j) & 0xff);
int a2 = (int)((A2 >> j) & 0xff);
int a3 = (int)((A3 >> j) & 0xff);
//
// pre-lookup the log table
//
a0 = (a0 != 0) ? (Logtable[a0 & 0xff] & 0xff) : -1;
a1 = (a1 != 0) ? (Logtable[a1 & 0xff] & 0xff) : -1;
a2 = (a2 != 0) ? (Logtable[a2 & 0xff] & 0xff) : -1;
a3 = (a3 != 0) ? (Logtable[a3 & 0xff] & 0xff) : -1;
r0 |= (long)((Mul0xe(a0) ^ Mul0xb(a1) ^ Mul0xd(a2) ^ Mul0x9(a3)) & 0xff) << j;
r1 |= (long)((Mul0xe(a1) ^ Mul0xb(a2) ^ Mul0xd(a3) ^ Mul0x9(a0)) & 0xff) << j;
r2 |= (long)((Mul0xe(a2) ^ Mul0xb(a3) ^ Mul0xd(a0) ^ Mul0x9(a1)) & 0xff) << j;
r3 |= (long)((Mul0xe(a3) ^ Mul0xb(a0) ^ Mul0xd(a1) ^ Mul0x9(a2)) & 0xff) << j;
}
A0 = r0;
A1 = r1;
A2 = r2;
A3 = r3;
}
/**
* Calculate the necessary round keys
* The number of calculations depends on keyBits and blockBits
*/
private long[][] GenerateWorkingKey(
byte[] key)
{
int KC;
int t, rconpointer = 0;
int keyBits = key.Length * 8;
byte[,] tk = new byte[4,MAXKC];
//long[,] W = new long[MAXROUNDS+1,4];
long[][] W = new long[MAXROUNDS+1][];
for (int i = 0; i < MAXROUNDS+1; i++) W[i] = new long[4];
switch (keyBits)
{
case 128:
KC = 4;
break;
case 160:
KC = 5;
break;
case 192:
KC = 6;
break;
case 224:
KC = 7;
break;
case 256:
KC = 8;
break;
default :
throw new ArgumentException("Key length not 128/160/192/224/256 bits.");
}
if (keyBits >= blockBits)
{
ROUNDS = KC + 6;
}
else
{
ROUNDS = (BC / 8) + 6;
}
//
// copy the key into the processing area
//
int index = 0;
for (int i = 0; i < key.Length; i++)
{
tk[i % 4,i / 4] = key[index++];
}
t = 0;
//
// copy values into round key array
//
for (int j = 0; (j < KC) && (t < (ROUNDS+1)*(BC / 8)); j++, t++)
{
for (int i = 0; i < 4; i++)
{
W[t / (BC / 8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % BC);
}
}
//
// while not enough round key material calculated
// calculate new values
//
while (t < (ROUNDS+1)*(BC/8))
{
for (int i = 0; i < 4; i++)
{
tk[i,0] ^= S[tk[(i+1)%4,KC-1] & 0xff];
}
tk[0,0] ^= (byte) rcon[rconpointer++];
if (KC <= 6)
{
for (int j = 1; j < KC; j++)
{
for (int i = 0; i < 4; i++)
{
tk[i,j] ^= tk[i,j-1];
}
}
}
else
{
for (int j = 1; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
tk[i,j] ^= tk[i,j-1];
}
}
for (int i = 0; i < 4; i++)
{
tk[i,4] ^= S[tk[i,3] & 0xff];
}
for (int j = 5; j < KC; j++)
{
for (int i = 0; i < 4; i++)
{
tk[i,j] ^= tk[i,j-1];
}
}
}
//
// copy values into round key array
//
for (int j = 0; (j < KC) && (t < (ROUNDS+1)*(BC/8)); j++, t++)
{
for (int i = 0; i < 4; i++)
{
W[t / (BC/8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % (BC));
}
}
}
return W;
}
private int BC;
private long BC_MASK;
private int ROUNDS;
private int blockBits;
private long[][] workingKey;
private long A0, A1, A2, A3;
private bool forEncryption;
private byte[] shifts0SC;
private byte[] shifts1SC;
/**
* default constructor - 128 bit block size.
*/
public RijndaelEngine() : this(128) {}
/**
* basic constructor - set the cipher up for a given blocksize
*
* @param blocksize the blocksize in bits, must be 128, 192, or 256.
*/
public RijndaelEngine(
int blockBits)
{
switch (blockBits)
{
case 128:
BC = 32;
BC_MASK = 0xffffffffL;
shifts0SC = shifts0[0];
shifts1SC = shifts1[0];
break;
case 160:
BC = 40;
BC_MASK = 0xffffffffffL;
shifts0SC = shifts0[1];
shifts1SC = shifts1[1];
break;
case 192:
BC = 48;
BC_MASK = 0xffffffffffffL;
shifts0SC = shifts0[2];
shifts1SC = shifts1[2];
break;
case 224:
BC = 56;
BC_MASK = 0xffffffffffffffL;
shifts0SC = shifts0[3];
shifts1SC = shifts1[3];
break;
case 256:
BC = 64;
BC_MASK = unchecked( (long)0xffffffffffffffffL);
shifts0SC = shifts0[4];
shifts1SC = shifts1[4];
break;
default:
throw new ArgumentException("unknown blocksize to Rijndael");
}
this.blockBits = blockBits;
}
/**
* initialise a Rijndael cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (parameters is KeyParameter)
{
workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey());
this.forEncryption = forEncryption;
return;
}
throw new ArgumentException("invalid parameter passed to Rijndael init - " + parameters.GetType().ToString());
}
public string AlgorithmName
{
get { return "Rijndael"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return BC / 2;
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (workingKey == null)
{
throw new InvalidOperationException("Rijndael engine not initialised");
}
if ((inOff + (BC / 2)) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + (BC / 2)) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
UnPackBlock(input, inOff);
if (forEncryption)
{
EncryptBlock(workingKey);
}
else
{
DecryptBlock(workingKey);
}
PackBlock(output, outOff);
return BC / 2;
}
public void Reset()
{
}
private void UnPackBlock(
byte[] bytes,
int off)
{
int index = off;
A0 = (long)(bytes[index++] & 0xff);
A1 = (long)(bytes[index++] & 0xff);
A2 = (long)(bytes[index++] & 0xff);
A3 = (long)(bytes[index++] & 0xff);
for (int j = 8; j != BC; j += 8)
{
A0 |= (long)(bytes[index++] & 0xff) << j;
A1 |= (long)(bytes[index++] & 0xff) << j;
A2 |= (long)(bytes[index++] & 0xff) << j;
A3 |= (long)(bytes[index++] & 0xff) << j;
}
}
private void PackBlock(
byte[] bytes,
int off)
{
int index = off;
for (int j = 0; j != BC; j += 8)
{
bytes[index++] = (byte)(A0 >> j);
bytes[index++] = (byte)(A1 >> j);
bytes[index++] = (byte)(A2 >> j);
bytes[index++] = (byte)(A3 >> j);
}
}
private void EncryptBlock(
long[][] rk)
{
int r;
//
// begin with a key addition
//
KeyAddition(rk[0]);
//
// ROUNDS-1 ordinary rounds
//
for (r = 1; r < ROUNDS; r++)
{
Substitution(S);
ShiftRow(shifts0SC);
MixColumn();
KeyAddition(rk[r]);
}
//
// Last round is special: there is no MixColumn
//
Substitution(S);
ShiftRow(shifts0SC);
KeyAddition(rk[ROUNDS]);
}
private void DecryptBlock(
long[][] rk)
{
int r;
// To decrypt: apply the inverse operations of the encrypt routine,
// in opposite order
//
// (KeyAddition is an involution: it 's equal to its inverse)
// (the inverse of Substitution with table S is Substitution with the inverse table of S)
// (the inverse of Shiftrow is Shiftrow over a suitable distance)
//
// First the special round:
// without InvMixColumn
// with extra KeyAddition
//
KeyAddition(rk[ROUNDS]);
Substitution(Si);
ShiftRow(shifts1SC);
//
// ROUNDS-1 ordinary rounds
//
for (r = ROUNDS-1; r > 0; r--)
{
KeyAddition(rk[r]);
InvMixColumn();
Substitution(Si);
ShiftRow(shifts1SC);
}
//
// End with the extra key addition
//
KeyAddition(rk[0]);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache.Affinity;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Log;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Impl.Unmanaged.Jni;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Resource;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// This class defines a factory for the main Ignite API.
/// <p/>
/// Use <see cref="Start()"/> method to start Ignite with default configuration.
/// <para/>
/// All members are thread-safe and may be used concurrently from multiple threads.
/// </summary>
public static class Ignition
{
/// <summary>
/// Default configuration section name.
/// </summary>
public const string ConfigurationSectionName = "igniteConfiguration";
/// <summary>
/// Default configuration section name.
/// </summary>
public const string ClientConfigurationSectionName = "igniteClientConfiguration";
/** */
private static readonly object SyncRoot = new object();
/** GC warning flag. */
private static int _gcWarn;
/** */
private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>();
/** Current DLL name. */
private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
/** Startup info. */
[ThreadStatic]
private static Startup _startup;
/** Client mode flag. */
[ThreadStatic]
private static bool _clientMode;
/// <summary>
/// Static initializer.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static Ignition()
{
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
}
/// <summary>
/// Gets or sets a value indicating whether Ignite should be started in client mode.
/// Client nodes cannot hold data in caches.
/// </summary>
public static bool ClientMode
{
get { return _clientMode; }
set { _clientMode = value; }
}
/// <summary>
/// Starts Ignite with default configuration. By default this method will
/// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c>
/// configuration file. If such file is not found, then all system defaults will be used.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite Start()
{
return Start(new IgniteConfiguration());
}
/// <summary>
/// Starts all grids specified within given Spring XML configuration file. If Ignite with given name
/// is already started, then exception is thrown. In this case all instances that may
/// have been started so far will be stopped too.
/// </summary>
/// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be
/// absolute or relative to IGNITE_HOME.</param>
/// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st
/// found instance is returned.</returns>
public static IIgnite Start(string springCfgPath)
{
return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath});
}
/// <summary>
/// Reads <see cref="IgniteConfiguration"/> from application configuration
/// <see cref="IgniteConfigurationSection"/> with <see cref="ConfigurationSectionName"/>
/// name and starts Ignite.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration()
{
// ReSharper disable once IntroduceOptionalParameters.Global
return StartFromApplicationConfiguration(ConfigurationSectionName);
}
/// <summary>
/// Reads <see cref="IgniteConfiguration"/> from application configuration
/// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration(string sectionName)
{
IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName");
var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection;
if (section == null)
throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'",
typeof(IgniteConfigurationSection).Name, sectionName));
if (section.IgniteConfiguration == null)
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteConfigurationSection).Name, sectionName));
return Start(section.IgniteConfiguration);
}
/// <summary>
/// Reads <see cref="IgniteConfiguration" /> from application configuration
/// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <param name="configPath">Path to the configuration file.</param>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration(string sectionName, string configPath)
{
var section = GetConfigurationSection<IgniteConfigurationSection>(sectionName, configPath);
if (section.IgniteConfiguration == null)
{
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteConfigurationSection).Name, sectionName, configPath));
}
return Start(section.IgniteConfiguration);
}
/// <summary>
/// Gets the configuration section.
/// </summary>
private static T GetConfigurationSection<T>(string sectionName, string configPath)
where T : class
{
IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName");
IgniteArgumentCheck.NotNullOrEmpty(configPath, "configPath");
var fileMap = GetConfigMap(configPath);
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var section = config.GetSection(sectionName) as T;
if (section == null)
{
throw new ConfigurationErrorsException(
string.Format("Could not find {0} with name '{1}' in file '{2}'",
typeof(T).Name, sectionName, configPath));
}
return section;
}
/// <summary>
/// Gets the configuration file map.
/// </summary>
private static ExeConfigurationFileMap GetConfigMap(string fileName)
{
var fullFileName = Path.GetFullPath(fileName);
if (!File.Exists(fullFileName))
throw new ConfigurationErrorsException("Specified config file does not exist: " + fileName);
return new ExeConfigurationFileMap { ExeConfigFilename = fullFileName };
}
/// <summary>
/// Starts Ignite with given configuration.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite Start(IgniteConfiguration cfg)
{
IgniteArgumentCheck.NotNull(cfg, "cfg");
cfg = new IgniteConfiguration(cfg); // Create a copy so that config can be modified and reused.
lock (SyncRoot)
{
// 0. Init logger
var log = cfg.Logger ?? new JavaLogger();
log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version);
// 1. Check GC settings.
CheckServerGc(cfg, log);
// 2. Create context.
JvmDll.Load(cfg.JvmDllPath, log);
var cbs = IgniteManager.CreateJvmContext(cfg, log);
var env = cbs.Jvm.AttachCurrentThread();
log.Debug("JVM started.");
var gridName = cfg.IgniteInstanceName;
if (cfg.AutoGenerateIgniteInstanceName)
{
gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid();
}
// 3. Create startup object which will guide us through the rest of the process.
_startup = new Startup(cfg, cbs);
PlatformJniTarget interopProc = null;
try
{
// 4. Initiate Ignite start.
UU.IgnitionStart(env, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null, cbs.IgniteId,
cfg.RedirectJavaConsoleOutput);
// 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
var node = _startup.Ignite;
interopProc = (PlatformJniTarget)node.InteropProcessor;
var javaLogger = log as JavaLogger;
if (javaLogger != null)
{
javaLogger.SetIgnite(node);
}
// 6. On-start callback (notify lifecycle components).
node.OnStart();
Nodes[new NodeKey(_startup.Name)] = node;
return node;
}
catch (Exception ex)
{
// 1. Perform keys cleanup.
string name = _startup.Name;
if (name != null)
{
NodeKey key = new NodeKey(name);
if (Nodes.ContainsKey(key))
Nodes.Remove(key);
}
// 2. Stop Ignite node if it was started.
if (interopProc != null)
UU.IgnitionStop(gridName, true);
// 3. Throw error further (use startup error if exists because it is more precise).
if (_startup.Error != null)
{
// Wrap in a new exception to preserve original stack trace.
throw new IgniteException("Failed to start Ignite.NET, check inner exception for details",
_startup.Error);
}
var jex = ex as JavaException;
if (jex == null)
{
throw;
}
throw ExceptionUtils.GetException(null, jex);
}
finally
{
var ignite = _startup.Ignite;
_startup = null;
if (ignite != null)
{
ignite.ProcessorReleaseStart();
}
}
}
}
/// <summary>
/// Check whether GC is set to server mode.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="log">Log.</param>
private static void CheckServerGc(IgniteConfiguration cfg, ILogger log)
{
if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0)
log.Warn("GC server mode is not enabled, this could lead to less " +
"than optimal performance on multi-core machines (to enable see " +
"http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx).");
}
/// <summary>
/// Prepare callback invoked from Java.
/// </summary>
/// <param name="inStream">Input stream with data.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="handleRegistry">Handle registry.</param>
/// <param name="log">Log.</param>
internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream,
HandleRegistry handleRegistry, ILogger log)
{
try
{
BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream);
PrepareConfiguration(reader, outStream, log);
PrepareLifecycleHandlers(reader, outStream, handleRegistry);
PrepareAffinityFunctions(reader, outStream);
outStream.SynchronizeOutput();
}
catch (Exception e)
{
_startup.Error = e;
throw;
}
}
/// <summary>
/// Prepare configuration.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="outStream">Response stream.</param>
/// <param name="log">Log.</param>
private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream, ILogger log)
{
// 1. Load assemblies.
IgniteConfiguration cfg = _startup.Configuration;
LoadAssemblies(cfg.Assemblies);
ICollection<string> cfgAssembllies;
BinaryConfiguration binaryCfg;
BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg);
LoadAssemblies(cfgAssembllies);
// 2. Create marshaller only after assemblies are loaded.
if (cfg.BinaryConfiguration == null)
cfg.BinaryConfiguration = binaryCfg;
_startup.Marshaller = new Marshaller(cfg.BinaryConfiguration, log);
// 3. Send configuration details to Java
cfg.Validate(log);
// Use system marshaller.
cfg.Write(BinaryUtils.Marshaller.StartMarshal(outStream), ClientSocket.CurrentProtocolVersion);
}
/// <summary>
/// Prepare lifecycle handlers.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="handleRegistry">Handle registry.</param>
private static void PrepareLifecycleHandlers(IBinaryRawReader reader, IBinaryStream outStream,
HandleRegistry handleRegistry)
{
IList<LifecycleHandlerHolder> beans = new List<LifecycleHandlerHolder>
{
new LifecycleHandlerHolder(new InternalLifecycleHandler()) // add internal bean for events
};
// 1. Read beans defined in Java.
int cnt = reader.ReadInt();
for (int i = 0; i < cnt; i++)
beans.Add(new LifecycleHandlerHolder(CreateObject<ILifecycleHandler>(reader)));
// 2. Append beans defined in local configuration.
ICollection<ILifecycleHandler> nativeBeans = _startup.Configuration.LifecycleHandlers;
if (nativeBeans != null)
{
foreach (ILifecycleHandler nativeBean in nativeBeans)
beans.Add(new LifecycleHandlerHolder(nativeBean));
}
// 3. Write bean pointers to Java stream.
outStream.WriteInt(beans.Count);
foreach (LifecycleHandlerHolder bean in beans)
outStream.WriteLong(handleRegistry.AllocateCritical(bean));
// 4. Set beans to STARTUP object.
_startup.LifecycleHandlers = beans;
}
/// <summary>
/// Prepares the affinity functions.
/// </summary>
private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream)
{
var cnt = reader.ReadInt();
var writer = reader.Marshaller.StartMarshal(outStream);
for (var i = 0; i < cnt; i++)
{
var objHolder = new ObjectInfoHolder(reader);
AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder);
}
}
/// <summary>
/// Creates an object and sets the properties.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Resulting object.</returns>
private static T CreateObject<T>(IBinaryRawReader reader)
{
return IgniteUtils.CreateInstance<T>(reader.ReadString(),
reader.ReadDictionaryAsGeneric<string, object>());
}
/// <summary>
/// Kernal start callback.
/// </summary>
/// <param name="interopProc">Interop processor.</param>
/// <param name="stream">Stream.</param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "PlatformJniTarget is passed further")]
internal static void OnStart(GlobalRef interopProc, IBinaryStream stream)
{
try
{
// 1. Read data and leave critical state ASAP.
BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream);
// ReSharper disable once PossibleInvalidOperationException
var name = reader.ReadString();
// 2. Set ID and name so that Start() method can use them later.
_startup.Name = name;
if (Nodes.ContainsKey(new NodeKey(name)))
throw new IgniteException("Ignite with the same name already started: " + name);
_startup.Ignite = new Ignite(_startup.Configuration, _startup.Name,
new PlatformJniTarget(interopProc, _startup.Marshaller), _startup.Marshaller,
_startup.LifecycleHandlers, _startup.Callbacks);
}
catch (Exception e)
{
// 5. Preserve exception to throw it later in the "Start" method and throw it further
// to abort startup in Java.
_startup.Error = e;
throw;
}
}
/// <summary>
/// Load assemblies.
/// </summary>
/// <param name="assemblies">Assemblies.</param>
private static void LoadAssemblies(IEnumerable<string> assemblies)
{
if (assemblies != null)
{
foreach (string s in assemblies)
{
// 1. Try loading as directory.
if (Directory.Exists(s))
{
string[] files = Directory.GetFiles(s, "*.dll");
#pragma warning disable 0168
foreach (string dllPath in files)
{
if (!SelfAssembly(dllPath))
{
try
{
Assembly.LoadFile(dllPath);
}
catch (BadImageFormatException)
{
// No-op.
}
}
}
#pragma warning restore 0168
continue;
}
// 2. Try loading using full-name.
try
{
Assembly assembly = Assembly.Load(s);
if (assembly != null)
continue;
}
catch (Exception e)
{
if (!(e is FileNotFoundException || e is FileLoadException))
throw new IgniteException("Failed to load assembly: " + s, e);
}
// 3. Try loading using file path.
try
{
Assembly assembly = Assembly.LoadFrom(s);
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (assembly != null)
continue;
}
catch (Exception e)
{
if (!(e is FileNotFoundException || e is FileLoadException))
throw new IgniteException("Failed to load assembly: " + s, e);
}
// 4. Not found, exception.
throw new IgniteException("Failed to load assembly: " + s);
}
}
}
/// <summary>
/// Whether assembly points to Ignite binary.
/// </summary>
/// <param name="assembly">Assembly to check..</param>
/// <returns><c>True</c> if this is one of GG assemblies.</returns>
private static bool SelfAssembly(string assembly)
{
return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string,
/// then default no-name Ignite will be returned. Note that caller of this method
/// should not assume that it will return the same instance every time.
/// <p />
/// Note that single process can run multiple Ignite instances and every Ignite instance (and its
/// node) can belong to a different grid. Ignite name defines what grid a particular Ignite
/// instance (and correspondingly its node) belongs to.
/// </summary>
/// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>,
/// then Ignite instance belonging to a default no-name Ignite will be returned.</param>
/// <returns>
/// An instance of named grid.
/// </returns>
/// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception>
public static IIgnite GetIgnite(string name)
{
var ignite = TryGetIgnite(name);
if (ignite == null)
throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name);
return ignite;
}
/// <summary>
/// Gets the default Ignite instance with null name, or an instance with any name when there is only one.
/// <para />
/// Note that caller of this method should not assume that it will return the same instance every time.
/// </summary>
/// <returns>Default Ignite instance.</returns>
/// <exception cref="IgniteException">When there is no matching Ignite instance.</exception>
public static IIgnite GetIgnite()
{
lock (SyncRoot)
{
if (Nodes.Count == 0)
{
throw new IgniteException("Failed to get default Ignite instance: " +
"there are no instances started.");
}
if (Nodes.Count == 1)
{
return Nodes.Single().Value;
}
Ignite result;
if (Nodes.TryGetValue(new NodeKey(null), out result))
{
return result;
}
throw new IgniteException(string.Format("Failed to get default Ignite instance: " +
"there are {0} instances started, and none of them has null name.", Nodes.Count));
}
}
/// <summary>
/// Gets all started Ignite instances.
/// </summary>
/// <returns>All Ignite instances.</returns>
public static ICollection<IIgnite> GetAll()
{
lock (SyncRoot)
{
return Nodes.Values.ToArray();
}
}
/// <summary>
/// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string,
/// then default no-name Ignite will be returned. Note that caller of this method
/// should not assume that it will return the same instance every time.
/// <p/>
/// Note that single process can run multiple Ignite instances and every Ignite instance (and its
/// node) can belong to a different grid. Ignite name defines what grid a particular Ignite
/// instance (and correspondingly its node) belongs to.
/// </summary>
/// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>,
/// then Ignite instance belonging to a default no-name Ignite will be returned.
/// </param>
/// <returns>An instance of named grid, or null.</returns>
public static IIgnite TryGetIgnite(string name)
{
lock (SyncRoot)
{
Ignite result;
return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result;
}
}
/// <summary>
/// Gets the default Ignite instance with null name, or an instance with any name when there is only one.
/// Returns null when there are no Ignite instances started, or when there are more than one,
/// and none of them has null name.
/// </summary>
/// <returns>An instance of default no-name grid, or null.</returns>
public static IIgnite TryGetIgnite()
{
lock (SyncRoot)
{
if (Nodes.Count == 1)
{
return Nodes.Single().Value;
}
return TryGetIgnite(null);
}
}
/// <summary>
/// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then
/// all jobs currently executing on local node will be interrupted. If
/// grid name is <c>null</c>, then default no-name Ignite will be stopped.
/// </summary>
/// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param>
/// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled
/// by calling <c>ComputeJob.cancel</c>method.</param>
/// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c>
/// othwerwise (the instance with given <c>name</c> was not found).</returns>
public static bool Stop(string name, bool cancel)
{
lock (SyncRoot)
{
NodeKey key = new NodeKey(name);
Ignite node;
if (!Nodes.TryGetValue(key, out node))
return false;
node.Stop(cancel);
Nodes.Remove(key);
GC.Collect();
return true;
}
}
/// <summary>
/// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then
/// all jobs currently executing on local node will be interrupted.
/// </summary>
/// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled
/// by calling <c>ComputeJob.Cancel()</c> method.</param>
public static void StopAll(bool cancel)
{
lock (SyncRoot)
{
while (Nodes.Count > 0)
{
var entry = Nodes.First();
entry.Value.Stop(cancel);
Nodes.Remove(entry.Key);
}
}
GC.Collect();
}
/// <summary>
/// Connects Ignite lightweight (thin) client to an Ignite node.
/// <para />
/// Thin client connects to an existing Ignite node with a socket and does not start JVM in process.
/// </summary>
/// <param name="clientConfiguration">The client configuration.</param>
/// <returns>Ignite client instance.</returns>
public static IIgniteClient StartClient(IgniteClientConfiguration clientConfiguration)
{
IgniteArgumentCheck.NotNull(clientConfiguration, "clientConfiguration");
IgniteArgumentCheck.NotNull(clientConfiguration.Host, "clientConfiguration.Host");
return new IgniteClient(clientConfiguration);
}
/// <summary>
/// Reads <see cref="IgniteClientConfiguration"/> from application configuration
/// <see cref="IgniteClientConfigurationSection"/> with <see cref="ClientConfigurationSectionName"/>
/// name and connects Ignite lightweight (thin) client to an Ignite node.
/// <para />
/// Thin client connects to an existing Ignite node with a socket and does not start JVM in process.
/// </summary>
/// <returns>Ignite client instance.</returns>
public static IIgniteClient StartClient()
{
// ReSharper disable once IntroduceOptionalParameters.Global
return StartClient(ClientConfigurationSectionName);
}
/// <summary>
/// Reads <see cref="IgniteClientConfiguration" /> from application configuration
/// <see cref="IgniteClientConfigurationSection" /> with specified name and connects
/// Ignite lightweight (thin) client to an Ignite node.
/// <para />
/// Thin client connects to an existing Ignite node with a socket and does not start JVM in process.
/// </summary>
/// <param name="sectionName">Name of the configuration section.</param>
/// <returns>Ignite client instance.</returns>
public static IIgniteClient StartClient(string sectionName)
{
IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName");
var section = ConfigurationManager.GetSection(sectionName) as IgniteClientConfigurationSection;
if (section == null)
{
throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'.",
typeof(IgniteClientConfigurationSection).Name, sectionName));
}
if (section.IgniteClientConfiguration == null)
{
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteClientConfigurationSection).Name, sectionName));
}
return StartClient(section.IgniteClientConfiguration);
}
/// <summary>
/// Reads <see cref="IgniteConfiguration" /> from application configuration
/// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <param name="configPath">Path to the configuration file.</param>
/// <returns>Started Ignite.</returns>
public static IIgniteClient StartClient(string sectionName, string configPath)
{
var section = GetConfigurationSection<IgniteClientConfigurationSection>(sectionName, configPath);
if (section.IgniteClientConfiguration == null)
{
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteClientConfigurationSection).Name, sectionName, configPath));
}
return StartClient(section.IgniteClientConfiguration);
}
/// <summary>
/// Handles the DomainUnload event of the CurrentDomain control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
// If we don't stop Ignite.NET on domain unload,
// we end up with broken instances in Java (invalid callbacks, etc).
// IIS, in particular, is known to unload and reload domains within the same process.
StopAll(true);
}
/// <summary>
/// Grid key. Workaround for non-null key requirement in Dictionary.
/// </summary>
private class NodeKey
{
/** */
private readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="NodeKey"/> class.
/// </summary>
/// <param name="name">The name.</param>
internal NodeKey(string name)
{
_name = name;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
var other = obj as NodeKey;
return other != null && Equals(_name, other._name);
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return _name == null ? 0 : _name.GetHashCode();
}
}
/// <summary>
/// Value object to pass data between .Net methods during startup bypassing Java.
/// </summary>
private class Startup
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="cbs"></param>
internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs)
{
Configuration = cfg;
Callbacks = cbs;
}
/// <summary>
/// Configuration.
/// </summary>
internal IgniteConfiguration Configuration { get; private set; }
/// <summary>
/// Gets unmanaged callbacks.
/// </summary>
internal UnmanagedCallbacks Callbacks { get; private set; }
/// <summary>
/// Lifecycle handlers.
/// </summary>
internal IList<LifecycleHandlerHolder> LifecycleHandlers { get; set; }
/// <summary>
/// Node name.
/// </summary>
internal string Name { get; set; }
/// <summary>
/// Marshaller.
/// </summary>
internal Marshaller Marshaller { get; set; }
/// <summary>
/// Start error.
/// </summary>
internal Exception Error { get; set; }
/// <summary>
/// Gets or sets the ignite.
/// </summary>
internal Ignite Ignite { get; set; }
}
/// <summary>
/// Internal handler for event notification.
/// </summary>
private class InternalLifecycleHandler : ILifecycleHandler
{
/** */
#pragma warning disable 649 // unused field
[InstanceResource] private readonly IIgnite _ignite;
/** <inheritdoc /> */
public void OnLifecycleEvent(LifecycleEventType evt)
{
if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null)
((Ignite) _ignite).BeforeNodeStop();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using RLToolkit;
using RLToolkit.Basic;
using NUnit.Framework;
// todo: RL:
// -Fix the windows version of the tests
// -replace the cmdrunner dummy file with something legit for envvarsearch
using System.IO;
namespace RLToolkit.UnitTests.Modules
{
[TestFixture]
public class EnvVarSearchTest : TestHarness, ITestBase
{
#region Interface Override
public string ModuleName()
{
return "EnvVarSearch";
}
public override void SetFolderPaths()
{
localFolder = AppDomain.CurrentDomain.BaseDirectory;
SetPaths (localFolder, ModuleName());
}
public override void DataPrepare()
{
// copy the data locally
AddInputFile(Path.Combine(folder_testdata, "EnvVarSearch_File.txt"), true, false);
}
#endregion
#region Basic
[Test]
public void EnvVarSearch_GetDictionary()
{
EnvVarSearch search = new EnvVarSearch ();
Assert.Greater(search.GetDictionary().Count, 0, "Dictionary Size should be greater than 0");
}
[Test]
public void EnvVarSearch_FindInPath_Valid()
{
Dictionary<string, string> setup = new Dictionary<string, string>();
OsDetector.OsSelection os = OsDetector.DetectOs();
bool isFound = false;
if (os == OsDetector.OsSelection.Unix)
{
setup.Add("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
EnvVarSearch search = new EnvVarSearch(setup);
isFound = search.IsPathInEnv("/usr/bin");
} else if (os == OsDetector.OsSelection.Windows)
{
setup.Add("path", @"C:\Windows\system32;C:\Windows");
EnvVarSearch search = new EnvVarSearch(setup);
isFound = search.IsPathInEnv(@"C:\Windows\system32");
} else
{
Assert.Fail("Bad platform");
}
Assert.IsTrue(isFound, "The path should have been found");
}
[Test]
public void EnvVarSearch_FindInPath_NotFound()
{
Dictionary<string, string> setup = new Dictionary<string, string>();
OsDetector.OsSelection os = OsDetector.DetectOs();
bool isFound = false;
if (os == OsDetector.OsSelection.Unix)
{
setup.Add("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
EnvVarSearch search = new EnvVarSearch(setup);
isFound = search.IsPathInEnv("/home/test/folder");
} else if (os == OsDetector.OsSelection.Windows)
{
setup.Add("path", @"C:\Windows\system32;C:\Windows");
EnvVarSearch search = new EnvVarSearch(setup);
isFound = search.IsPathInEnv(@"C:\home\test\folder");
} else
{
Assert.Fail("Bad platform");
}
Assert.IsFalse(isFound, "The path should not have been found");
}
[Test]
public void EnvVarSearch_FindInPath_TrailingBackslash()
{
Dictionary<string, string> setup = new Dictionary<string, string>();
OsDetector.OsSelection os = OsDetector.DetectOs();
bool isFound = false;
if (os == OsDetector.OsSelection.Unix)
{
setup.Add("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
EnvVarSearch search = new EnvVarSearch(setup);
isFound = search.IsPathInEnv("/usr/bin/");
} else if (os == OsDetector.OsSelection.Windows)
{
setup.Add("path", @"C:\Windows\system32;C:\Windows");
EnvVarSearch search = new EnvVarSearch(setup);
isFound = search.IsPathInEnv(@"C:\Windows\system32\");
} else
{
Assert.Fail("Bad platform");
}
Assert.IsTrue(isFound, "The path should have been found");
}
[Test]
public void EnvVarSearch_FindInPath_Valid_File()
{
Dictionary<string, string> setup = new Dictionary<string, string>();
OsDetector.OsSelection os = OsDetector.DetectOs();
string retval = null;
if (os == OsDetector.OsSelection.Unix)
{
setup.Add("PATH", "/usr/local/bin:/usr/bin:" + AppDomain.CurrentDomain.BaseDirectory);
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath("EnvVarSearch_File.txt");
} else if (os == OsDetector.OsSelection.Windows)
{
setup.Add("path", @"C:\Windows\system32;C:\Windows;" + AppDomain.CurrentDomain.BaseDirectory);
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath("EnvVarSearch_File.txt");
} else
{
Assert.Fail("Bad platform");
}
Assert.NotNull(retval, "The path should have been found");
}
[Test]
public void EnvVarSearch_FindInPath_Valid_Folder()
{
Dictionary<string, string> setup = new Dictionary<string, string>();
OsDetector.OsSelection os = OsDetector.DetectOs();
string retval = null;
if (os == OsDetector.OsSelection.Unix)
{
setup.Add("PATH", "/usr/local/bin:/usr/bin:" + AppDomain.CurrentDomain.BaseDirectory);
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath(@"TestData/");
} else if (os == OsDetector.OsSelection.Windows)
{
setup.Add("path", @"C:\Windows\system32;C:\Windows;" + AppDomain.CurrentDomain.BaseDirectory);
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath(@"TestData\");
} else
{
Assert.Fail("Bad platform");
}
Assert.NotNull(retval, "The path should have been found");
}
[Test]
public void EnvVarSearch_FindInPath_NotFound_File()
{
Dictionary<string, string> setup = new Dictionary<string, string>();
OsDetector.OsSelection os = OsDetector.DetectOs();
string retval = null;
if (os == OsDetector.OsSelection.Unix)
{
setup.Add("PATH", "/usr/local/bin:/usr/bin");
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath(@"FooBarSomethingFolder.exe");
} else if (os == OsDetector.OsSelection.Windows)
{
setup.Add("path", @"C:\Windows\system32;C:\Windows");
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath(@"FooBarSomethingFolder.exe");
} else
{
Assert.Fail("Bad platform");
}
Assert.IsNull(retval, "The path should not have been found");
}
[Test]
public void EnvVarSearch_FindInPath_NotFound_Folder()
{
Dictionary<string, string> setup = new Dictionary<string, string>();
OsDetector.OsSelection os = OsDetector.DetectOs();
string retval = null;
if (os == OsDetector.OsSelection.Unix)
{
setup.Add("PATH", "/usr/local/bin:/usr/bin");
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath(@"FooBarSomethingFolder/");
} else if (os == OsDetector.OsSelection.Windows)
{
setup.Add("path", @"C:\Windows\system32;C:\Windows");
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath(@"FooBarSomethingFolder/");
} else
{
Assert.Fail("Bad platform");
}
Assert.IsNull(retval, "The path should not have been found");
}
[Test]
public void EnvVarSearch_FindInPath_MultipleResult()
{
Dictionary<string, string> setup = new Dictionary<string, string>();
OsDetector.OsSelection os = OsDetector.DetectOs();
string retval = null;
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
if (os == OsDetector.OsSelection.Unix)
{
// TestData folder before base dir
setup.Add("PATH", "/usr/local/bin:/usr/bin:" + folder_testdata + ":" + baseDir);
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath("EnvVarSearch_File.txt");
} else if (os == OsDetector.OsSelection.Windows)
{
setup.Add("path", @"C:\Windows\system32;C:\Windows;" + folder_testdata + ";" + baseDir);
EnvVarSearch search = new EnvVarSearch(setup);
retval = search.FindInPath("EnvVarSearch_File.txt");
} else
{
Assert.Fail("Bad platform");
}
Assert.NotNull(retval, "The path should have been found");
Assert.AreEqual(Path.Combine(folder_testdata, "EnvVarSearch_File.txt"), retval, "The path found should be the TestData foldfer");
}
#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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Falken
{
/// <summary>
/// <c>AttributeNotBoundException</c> thrown when access to an
/// unbound attribute property is forbidden.
/// </summary>
[Serializable]
public class AttributeNotBoundException : Exception
{
internal AttributeNotBoundException()
{
}
internal AttributeNotBoundException(string message)
: base(message) { }
internal AttributeNotBoundException(string message, Exception inner)
: base(message, inner) { }
}
/// <summary>
/// <c>InheritedAttributeNotFoundException</c> thrown when an inherited
/// Falken attribute could not be found.
/// </summary>
[Serializable]
public class InheritedAttributeNotFoundException : Exception
{
internal InheritedAttributeNotFoundException()
{
}
internal InheritedAttributeNotFoundException(string message)
: base(message) { }
internal InheritedAttributeNotFoundException(string message, Exception inner)
: base(message, inner) { }
}
/// <summary>
/// <c>FieldNameMismatchException</c> thrown when an Attribute has a name that does
/// not match its field name.
/// </summary>
[Serializable]
public class MismatchingFieldNameException : Exception
{
internal MismatchingFieldNameException()
{
}
internal MismatchingFieldNameException(string message)
: base(message) { }
internal MismatchingFieldNameException(string message, Exception inner)
: base(message, inner) { }
}
/// <summary>
/// <c>AttributeBase</c> Base attribute class that establishes a connection
/// with any Falken attribute.
/// </summary>
public abstract class AttributeBase
{
/// <summary>
/// Falken attribute that this is bound to.
/// </summary>
protected FalkenInternal.falken.AttributeBase _attribute = null;
/// <summary>
/// Metadata of the field in _fieldContainer that this attribute represents.
/// </summary>
protected FieldInfo _fieldInfo = null;
/// <summary>
/// Container object for the field this attribute represents.
/// </summary>
protected object _fieldContainer = null;
/// <summary>
/// Name of the attribute, only when not using reflection.
/// </summary>
protected string _name = null;
/// <summary>
/// Implicit conversion method used to convert to values.
/// </summary>
private MethodInfo _implicitToConversion = null;
/// <summary>
/// Implicit conversion method used to convert from values.
/// </summary>
private MethodInfo _implicitFromConversion = null;
/// <summary>
/// Cache of conversion methods.
/// </summary>
private static Dictionary<KeyValuePair<Type, Type>, MethodInfo> _implicitConversionCache =
new Dictionary<KeyValuePair<Type, Type>, MethodInfo>();
/// <summary>
/// Get the internal attribute this is bound to.
/// Do NOT use this. There's no need to access this directly.
/// </summary>
internal FalkenInternal.falken.AttributeBase InternalAttribute
{
get
{
return _attribute;
}
}
/// <summary>
/// Check if the attribute is bound to a Falken's attribute.
/// </summary>
internal bool Bound
{
get
{
return _attribute != null;
}
}
/// <summary>
/// Check whether the attribute has an associated field value that is not itself.
/// </summary>
internal bool HasForeignFieldValue
{
get
{
return _fieldInfo != null && _fieldContainer != null
&& _fieldInfo.GetValue(_fieldContainer) != this;
}
}
/// <summary>
/// Get the name of this attribute (which will be equal to the field name).
/// Can return null if attribute is not bound.
/// </summary>
public string Name
{
get
{
if (Bound)
{
return _attribute.name();
}
return null;
}
}
/// <summary>
/// Enable/disable clamping of out-of-range values for
/// attribute types that support it. When it's enabled
/// values will be clamped to the max or min value
/// of the range.
/// </summary>
public bool EnableClamping {
get
{
if (Bound)
{
return _attribute.enable_clamping();
}
return false;
}
set
{
if (Bound)
{
_attribute.set_enable_clamping(value);
}
}
}
/// <summary>
/// Default attribute base constructor.
/// </summary>
protected AttributeBase()
{
}
/// <summary>
/// Construct the attribute base with the given name.
/// Used when for attributes created dynamically, rather than using
/// reflection.
/// <exception>
/// ArgumentNullException thrown when name is null.
/// </exception>
/// </summary>
protected AttributeBase(string name)
{
if (name == null)
{
throw new ArgumentNullException(name);
}
_name = name;
}
/// <summary>
/// Find an implicit conversion method and cache it.
/// </summary>
/// <param name="fromType">Type to convert from.</param>
/// <param name="toType">Type to convert to.</param>
/// <returns> MethodInfo if conversion is found, null otherwise.</returns>
private static MethodInfo FindImplicitConversionOp(Type fromType, Type toType)
{
var key = new KeyValuePair<Type, Type>(fromType, toType);
// Search the cache first.
MethodInfo foundMethod;
if (_implicitConversionCache.TryGetValue(key, out foundMethod))
{
return foundMethod;
}
// Search each type for a conversion method.
foreach (var baseType in new[] { fromType, toType })
{
IEnumerable<MethodInfo> methods = baseType.GetMethods(
BindingFlags.Public | BindingFlags.Static).Where(
method => method.Name == "op_Implicit" && method.ReturnType == toType);
foreach (MethodInfo method in methods)
{
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 1 &&
parameters.FirstOrDefault().ParameterType == fromType)
{
foundMethod = method;
break;
}
}
if (foundMethod != null)
{
break;
}
}
_implicitConversionCache[key] = foundMethod;
return foundMethod;
}
/// <summary>
/// Verify that a given object can be converted/assigned to a value
/// of a given type.
/// </summary>
protected static bool CanConvertToGivenType(Type type, object obj)
{
if (obj == null)
{
throw new ArgumentNullException("Given obj can't be null.");
}
Type objType = obj.GetType();
if (objType.IsAssignableFrom(type))
{
return true;
}
if (FindImplicitMethods(objType, type))
{
return true;
}
return false;
}
/// <summary>
/// Find the implicit conversion between types and cache them.
/// if we do.
/// <return> True if both methods are found, false otherwise. </return>
/// </summary>
protected static bool FindImplicitMethods(Type baseType, Type toType)
{
return FindImplicitConversionOp(baseType, toType) != null &&
FindImplicitConversionOp(toType, baseType) != null;
}
/// <summary>
/// Cast a given object value to type T.
/// Does not check if the conversion is valid.
/// </summary>
/// <param name="value">Value to cast.</param>
/// <returns>Object cast to typeof(T).</returns>
/// <exception>InvalidCastException if conversion isn't possible.</exception>
protected T CastTo<T>(object value)
{
Type valueType = value.GetType();
if (typeof(IConvertible).IsAssignableFrom(valueType))
{
return (T)Convert.ChangeType(value, typeof(T));
}
else if (valueType == typeof(T))
{
return (T)value;
}
if (_implicitToConversion == null)
{
_implicitToConversion = FindImplicitConversionOp(valueType, typeof(T));
if (_implicitToConversion == null)
{
throw new InvalidCastException(
$"Unable to convert {value} from type {valueType} to {typeof(T)}");
}
}
return (T)_implicitToConversion.Invoke(null, new[] { value });
}
/// <summary>
/// Cast a given object value from another type to the bound field type.
/// Does not check if the conversion is valid.
/// </summary>
/// <param name="value">Value to cast.</param>
/// <returns>Object cast to _fieldInfo.FieldType.</returns>
/// <exception>InvalidCastException if conversion isn't possible.</exception>
protected object CastFrom<T>(T value)
{
Type valueType = typeof(T);
Type fieldType = _fieldInfo.FieldType;
if (typeof(IConvertible).IsAssignableFrom(fieldType))
{
return Convert.ChangeType(value, fieldType);
}
else if (valueType == fieldType)
{
return value;
}
if (_implicitFromConversion == null)
{
_implicitFromConversion = FindImplicitConversionOp(valueType, fieldType);
if (_implicitFromConversion == null)
{
throw new InvalidCastException(
$"Unable to convert {value} from type {valueType} to {fieldType}");
}
}
return _implicitFromConversion.Invoke(null, new[] { (object)value });
}
/// <summary>
/// If the attribute is already bound to a field throw an exception.
/// </summary>
/// <param name="fieldInfo">Optional field metadata to attempt to bind to.</param>
/// <exception>AlreadyBoundException</exception> is thrown if the attribute is already
/// bound to a field.
protected void ThrowIfBound(FieldInfo fieldInfo)
{
if (Bound)
{
var newFieldName = fieldInfo != null ? fieldInfo.Name : "<unknown>";
var existingFieldName = _fieldInfo != null ? _fieldInfo.Name : Name;
throw new AlreadyBoundException($"Can't bind field {newFieldName} to " +
$"attribute {Name} as it is " +
$"already bound to field {existingFieldName}");
}
}
/// <summary>
/// Establish a connection between a C# attribute and a Falken's attribute.
/// </summary>
/// <param name="fieldInfo">Metadata information of the field this is being bound
/// to.</param>
/// <param name="fieldContainer">Object that contains the value of the field.</param>
/// <param name="container">Internal container to add the attribute to.</param>
/// <exception>AlreadyBoundException thrown when trying to bind the attribute when it was
/// bound already.</exception>
internal abstract void BindAttribute(FieldInfo fieldInfo, object fieldContainer,
FalkenInternal.falken.AttributeContainer container);
/// <summary>
/// Infer the attribute name based on name provided at construction (if any) and the
/// associated fieldname.
/// <exception>FieldNameMismatchException thrown when the attribute has a name
/// that does not match its field name.</exception>
/// </summary>
internal void SetNameToFieldName(FieldInfo fieldInfo, object fieldContainer)
{
if (fieldInfo != null && fieldContainer != null)
{
var value = fieldInfo.GetValue(fieldContainer);
if (value == this && _name != null && _name != fieldInfo.Name)
{
throw new MismatchingFieldNameException(
$"Attribute {this} has set name {_name} which does not match its " +
$"associated field name {fieldInfo.Name}.");
}
_name = fieldInfo.Name;
}
}
/// <summary>
/// Clear all field and attribute bindings.
/// </summary>
protected virtual void ClearBindings()
{
_attribute = null;
_fieldInfo = null;
_fieldContainer = null;
}
/// <summary>
/// Read a field value and cast to the attribute's data type.
/// </summary>
/// <returns>Field value or null if it can't be converted to the required type or the
/// attribute isn't bound to a field.</returns>
internal virtual object ReadField()
{
return Bound && HasForeignFieldValue ? _fieldInfo.GetValue(_fieldContainer) : null;
}
/// <summary>
/// Update Falken's attribute value to reflect C# field's value.
/// </summary>
internal abstract void Read();
/// <summary>
/// Set internal attribute base directly without going through the binding process.
/// </summary>
/// <param name="attributeBase">Internal attribute to associate with this instance.</param>
/// <param name="fieldInfo">Field metadata for a field on the fieldContainer object.</param>
/// <param name="fieldContainer">Object that contains the field.</param>
internal virtual void SetFalkenInternalAttribute(
FalkenInternal.falken.AttributeBase attributeBase,
FieldInfo fieldInfo, object fieldContainer)
{
if (!((fieldInfo == null && fieldContainer == null) ||
(fieldInfo != null && fieldContainer != null)))
{
ClearBindings();
throw new ArgumentException("Both fieldInfo and fieldContainer must be " +
"either null or not null.");
}
_attribute = attributeBase;
_fieldInfo = fieldInfo;
_fieldContainer = fieldContainer;
}
/// <summary>
/// Change the internal attribute base. It's assumed that the given
/// attribute is the same as the one that it's set.
/// </summary>
internal virtual void Rebind(FalkenInternal.falken.AttributeBase attributeBase)
{
_attribute = attributeBase;
// Mark the contents of the attribute as invalid
InvalidateNonFalkenFieldValue();
}
/// <summary>
/// Write a value to the field bound to this object.
/// </summary>
/// <param name="value">Value to set to the field.</param>
/// <returns>true if the value is set, false otherwise.</returns>
internal virtual bool WriteField(object value)
{
if (HasForeignFieldValue)
{
_fieldInfo.SetValue(_fieldContainer, value);
return true;
}
return false;
}
/// <summary>
/// Set C# field's value to match Falken's internal one.
/// </summary>
internal abstract void Write();
/// <summary>
/// Read a field and check if the value is valid.
/// </summary>
/// <returns>
/// Object boxed version of the attribute value.
/// or null if invalid or unable to readValue stored in Falken's attribute.
/// </returns>
internal virtual object ReadFieldIfValid() {
return ReadField();
}
/// <summary>
/// Invalidates the value of any non-Falken field represented by this attribute.
/// </summary>
internal virtual void InvalidateNonFalkenFieldValue() {}
}
}
| |
using System;
using System.Text;
namespace Lucene.Net.Search
{
/*
* 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 AttributeSource = Lucene.Net.Util.AttributeSource;
using BytesRef = Lucene.Net.Util.BytesRef;
using Term = Lucene.Net.Index.Term;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// A <see cref="Query"/> that matches documents within an range of terms.
///
/// <para/>This query matches the documents looking for terms that fall into the
/// supplied range according to
/// <see cref="byte.CompareTo(byte)"/>. It is not intended
/// for numerical ranges; use <see cref="NumericRangeQuery"/> instead.
///
/// <para/>This query uses the
/// <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/>
/// rewrite method.
/// <para/>
/// @since 2.9
/// </summary>
public class TermRangeQuery : MultiTermQuery
{
private BytesRef lowerTerm;
private BytesRef upperTerm;
private bool includeLower;
private bool includeUpper;
/// <summary>
/// Constructs a query selecting all terms greater/equal than <paramref name="lowerTerm"/>
/// but less/equal than <paramref name="upperTerm"/>.
///
/// <para/>
/// If an endpoint is <c>null</c>, it is said
/// to be "open". Either or both endpoints may be open. Open endpoints may not
/// be exclusive (you can't select all but the first or last term without
/// explicitly specifying the term to exclude.)
/// </summary>
/// <param name="field"> The field that holds both lower and upper terms. </param>
/// <param name="lowerTerm">
/// The term text at the lower end of the range. </param>
/// <param name="upperTerm">
/// The term text at the upper end of the range. </param>
/// <param name="includeLower">
/// If true, the <paramref name="lowerTerm"/> is
/// included in the range. </param>
/// <param name="includeUpper">
/// If true, the <paramref name="upperTerm"/> is
/// included in the range. </param>
public TermRangeQuery(string field, BytesRef lowerTerm, BytesRef upperTerm, bool includeLower, bool includeUpper)
: base(field)
{
this.lowerTerm = lowerTerm;
this.upperTerm = upperTerm;
this.includeLower = includeLower;
this.includeUpper = includeUpper;
}
/// <summary>
/// Factory that creates a new <see cref="TermRangeQuery"/> using <see cref="string"/>s for term text.
/// </summary>
public static TermRangeQuery NewStringRange(string field, string lowerTerm, string upperTerm, bool includeLower, bool includeUpper)
{
BytesRef lower = lowerTerm == null ? null : new BytesRef(lowerTerm);
BytesRef upper = upperTerm == null ? null : new BytesRef(upperTerm);
return new TermRangeQuery(field, lower, upper, includeLower, includeUpper);
}
/// <summary>
/// Returns the lower value of this range query </summary>
public virtual BytesRef LowerTerm
{
get
{
return lowerTerm;
}
}
/// <summary>
/// Returns the upper value of this range query </summary>
public virtual BytesRef UpperTerm
{
get
{
return upperTerm;
}
}
/// <summary>
/// Returns <c>true</c> if the lower endpoint is inclusive </summary>
public virtual bool IncludesLower
{
get { return includeLower; }
}
/// <summary>
/// Returns <c>true</c> if the upper endpoint is inclusive </summary>
public virtual bool IncludesUpper
{
get { return includeUpper; }
}
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
if (lowerTerm != null && upperTerm != null && lowerTerm.CompareTo(upperTerm) > 0)
{
return TermsEnum.EMPTY;
}
TermsEnum tenum = terms.GetIterator(null);
if ((lowerTerm == null || (includeLower && lowerTerm.Length == 0)) && upperTerm == null)
{
return tenum;
}
return new TermRangeTermsEnum(tenum, lowerTerm, upperTerm, includeLower, includeUpper);
}
/// <summary>
/// Prints a user-readable version of this query. </summary>
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
if (!Field.Equals(field, StringComparison.Ordinal))
{
buffer.Append(Field);
buffer.Append(":");
}
buffer.Append(includeLower ? '[' : '{');
// TODO: all these toStrings for queries should just output the bytes, it might not be UTF-8!
buffer.Append(lowerTerm != null ? ("*".Equals(Term.ToString(lowerTerm), StringComparison.Ordinal) ? "\\*" : Term.ToString(lowerTerm)) : "*");
buffer.Append(" TO ");
buffer.Append(upperTerm != null ? ("*".Equals(Term.ToString(upperTerm), StringComparison.Ordinal) ? "\\*" : Term.ToString(upperTerm)) : "*");
buffer.Append(includeUpper ? ']' : '}');
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
result = prime * result + (includeLower ? 1231 : 1237);
result = prime * result + (includeUpper ? 1231 : 1237);
result = prime * result + ((lowerTerm == null) ? 0 : lowerTerm.GetHashCode());
result = prime * result + ((upperTerm == null) ? 0 : upperTerm.GetHashCode());
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (!base.Equals(obj))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
TermRangeQuery other = (TermRangeQuery)obj;
if (includeLower != other.includeLower)
{
return false;
}
if (includeUpper != other.includeUpper)
{
return false;
}
if (lowerTerm == null)
{
if (other.lowerTerm != null)
{
return false;
}
}
else if (!lowerTerm.Equals(other.lowerTerm))
{
return false;
}
if (upperTerm == null)
{
if (other.upperTerm != null)
{
return false;
}
}
else if (!upperTerm.Equals(other.upperTerm))
{
return false;
}
return true;
}
}
}
| |
/*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
namespace GemFireXDDBI.DBMigrate
{
partial class MigrateCfg
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBoxTriggers = new System.Windows.Forms.CheckBox();
this.checkBoxFunctions = new System.Windows.Forms.CheckBox();
this.checkBoxStoredProcedures = new System.Windows.Forms.CheckBox();
this.checkBoxViews = new System.Windows.Forms.CheckBox();
this.checkBoxTables = new System.Windows.Forms.CheckBox();
this.comboBoxDestDB = new System.Windows.Forms.ComboBox();
this.comboBoxSourceDB = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.buttonOK = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.checkBoxIndexes = new System.Windows.Forms.CheckBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.checkBoxIndexes);
this.groupBox1.Controls.Add(this.checkBoxTriggers);
this.groupBox1.Controls.Add(this.checkBoxFunctions);
this.groupBox1.Controls.Add(this.checkBoxStoredProcedures);
this.groupBox1.Controls.Add(this.checkBoxViews);
this.groupBox1.Controls.Add(this.checkBoxTables);
this.groupBox1.Controls.Add(this.comboBoxDestDB);
this.groupBox1.Controls.Add(this.comboBoxSourceDB);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(13, 22);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(433, 175);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Specify options for database migartion";
//
// checkBoxTriggers
//
this.checkBoxTriggers.AutoSize = true;
this.checkBoxTriggers.Location = new System.Drawing.Point(187, 128);
this.checkBoxTriggers.Name = "checkBoxTriggers";
this.checkBoxTriggers.Size = new System.Drawing.Size(64, 17);
this.checkBoxTriggers.TabIndex = 9;
this.checkBoxTriggers.Text = "Triggers";
this.checkBoxTriggers.UseVisualStyleBackColor = true;
//
// checkBoxFunctions
//
this.checkBoxFunctions.AutoSize = true;
this.checkBoxFunctions.Location = new System.Drawing.Point(100, 128);
this.checkBoxFunctions.Name = "checkBoxFunctions";
this.checkBoxFunctions.Size = new System.Drawing.Size(72, 17);
this.checkBoxFunctions.TabIndex = 8;
this.checkBoxFunctions.Text = "Functions";
this.checkBoxFunctions.UseVisualStyleBackColor = true;
//
// checkBoxStoredProcedures
//
this.checkBoxStoredProcedures.AutoSize = true;
this.checkBoxStoredProcedures.Location = new System.Drawing.Point(274, 104);
this.checkBoxStoredProcedures.Name = "checkBoxStoredProcedures";
this.checkBoxStoredProcedures.Size = new System.Drawing.Size(114, 17);
this.checkBoxStoredProcedures.TabIndex = 7;
this.checkBoxStoredProcedures.Text = "Stored Procedures";
this.checkBoxStoredProcedures.UseVisualStyleBackColor = true;
//
// checkBoxViews
//
this.checkBoxViews.AutoSize = true;
this.checkBoxViews.Location = new System.Drawing.Point(187, 104);
this.checkBoxViews.Name = "checkBoxViews";
this.checkBoxViews.Size = new System.Drawing.Size(54, 17);
this.checkBoxViews.TabIndex = 6;
this.checkBoxViews.Text = "Views";
this.checkBoxViews.UseVisualStyleBackColor = true;
//
// checkBoxTables
//
this.checkBoxTables.AutoSize = true;
this.checkBoxTables.Location = new System.Drawing.Point(100, 104);
this.checkBoxTables.Name = "checkBoxTables";
this.checkBoxTables.Size = new System.Drawing.Size(58, 17);
this.checkBoxTables.TabIndex = 5;
this.checkBoxTables.Text = "Tables";
this.checkBoxTables.UseVisualStyleBackColor = true;
//
// comboBoxDestDB
//
this.comboBoxDestDB.FormattingEnabled = true;
this.comboBoxDestDB.Location = new System.Drawing.Point(100, 70);
this.comboBoxDestDB.Name = "comboBoxDestDB";
this.comboBoxDestDB.Size = new System.Drawing.Size(327, 21);
this.comboBoxDestDB.TabIndex = 4;
//
// comboBoxSourceDB
//
this.comboBoxSourceDB.FormattingEnabled = true;
this.comboBoxSourceDB.Location = new System.Drawing.Point(100, 35);
this.comboBoxSourceDB.Name = "comboBoxSourceDB";
this.comboBoxSourceDB.Size = new System.Drawing.Size(327, 21);
this.comboBoxSourceDB.TabIndex = 3;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 104);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(82, 13);
this.label3.TabIndex = 2;
this.label3.Text = "Include Entities:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 70);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(81, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Destination DB:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 35);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(62, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Source DB:";
//
// buttonOK
//
this.buttonOK.Location = new System.Drawing.Point(279, 214);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 23);
this.buttonOK.TabIndex = 1;
this.buttonOK.Text = "OK";
this.buttonOK.UseVisualStyleBackColor = true;
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(371, 214);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 2;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// checkBoxIndexes
//
this.checkBoxIndexes.AutoSize = true;
this.checkBoxIndexes.Location = new System.Drawing.Point(274, 128);
this.checkBoxIndexes.Name = "checkBoxIndexes";
this.checkBoxIndexes.Size = new System.Drawing.Size(63, 17);
this.checkBoxIndexes.TabIndex = 10;
this.checkBoxIndexes.Text = "Indexes";
this.checkBoxIndexes.UseVisualStyleBackColor = true;
//
// MigrateCfg
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(459, 262);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.groupBox1);
this.Name = "MigrateCfg";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "DBMigrate";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox checkBoxTriggers;
private System.Windows.Forms.CheckBox checkBoxFunctions;
private System.Windows.Forms.CheckBox checkBoxStoredProcedures;
private System.Windows.Forms.CheckBox checkBoxViews;
private System.Windows.Forms.CheckBox checkBoxTables;
private System.Windows.Forms.ComboBox comboBoxDestDB;
private System.Windows.Forms.ComboBox comboBoxSourceDB;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.CheckBox checkBoxIndexes;
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using GrandTheftMultiplayer.Server;
using GrandTheftMultiplayer.Server.API;
using GrandTheftMultiplayer.Server.Elements;
using GrandTheftMultiplayer.Server.Managers;
using GrandTheftMultiplayer.Shared;
using GrandTheftMultiplayer.Shared.Math;
public class RaceGamemode : Script
{
public RaceGamemode()
{
API.onUpdate += onUpdate;
API.onPlayerDisconnected += onDisconnect;
API.onPlayerFinishedDownload += onPlayerConnect;
API.onPlayerRespawn += onPlayerRespawn;
API.onClientEventTrigger += onClientEvent;
API.onResourceStop += onResourceStop;
API.onResourceStart += onResourceStart;
API.onMapChange += MapChange;
}
public bool IsRaceOngoing { get; set; }
public List<Opponent> Opponents { get; set; }
public Race CurrentRace { get; set; }
public List<Race> AvailableRaces { get; set; }
public List<Vector3> CurrentRaceCheckpoints { get; set; }
public DateTime RaceStart { get; set; }
public List<NetHandle> Objects { get; set; }
public List<Thread> ActiveThreads { get; set; }
public int RaceStartCountdown { get; set; }
public DateTime RaceTimer { get; set; }
public DateTime LastSecond {get; set;}
public void onResourceStart()
{
AvailableRaces = new List<Race>();
Opponents = new List<Opponent>();
CurrentRaceCheckpoints = new List<Vector3>();
Objects = new List<NetHandle>();
API.consoleOutput("Race gamemode started!");
API.exported.scoreboard.addScoreboardColumn("race_place", "Place", 80);
API.exported.scoreboard.addScoreboardColumn("race_checkpoints", "Checkpoints", 160);
API.exported.scoreboard.addScoreboardColumn("race_time", "Time", 120);
API.exported.mapcycler.endRound();
}
private void UpdateScoreboardData(Opponent player, int place)
{
if (place != -1)
API.exported.scoreboard.setPlayerScoreboardData(player.Client, "race_place", place.ToString());
API.exported.scoreboard.setPlayerScoreboardData(player.Client, "race_checkpoints", player.CheckpointsPassed.ToString());
API.exported.scoreboard.setPlayerScoreboardData(player.Client, "race_time", player.TimeFinished);
}
public void onPlayerRespawn(Client player)
{
if (IsRaceOngoing)
{
Opponent curOp = Opponents.FirstOrDefault(op => op.Client == player);
if (curOp == null || curOp.HasFinished || !curOp.HasStarted || curOp.CheckpointsPassed == 0)
{
SetUpPlayerForRace(player, CurrentRace, false, 0);
}
else
{
RespawnPlayer(player, CurrentRace, curOp.CheckpointsPassed - 1);
}
}
}
public void onResourceStop()
{
API.triggerClientEventForAll("resetRace");
API.exported.scoreboard.removeScoreboardColumn("race_place");
API.exported.scoreboard.removeScoreboardColumn("race_checkpoints");
API.exported.scoreboard.removeScoreboardColumn("race_time");
}
private Race parseRace(string mapName, XmlGroup map)
{
var output = new Race();
output.Name = API.getResourceName(mapName);
output.Description = API.getResourceDescription(mapName);
output.Filename = mapName;
var meta = map.getElementByType("laps");
if (meta != null)
{
output.LapsAvailable = meta.getElementData<bool>("value");
}
var checkpoints = new List<Vector3>();
foreach(var chk in map.getElementsByType("checkpoint"))
{
checkpoints.Add(
new Vector3(chk.getElementData<float>("posX"),
chk.getElementData<float>("posY"),
chk.getElementData<float>("posZ")));
}
output.Checkpoints = checkpoints.ToArray();
var sp = new List<SpawnPoint>();
foreach(var chk in map.getElementsByType("spawnpoint"))
{
sp.Add(new SpawnPoint() {
Position = new Vector3(chk.getElementData<float>("posX"),
chk.getElementData<float>("posY"),
chk.getElementData<float>("posZ")),
Heading = chk.getElementData<float>("heading"),
});
}
output.SpawnPoints = sp.ToArray();
var vehs = new List<VehicleHash>();
foreach(var chk in map.getElementsByType("availablecar"))
{
vehs.Add((VehicleHash)chk.getElementData<int>("model"));
}
output.AvailableVehicles = vehs.ToArray();
return output;
}
public void MapChange(string mapName, XmlGroup map)
{
EndRace();
API.consoleOutput("Parsing map...");
var race = new Race(parseRace(mapName, map));
API.consoleOutput("Map parse done! Race null? " + (race == null));
CurrentRace = race;
Opponents.ForEach(op =>
{
op.HasFinished = false;
op.CheckpointsPassed = 0;
op.TimeFinished = "";
if (!op.Vehicle.IsNull)
{
API.deleteEntity(op.Vehicle);
}
API.freezePlayer(op.Client, true);
});
if (Objects != null)
{
foreach (var ent in Objects)
{
API.deleteEntity(ent);
}
Objects.Clear();
}
else
{
Objects = new List<NetHandle>();
}
var clients = API.getAllPlayers();
for (int i = 0; i < clients.Count; i++)
{
API.freezePlayer(clients[i], false);
SetUpPlayerForRace(clients[i], CurrentRace, true, i);
}
CurrentRaceCheckpoints = race.Checkpoints.ToList();
RaceStart = DateTime.UtcNow;
API.consoleOutput("RACE: Starting race " + race.Name);
RaceStartCountdown = 13;
}
private DateTime _lastPositionCalculation;
private void CalculatePositions()
{
if (DateTime.Now.Subtract(_lastPositionCalculation).TotalMilliseconds < 1000)
return;
foreach (var opponent in Opponents)
{
if (opponent.HasFinished || !opponent.HasStarted)
{
}
else
{
var newPos = CalculatePlayerPositionInRace(opponent);
if (true)
{
opponent.RacePosition = newPos;
API.triggerClientEvent(opponent.Client, "updatePosition", newPos, Opponents.Count, opponent.CheckpointsPassed, CurrentRaceCheckpoints.Count);
}
}
}
_lastPositionCalculation = DateTime.Now;
}
private DateTime _lastScoreboardUpdate;
private void UpdateScoreboard()
{
if (DateTime.Now.Subtract(_lastScoreboardUpdate).TotalMilliseconds < 5000)
return;
foreach (var opponent in Opponents)
{
if (opponent.HasFinished || !opponent.HasStarted)
{
UpdateScoreboardData(opponent, -1);
}
else
{
UpdateScoreboardData(opponent, opponent.RacePosition);
}
}
_lastScoreboardUpdate = DateTime.Now;
}
private void onClientEvent(Client sender, string eventName, params object[] arguments)
{
if (eventName == "race_requestRespawn")
{
Opponent curOp = Opponents.FirstOrDefault(op => op.Client == sender);
if (curOp == null || curOp.HasFinished || !curOp.HasStarted || curOp.CheckpointsPassed == 0) return;
RespawnPlayer(sender, CurrentRace, curOp.CheckpointsPassed - 1);
}
}
public void onUpdate()
{
if (DateTime.Now.Subtract(LastSecond).TotalMilliseconds > 1000)
{
LastSecond = DateTime.Now;
if (RaceStartCountdown > 0)
{
RaceStartCountdown--;
if (RaceStartCountdown == 3)
{
API.triggerClientEventForAll("startRaceCountdown");
}
else if (RaceStartCountdown == 0)
{
IsRaceOngoing = true;
lock (Opponents)
foreach (var opponent in Opponents)
{
API.setEntityPositionFrozen(opponent.Client, opponent.Vehicle, false);
opponent.HasStarted = true;
}
RaceTimer = DateTime.Now;
}
}
}
if (!IsRaceOngoing) return;
CalculatePositions();
UpdateScoreboard();
lock (Opponents)
{
lock (CurrentRaceCheckpoints)
foreach (var opponent in Opponents)
{
if (opponent.HasFinished || !opponent.HasStarted) continue;
if (CurrentRaceCheckpoints.Any() && opponent.Client.position.IsInRangeOf(CurrentRaceCheckpoints[opponent.CheckpointsPassed], 10f))
{
opponent.CheckpointsPassed++;
if (opponent.CheckpointsPassed >= CurrentRaceCheckpoints.Count)
{
if (Opponents.All(op => !op.HasFinished))
{
API.exported.mapcycler.endRoundEx(60000);
}
opponent.HasFinished = true;
var pos = Opponents.Count(o => o.HasFinished);
var suffix = pos.ToString().EndsWith("1")
? "st"
: pos.ToString().EndsWith("2") ? "nd" : pos.ToString().EndsWith("3") ? "rd" : "th";
var timeElapsed = DateTime.Now.Subtract(RaceTimer);
API.sendChatMessageToAll("~h~" + opponent.Client.name + "~h~ has finished " + pos + suffix + " (" + timeElapsed.ToString("mm\\:ss\\.fff") + ")");
opponent.TimeFinished = timeElapsed.ToString("mm\\:ss\\.fff");
API.triggerClientEvent(opponent.Client, "finishRace");
continue;
}
Vector3 nextPos = CurrentRaceCheckpoints[opponent.CheckpointsPassed];
Vector3 nextDir = null;
if (CurrentRaceCheckpoints.Count > opponent.CheckpointsPassed + 1)
{
var nextCp = CurrentRaceCheckpoints[opponent.CheckpointsPassed + 1];
var curCp = CurrentRaceCheckpoints[opponent.CheckpointsPassed];
if (nextCp != null && curCp != null)
{
Vector3 dir = nextCp.Subtract(curCp);
dir.Normalize();
nextDir = dir;
}
}
if (nextDir == null)
{
API.triggerClientEvent(opponent.Client, "setNextCheckpoint", nextPos, true, true);
}
else
{
API.triggerClientEvent(opponent.Client, "setNextCheckpoint", nextPos, false, true, nextDir, CurrentRaceCheckpoints[opponent.CheckpointsPassed + 1]);
}
}
}
}
}
public void onDisconnect(Client player, string reason)
{
Opponent curOp = Opponents.FirstOrDefault(op => op.Client == player);
if (curOp == null) return;
API.deleteEntity(curOp.Vehicle);
lock (Opponents) Opponents.Remove(curOp);
}
[Command("forcemap", ACLRequired = true, GreedyArg = true)]
public void ForceMapCommand(Client sender, string mapFilename)
{
if (!API.doesResourceExist(mapFilename) || API.getResourceType(mapFilename) != ResourceType.map)
{
API.sendChatMessageToPlayer(sender, "Map was not found!");
return;
}
EndRace();
API.sendChatMessageToAll("Starting map ~b~" + mapFilename + "!");
API.sleep(1000);
API.startResource(mapFilename);
}
public void onPlayerConnect(Client player)
{
if (IsRaceOngoing)
{
SetUpPlayerForRace(player, CurrentRace, false, 0);
}
if (ghostmode)
{
API.triggerClientEvent(player, "race_toggleGhostMode", true);
}
}
private void EndRace()
{
IsRaceOngoing = false;
CurrentRace = null;
foreach (var opponent in Opponents)
{
opponent.CheckpointsPassed = 0;
opponent.HasFinished = true;
opponent.HasStarted = false;
}
API.triggerClientEventForAll("resetRace");
CurrentRaceCheckpoints.Clear();
}
private bool ghostmode;
[Command("ghostmode")]
public void ghostmodetoggle(Client sender, bool ghost)
{
API.triggerClientEventForAll("race_toggleGhostMode", ghost);
ghostmode = ghost;
API.sendChatMessageToAll("Ghost mode has been " + (ghost ? "~g~enabled~" : "~r~disabled!"));
}
private Random randGen = new Random();
private void SetUpPlayerForRace(Client client, Race race, bool freeze, int spawnpoint)
{
if (race == null) return;
var selectedModel = unchecked((int)((uint)race.AvailableVehicles[randGen.Next(race.AvailableVehicles.Length)]));
var position = race.SpawnPoints[spawnpoint % race.SpawnPoints.Length].Position;
var heading = race.SpawnPoints[spawnpoint % race.SpawnPoints.Length].Heading;
API.setEntityPosition(client.handle, position);
Vector3 newDir = null;
if (race.Checkpoints.Length >= 2)
{
Vector3 dir = race.Checkpoints[1].Subtract(race.Checkpoints[0]);
dir.Normalize();
newDir = dir;
}
var nextPos = race.Checkpoints[0];
if (newDir == null)
{
API.triggerClientEvent(client, "setNextCheckpoint", nextPos, true, false);
}
else
{
API.triggerClientEvent(client, "setNextCheckpoint", nextPos, false, false, newDir, race.Checkpoints[1]);
}
var playerVehicle = API.createVehicle((VehicleHash)selectedModel, position, new Vector3(0, 0, heading), randGen.Next(70), randGen.Next(70));
API.setPlayerIntoVehicle(client, playerVehicle, -1);
if (freeze)
API.setEntityPositionFrozen(client, playerVehicle, true);
Opponent inOp = Opponents.FirstOrDefault(op => op.Client == client);
lock (Opponents)
{
if (inOp != null)
{
inOp.Vehicle = playerVehicle;
inOp.HasStarted = true;
}
else
{
Opponents.Add(new Opponent(client) { Vehicle = playerVehicle, HasStarted = true });
}
}
}
private void RespawnPlayer(Client client, Race race, int checkpoint)
{
if (race == null) return;
Opponent inOp = Opponents.FirstOrDefault(op => op.Client == client);
int selectedModel = 0;
int color1 = 0;
int color2 = 0;
if (inOp != null)
{
selectedModel = API.getEntityModel(inOp.Vehicle);
color1 = API.getVehiclePrimaryColor(inOp.Vehicle);
color2 = API.getVehicleSecondaryColor(inOp.Vehicle);
}
if (selectedModel == 0)
selectedModel = unchecked((int)(race.AvailableVehicles[randGen.Next(race.AvailableVehicles.Length)]));
var position = CurrentRaceCheckpoints[checkpoint];
var next = position;
if (CurrentRaceCheckpoints.Count > checkpoint + 1)
{
next = CurrentRaceCheckpoints[checkpoint + 1];
}
else
{
next = CurrentRaceCheckpoints[checkpoint - 1];
}
float heading;
var direction = next - position;
direction.Normalize();
var radAtan = -Math.Atan2(direction.X, direction.Y);
heading = (float)(radAtan * 180f / Math.PI);
API.setEntityPosition(client.handle, position);
Vector3 newDir = null;
if (CurrentRaceCheckpoints.Count > checkpoint + 2)
{
Vector3 dir = CurrentRaceCheckpoints[checkpoint+2].Subtract(CurrentRaceCheckpoints[checkpoint+1]);
dir.Normalize();
newDir = dir;
}
var nextPos = CurrentRaceCheckpoints[checkpoint+1];
if (newDir == null)
{
API.triggerClientEvent(client, "setNextCheckpoint", nextPos, true, false);
}
else
{
API.triggerClientEvent(client, "setNextCheckpoint", nextPos, false, false, newDir, CurrentRaceCheckpoints[checkpoint + 2]);
}
var playerVehicle = API.createVehicle((VehicleHash)selectedModel, position, new Vector3(0, 0, heading), color1, color2);
API.setPlayerIntoVehicle(client, playerVehicle, -1);
lock (Opponents)
{
if (inOp != null)
{
API.deleteEntity(inOp.Vehicle);
inOp.Vehicle = playerVehicle;
inOp.HasStarted = true;
}
else
{
Opponents.Add(new Opponent(client) { Vehicle = playerVehicle, HasStarted = true });
}
}
}
private int CalculatePlayerPositionInRace(Opponent player)
{
if (CurrentRace == null) return 0;
int output = 1;
int playerCheckpoint = player.CheckpointsPassed;
int beforeYou = Opponents.Count(tuple => {
if (tuple == player) return false;
return tuple.CheckpointsPassed > playerCheckpoint;
});
output += beforeYou;
var samePosAsYou = Opponents.Where(tuple => tuple.CheckpointsPassed == playerCheckpoint && tuple != player);
output +=
samePosAsYou.Count(
tuple =>
(CurrentRace.Checkpoints[playerCheckpoint].Subtract(tuple.Client.position)).Length() <
(CurrentRace.Checkpoints[playerCheckpoint].Subtract(player.Client.position)).Length());
return output;
}
}
public static class RangeExtension
{
public static bool IsInRangeOf(this Vector3 center, Vector3 dest, float radius)
{
return center.Subtract(dest).Length() < radius;
}
public static Vector3 Subtract(this Vector3 left, Vector3 right)
{
if (left == null || right == null)
{
return new Vector3(100, 100, 100);
}
return new Vector3()
{
X = left.X - right.X,
Y = left.Y - right.Y,
Z = left.Z - right.Z,
};
}
public static float Length(this Vector3 vect)
{
return (float)Math.Sqrt((vect.X * vect.X) + (vect.Y * vect.Y) + (vect.Z * vect.Z));
}
}
public class Race
{
public Vector3[] Checkpoints;
public SpawnPoint[] SpawnPoints;
public VehicleHash[] AvailableVehicles;
public bool LapsAvailable = true;
public Vector3 Trigger;
public SavedProp[] DecorativeProps;
public string Filename;
public string Name;
public string Description;
public Race() { }
public Race(Race copyFrom)
{
Checkpoints = copyFrom.Checkpoints;
SpawnPoints = copyFrom.SpawnPoints;
AvailableVehicles = copyFrom.AvailableVehicles;
LapsAvailable = copyFrom.LapsAvailable;
Trigger = copyFrom.Trigger;
DecorativeProps = copyFrom.DecorativeProps;
Name = copyFrom.Name;
Description = copyFrom.Description;
}
}
public class SpawnPoint
{
public Vector3 Position { get; set; }
public float Heading { get; set; }
}
public class SavedProp
{
public Vector3 Position { get; set; }
public Vector3 Rotation { get; set; }
public int Hash { get; set; }
public bool Dynamic { get; set; }
}
public class Opponent
{
public Opponent(Client c)
{
Client = c;
CheckpointsPassed = 0;
}
public Client Client { get; set; }
public int CheckpointsPassed { get; set; }
public bool HasFinished { get; set; }
public bool HasStarted { get; set; }
public NetHandle Vehicle { get; set; }
public NetHandle Blip { get; set; }
public int RacePosition { get; set; }
public string TimeFinished { get; set; }
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenMetaverse;
using System.Threading;
using InWorldz.Phlox.Serialization;
using System.IO;
using log4net;
using System.Reflection;
using System.Data.SQLite;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework;
namespace InWorldz.Phlox.Engine
{
/// <summary>
/// Manages the state of scripts and maintains a list of scripts that need
/// state storage to disk. Storage is performed on an time interval basis
/// </summary>
internal class StateManager
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly TimeSpan REPORT_INTERVAL = TimeSpan.FromMinutes(5);
private readonly TimeSpan SAVE_INTERVAL = TimeSpan.FromMinutes(4);
private const int SLEEP_TIME_MS = 500;
/// <summary>
/// The connection to the databases is kept open for the duration of the application
/// </summary>
private SQLiteConnection _connection;
private DateTime _lastReport = DateTime.Now;
private int _stateSavesSinceLastReport = 0;
private int _stateRemovalsSinceLastReport = 0;
ExecutionScheduler _scheduler;
/// <summary>
/// Used to lock the collection of dirty scripts and the delay queue
/// </summary>
private object _scriptChangeLock = new object();
/// <summary>
/// All scripts that have changed since their last save
/// </summary>
private Dictionary<UUID, VM.Interpreter> _dirtyScripts = new Dictionary<UUID, VM.Interpreter>();
/// <summary>
/// Stores scripts that have been saved and are on the delay list prevnting them from saving again
/// before SAVE_INTERVAL expires
/// </summary>
private IndexedPriorityQueue<UUID, DateTime> _delayQueue = new IndexedPriorityQueue<UUID, DateTime>();
/// <summary>
/// Scripts that we now have state for that needs to be written to disk on the next iteration
/// </summary>
private Dictionary<UUID, StateDataRequest> _needsSaving = new Dictionary<UUID, StateDataRequest>();
/// <summary>
/// Scripts that have been unloaded and thus no longer need to hold state on
/// region storage
/// </summary>
private List<UUID> _unloadedScripts = new List<UUID>();
/// <summary>
/// The thread we're running on
/// </summary>
private Thread _executionThread;
/// <summary>
/// Whether or not we're running
/// </summary>
private bool _running = true;
/// <summary>
/// Used by this class to know whether or not the scheduler is alive during shutdown
/// </summary>
private MasterScheduler _masterScheduler;
public MasterScheduler MMasterScheduler
{
set
{
_masterScheduler = value;
}
}
public StateManager(ExecutionScheduler scheduler)
{
_scheduler = scheduler;
this.SetupStorage();
}
private void SetupStorage()
{
Directory.CreateDirectory(PhloxConstants.STATE_SAVE_DIR);
SetupAndOpenDatabase();
}
private string GetDBFileName()
{
return Path.Combine(PhloxConstants.STATE_SAVE_DIR, "script_states.db3");
}
private void SetupAndOpenDatabase()
{
_connection = new SQLiteConnection(
String.Format("Data Source={0}", this.GetDBFileName()));
_connection.Open();
const string INITIALIZED_QUERY = "SELECT COUNT(*) AS tbl_count " +
"FROM sqlite_master " +
"WHERE type = 'table' AND tbl_name='StateData';";
using (SQLiteCommand cmd = new SQLiteCommand(INITIALIZED_QUERY, _connection))
{
long count = (long)cmd.ExecuteScalar();
if (count == 0)
{
const string SETUP_QUERY = "CREATE TABLE StateData (" +
" item_id CHARACTER(32) PRIMARY KEY NOT NULL, " +
" state_data BLOB " +
")";
using (SQLiteCommand createCmd = new SQLiteCommand(SETUP_QUERY, _connection))
{
createCmd.ExecuteNonQuery();
}
}
}
}
public void ScriptUnloaded(UUID scriptId)
{
lock (_unloadedScripts)
{
_unloadedScripts.Add(scriptId);
}
}
public void ScriptChanged(VM.Interpreter script)
{
lock (_scriptChangeLock)
{
_dirtyScripts[script.ItemId] = script;
if (!_delayQueue.ContainsKey(script.ItemId))
{
_delayQueue.Add(script.ItemId, DateTime.Now + SAVE_INTERVAL);
_scheduler.RequestStateData(new StateDataRequest(script.ItemId, this.StateAvailable));
}
}
}
private void StateAvailable(StateDataRequest dataRequest)
{
lock (_scriptChangeLock)
{
_dirtyScripts.Remove(dataRequest.ItemId);
if (dataRequest.RawStateData != null)
{
_needsSaving[dataRequest.ItemId] = dataRequest;
}
}
}
/// <summary>
/// Starts the state manager thread. This thread schedules region object state saves
/// </summary>
public void Start()
{
if (_executionThread == null)
{
_executionThread = new Thread(WorkLoop);
_executionThread.Priority = EngineInterface.SUBTASK_PRIORITY;
_executionThread.Start();
}
}
private void WorkLoop()
{
try
{
while (_running)
{
DoSaveDirtyScripts();
CheckForExpiredScripts();
DeleteUnloadedScriptStates();
Thread.Sleep(SLEEP_TIME_MS);
}
}
catch (Exception e)
{
_log.ErrorFormat("[Phlox]: State manager caught exception and is terminating: {0}", e);
throw;
}
}
private void DoSaveDirtyScripts()
{
List<StateDataRequest> data;
lock (_scriptChangeLock)
{
if (_needsSaving.Count == 0)
{
return;
}
data = new List<StateDataRequest>(_needsSaving.Values);
_needsSaving.Clear();
}
_stateSavesSinceLastReport += data.Count;
lock (_connection)
{
//write each state to disk
SQLiteTransaction transaction = _connection.BeginTransaction();
try
{
foreach (StateDataRequest req in data)
{
this.SaveStateToDisk(req);
}
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
private void CheckForExpiredScripts()
{
lock (_scriptChangeLock)
{
while (_delayQueue.Count > 0)
{
KeyValuePair<UUID, DateTime> kvp = _delayQueue.FindMinItemAndIndex();
if (kvp.Value <= DateTime.Now)
{
_delayQueue.Remove(kvp.Key);
if (_dirtyScripts.ContainsKey(kvp.Key))
{
//if this script is dirty and its wait is expired, we can request a save for it now
_delayQueue.Add(kvp.Key, DateTime.Now + SAVE_INTERVAL);
_scheduler.RequestStateData(new StateDataRequest(kvp.Key, this.StateAvailable));
}
//else, this script is expired, but not dirty. just removing it is fine
}
else
{
break;
}
}
}
}
private void DeleteUnloadedScriptStates()
{
List<UUID> unloadedScripts;
lock (_unloadedScripts)
{
if (_unloadedScripts.Count == 0)
{
return;
}
unloadedScripts = new List<UUID>(_unloadedScripts);
_unloadedScripts.Clear();
}
lock (_scriptChangeLock)
{
foreach (UUID uuid in unloadedScripts)
{
_delayQueue.Remove(uuid);
_dirtyScripts.Remove(uuid);
_needsSaving.Remove(uuid);
}
}
_stateRemovalsSinceLastReport += unloadedScripts.Count;
StringBuilder deleteQuery = new StringBuilder();
deleteQuery.Append("DELETE FROM StateData WHERE item_id IN (");
for (int i = 0; i < unloadedScripts.Count; i++)
{
if (i != 0) deleteQuery.Append(",");
deleteQuery.Append("'");
deleteQuery.Append(unloadedScripts[i].Guid.ToString("N"));
deleteQuery.Append("'");
}
deleteQuery.Append(");");
lock (_connection)
{
using (SQLiteCommand cmd = new SQLiteCommand(deleteQuery.ToString(), _connection))
{
cmd.ExecuteNonQuery();
}
}
}
private void ReportStateSaves()
{
if (DateTime.Now - _lastReport >= REPORT_INTERVAL)
{
_log.DebugFormat("[Phlox]: {0} script states saved, {1} states removed in the past {2} minutes",
_stateSavesSinceLastReport, _stateRemovalsSinceLastReport, REPORT_INTERVAL.TotalMinutes);
_stateSavesSinceLastReport = 0;
_stateRemovalsSinceLastReport = 0;
_lastReport = DateTime.Now;
}
}
/// <summary>
/// Only called during startup, loads the state data for the given item id off the disk
/// </summary>
/// <param name="itemId"></param>
/// <returns></returns>
public VM.RuntimeState LoadStateFromDisk(UUID itemId)
{
try
{
lock (_connection)
{
const string FIND_CMD = "SELECT state_data FROM StateData WHERE item_id = @itemId";
using (SQLiteCommand cmd = new SQLiteCommand(FIND_CMD, _connection))
{
SQLiteParameter itemIdParam = cmd.CreateParameter();
itemIdParam.ParameterName = "@itemId";
itemIdParam.Value = itemId.Guid.ToString("N");
cmd.Parameters.Add(itemIdParam);
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
//int bufSz = reader.GetBytes(0, 0, null, 0, 0);
byte[] buffer = (byte[])reader[0];//reader.GetBytes(
using (MemoryStream stateStream = new MemoryStream(buffer))
{
SerializedRuntimeState runstate = ProtoBuf.Serializer.Deserialize<SerializedRuntimeState>(stateStream);
if (runstate != null)
{
return runstate.ToRuntimeState();
}
}
}
}
}
}
}
catch (Exception e)
{
_log.ErrorFormat("[Phlox]: Could not load state for {0} script will be reset. Error was {1}",
itemId, e);
}
return null;
}
internal VM.RuntimeState LoadStateFromPrim(UUID currId, UUID oldId, SceneObjectPart sop)
{
string oldIdState = null;
string newIdState = null;
byte[] binaryState = null;
//Old way, the script states are stored in the group
if (sop.ParentGroup.m_savedScriptState != null &&
(sop.ParentGroup.m_savedScriptState.TryGetValue(oldId, out oldIdState) ||
sop.ParentGroup.m_savedScriptState.TryGetValue(currId, out newIdState)))
{
string state = oldIdState != null ? oldIdState : newIdState;
sop.ParentGroup.m_savedScriptState.Remove(oldIdState != null ? oldId : currId);
byte[] rawState = Convert.FromBase64String(state);
return DeserializeScriptState(currId, rawState);
}
else if (sop.HasSavedScriptStates &&
(sop.TryExtractSavedScriptState(oldId, out binaryState) ||
sop.TryExtractSavedScriptState(currId, out binaryState)))
{
return DeserializeScriptState(sop.UUID, binaryState);
}
return null;
}
private static VM.RuntimeState DeserializeScriptState(UUID currId, byte[] rawState)
{
using (MemoryStream loadStream = new MemoryStream(rawState))
{
try
{
SerializedRuntimeState runstate = ProtoBuf.Serializer.Deserialize<SerializedRuntimeState>(loadStream);
if (runstate != null)
{
return runstate.ToRuntimeState();
}
}
catch (Serialization.SerializationException e)
{
_log.ErrorFormat("[Phlox]: Unable to load script state for {0} from prim data: {1}", currId, e);
}
}
return null;
}
private void SaveStateToDisk(StateDataRequest req)
{
//serialize the state
SerializedRuntimeState serState = (SerializedRuntimeState)req.RawStateData;
using (MemoryStream ms = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(ms, serState);
WriteBlobRow(req.ItemId, ms);
}
}
private void WriteBlobRow(UUID uuid, MemoryStream ms)
{
const string INSERT_CMD = "INSERT OR REPLACE INTO StateData(item_id, state_data) VALUES(@itemId, @stateBlob)";
using (SQLiteCommand cmd = new SQLiteCommand(INSERT_CMD, _connection))
{
SQLiteParameter itemIdParam = cmd.CreateParameter();
itemIdParam.ParameterName = "@itemId";
itemIdParam.Value = uuid.Guid.ToString("N");
SQLiteParameter stateBlobParam = cmd.CreateParameter();
stateBlobParam.ParameterName = "@stateBlob";
stateBlobParam.Value = ms.ToArray();
cmd.Parameters.Add(itemIdParam);
cmd.Parameters.Add(stateBlobParam);
cmd.ExecuteNonQuery();
}
}
internal void Stop()
{
_running = false;
_executionThread.Join();
_log.InfoFormat("[Phlox]: Finalizing {0} script states for shutdown", _dirtyScripts.Count + _needsSaving.Count);
//write all pending script states with direct access since
//the execution scheduler is stopped
foreach (KeyValuePair<UUID, VM.Interpreter> script in _dirtyScripts)
{
SerializedRuntimeState runstate = SerializedRuntimeState.FromRuntimeState(script.Value.ScriptState);
_needsSaving[script.Key] = new StateDataRequest { ItemId = script.Key, RawStateData = runstate };
}
DoSaveDirtyScripts();
DeleteUnloadedScriptStates();
}
}
}
| |
/* Copyright (c) 2013, HotDocs Limited
Use, modification and redistribution of this source is subject
to the New BSD License as set out in LICENSE.TXT. */
using System;
using System.Collections.Generic;
using System.IO;
using HotDocs.Sdk;
namespace HotDocs.Sdk.Server
{
/// <summary>
/// This delegate type allows a host application to request notification immediately prior to the SDK assembling
/// a specific document (during the execution of the WorkSession.AssembleDocuments method).
/// </summary>
/// <param name="template">The Template from which a new document is about to be assembled.</param>
/// <param name="answers">The AnswerCollection which will be used for the assembly. This represents the current
/// state of the answer session for the entire WorkSession, and if modified, will modify the answers from here
/// through to the end of the answer session.</param>
/// <param name="settings">The AssembleDocumentSettings that will be used for this specific document assembly. This is
/// a copy of the WorkSession's DefaultAssemblySettings; if modified it affects only the current assembly.</param>
/// <param name="userState">Whatever state object is passed by the host application into
/// WorkSession.AssembleDocuments will be passed back out to the host application in this userState parameter.</param>
public delegate void PreAssembleDocumentDelegate(Template template, AnswerCollection answers, AssembleDocumentSettings settings, object userState);
/// <summary>
/// This delegate type allows a host application to request notification immediately following the SDK assembling
/// a document during the execution of the WorkSession.AssembleDocuments method.
/// </summary>
/// <param name="template">The Template from which a new document was just assembled.</param>
/// <param name="result">The AssemblyResult object associated with the assembled document. The SDK has not yet
/// processed this AssemblyResult. The Document inside the result will be added to the Document array
/// that will eventually be returned by AssembleDocuments. The Answers will become the new answers for subsequent
/// work in this WorkSession.</param>
/// <param name="userState">Whatever state object is passed by the host application into
/// WorkSession.AssembleDocuments will be passed back out to the host application in this userState parameter.</param>
public delegate void PostAssembleDocumentDelegate(Template template, AssembleDocumentResult result, object userState);
/// <summary>
/// WorkSession is a state machine enabling a host application to easily navigate an assembly queue.
/// It maintains an answer collection and a list of completed (and pending) interviews and documents.
/// A host application uses this class not only to process through the assembly queue, but also to
/// inspect the assembly queue for purposes of providing user feedback ("disposition pages").
/// </summary>
/// <remarks>
/// Note: The implementation of WorkSession is the same whether interfacing with HDS or Core Services.
/// </remarks>
[Serializable]
public class WorkSession
{
/// <summary>
/// <c>WorkSession</c> constructor
/// </summary>
/// <param name="service">An object implementing the IServices interface, encapsulating the instance of
/// HotDocs Server with which the host app is communicating.</param>
/// <param name="template">The template upon which this WorkSession is based. The initial interview and/or
/// document work items in the WorkSession will be based on this template (including its Switches property).</param>
public WorkSession(IServices service, Template template) : this(service, template, null, null) { }
/// <summary>
/// Creates a WorkSession object that a host application can use to step through the process of presenting
/// all the interviews and assembling all the documents that may result from the given template.
/// </summary>
/// <param name="service">An object implementing the IServices interface, encapsulating the instance of
/// HotDocs Server with which the host app is communicating.</param>
/// <param name="template">The template upon which this WorkSession is based. The initial interview and/or
/// document work items in the WorkSession will be based on this template (including its Switches property).</param>
/// <param name="answers">A collection of XML answers to use as a starting point for the work session.
/// The initial interview (if any) will be pre-populated with these answers, and the subsequent generation
/// of documents will have access to these answers as well.</param>
public WorkSession(IServices service, Template template, TextReader answers) : this(service, template, answers, null) {}
/// <summary>
/// Creates a WorkSession object that a host application can use to step through the process of presenting
/// all the interviews and assembling all the documents that may result from the given template.
///
/// Allows the default interview settings to be specified instead of being read from config file
/// </summary>
/// <param name="service">An object implementing the IServices interface, encapsulating the instance of
/// HotDocs Server with which the host app is communicating.</param>
/// <param name="template">The template upon which this WorkSession is based. The initial interview and/or
/// document work items in the WorkSession will be based on this template (including its Switches property).</param>
/// <param name="answers">A collection of XML answers to use as a starting point for the work session.
/// The initial interview (if any) will be pre-populated with these answers, and the subsequent generation
/// of documents will have access to these answers as well.</param>
/// <param name="defaultInterviewSettings">The default interview settings to be used throughout the session</param>
public WorkSession(IServices service, Template template, TextReader answers, InterviewSettings defaultInterviewSettings)
{
_service = service;
AnswerCollection = new AnswerCollection();
if (answers != null)
AnswerCollection.ReadXml(answers);
DefaultAssemblySettings = new AssembleDocumentSettings();
if (defaultInterviewSettings != null)
DefaultInterviewSettings = defaultInterviewSettings;
else
DefaultInterviewSettings = new InterviewSettings();
// add the work items
_workItems = new List<WorkItem>();
if (template.HasInterview)
_workItems.Add(new InterviewWorkItem(template));
if (template.GeneratesDocument)
_workItems.Add(new DocumentWorkItem(template));
}
/* properties/state */
/// <summary>
/// Returns the collection of answers pertaining to the current work item.
/// </summary>
public AnswerCollection AnswerCollection { get; private set; }
/// <summary>
/// When you create a WorkSession, a copy of the application-wide default assembly settings (as specified
/// in web.config) is made and assigned to this property of the AnswerCollection. If the host app customizes
/// these DefaultAssemblyOptions, each subsequent document generated in the WorkSession will inherit those
/// customized settings.
/// </summary>
public AssembleDocumentSettings DefaultAssemblySettings { get; private set; }
/// <summary>
/// The intent with DefaultInterviewOptions was to work much like DefaultAssemblyOptions. When you create
/// a WorkSession, a copy of the application-wide default interview settings (as specified in web.config) is
/// made and assigned to this property of the AnswerCollection. If the host app customizes these
/// DefaultInterviewOptions, each subsequent interview in the WorkSession will inherit those customized
/// settings. HOWEVER, this doesn't work currently because InterviewWorkItems do not carry a reference
/// to the WorkSession, and therefore don't have access to this property. TODO: figure out how this should work.
/// One possibility would be for the WorkSession class to expose the GetInterview method (and maybe also
/// FinishInterview) rather than having those on the InterviewWorkItem class. However, this would mean
/// WorkSession would expose a GetInterview method all the time, but it is only callable some of the time
/// (i.e. when the CurrentWorkItem is an interview).
/// </summary>
public InterviewSettings DefaultInterviewSettings { get; private set; }
/// <summary>
/// Returns the IServices object for the current work session.
/// </summary>
public IServices Service
{
get { return _service; }
}
private IServices _service;
private List<WorkItem> _workItems;
public static string GetSessionDebugSummary(HotDocs.Sdk.Server.WorkSession session)
{
var result = new System.Text.StringBuilder();
result.Append("Service type=");
if (session.Service is HotDocs.Sdk.Server.Cloud.Services)
result.Append("C");
else if (session.Service is HotDocs.Sdk.Server.Local.Services)
result.Append("L");
else if (session.Service is HotDocs.Sdk.Server.WebService.Services)
result.Append("W");
else
result.Append("O");
result.AppendFormat("; Answers={0}", session.AnswerCollection == null ? "null" : session.AnswerCollection.AnswerCount.ToString());
result.AppendFormat("; WorkItems={0}", (session.WorkItems as List<WorkItem>).Count);
var item = session.CurrentWorkItem;
result.AppendFormat("; Current={0} ({1})", item == null ? "null" : item.Template.FileName,
item == null ? "Complete" : ((item is HotDocs.Sdk.Server.InterviewWorkItem) ? "Interview" : "Document"));
return result.ToString();
}
/// <summary>
/// Exposees a list of interview and document work items, both already completed and pending, as suitable for
/// presentation in a host application (for example, to show progress through the work session).
/// </summary>
public IEnumerable<WorkItem> WorkItems
{
get
{
return _workItems;
}
}
/* convenience accessors */
/// <summary>
/// This is the one that's next in line to be completed. In the case of interview work items,
/// an interview is current both before and after it has been presented to the user, all the way
/// up until FinishInterview is called, at which time whatever work item that follows becomes current.
/// If the current work item is a document, AssembleDocuments() should be called, which will
/// complete that document (and any that follow it), advancing CurrentWorkItem as it goes.
/// </summary>
public WorkItem CurrentWorkItem
{
get
{
foreach (var item in _workItems)
{
if (!item.IsCompleted)
return item;
}
// else
return null;
}
}
/// <summary>
/// returns true when all work items in the session have been completed, i.e. CurrentWorkItem == null.
/// </summary>
public bool IsCompleted
{
get { return CurrentWorkItem == null; }
}
/// <summary>
/// AssembleDocuments causes all contiguous pending document work items (from CurrentWorkItem onwards)
/// to be assembled, and returns the assembled documents.
/// </summary>
/// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
/// <returns></returns>
/// <remarks>
/// <para>If AssembleDocuments is called when the current work item is not a document (i.e. when there are
/// currently no documents to assemble), it will return an empty array of results without performing any work.</para>
/// <para>If you need to take any actions before or after each assembly, use the alternate constructor that
/// accepts delegates.</para>
/// TODO: include a table that shows the relationship between members of Document, AssemblyResult, WorkSession and DocumentWorkItem.
/// </remarks>
public Document[] AssembleDocuments(string logRef)
{
return AssembleDocuments(null, null, null, logRef);
}
/// <summary>
/// AssembleDocuments causes all contiguous pending document work items (from CurrentWorkItem onwards)
/// to be assembled, and returns the assembled documents.
/// </summary>
/// <param name="preAssembleDocument">This delegate will be called immediately before each document is assembled.</param>
/// <param name="postAssembleDocument">This delegate will be called immediately following assembly of each document.</param>
/// <param name="userState">This object will be passed to the above delegates.</param>
/// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
/// <returns>An array of Document, one item for each document that was assembled. Note that these items
/// are of type Document, not AssemblyResult (see below).</returns>
/// <remarks>
/// <para>If AssembleDocuments is called when the current work item is not a document (i.e. when there are
/// currently no documents to assemble), it will return an empty array of results without performing any work.</para>
/// TODO: include a table that shows the relationship between members of Document, AssemblyResult, WorkSession and DocumentWorkItem.
/// </remarks>
public Document[] AssembleDocuments(PreAssembleDocumentDelegate preAssembleDocument,
PostAssembleDocumentDelegate postAssembleDocument, object userState, string logRef)
{
var result = new List<Document>();
// skip past completed work items to get the current workItem
WorkItem workItem = null;
int itemIndex = 0;
for (; itemIndex < _workItems.Count; itemIndex++)
{
workItem = _workItems[itemIndex];
if (!workItem.IsCompleted)
break;
workItem = null;
}
// while the current workItem != null && is a document (i.e. is not an interview)
while (workItem != null && workItem is DocumentWorkItem)
{
var docWorkItem = workItem as DocumentWorkItem;
// make a copy of the default assembly settings and pass it to the BeforeAssembleDocumentDelegate (if provided)
AssembleDocumentSettings asmOpts = new AssembleDocumentSettings(DefaultAssemblySettings);
asmOpts.Format = workItem.Template.NativeDocumentType;
// if this is not the last work item in the queue, force retention of transient answers
asmOpts.RetainTransientAnswers |= (workItem != _workItems[_workItems.Count - 1]);
if (preAssembleDocument != null)
preAssembleDocument(docWorkItem.Template, AnswerCollection, asmOpts, userState);
// assemble the item
using (var asmResult = _service.AssembleDocument(docWorkItem.Template, new StringReader(AnswerCollection.XmlAnswers), asmOpts, logRef))
{
if (postAssembleDocument != null)
postAssembleDocument(docWorkItem.Template, asmResult, userState);
// replace the session answers with the post-assembly answers
AnswerCollection.ReadXml(asmResult.Answers);
// add pendingAssemblies to the queue as necessary
InsertNewWorkItems(asmResult.PendingAssemblies, itemIndex);
// store UnansweredVariables in the DocumentWorkItem
docWorkItem.UnansweredVariables = asmResult.UnansweredVariables;
// add an appropriate Document to a list being compiled for the return value of this method
result.Add(asmResult.ExtractDocument());
}
// mark the current workitem as complete
docWorkItem.IsCompleted = true;
// advance to the next workitem
workItem = (++itemIndex >= _workItems.Count) ? null : _workItems[itemIndex];
}
return result.ToArray();
}
/// <summary>
/// This constructor accepts a value for the interview format in case the host application wants to have more
/// control over which format to use other than the one format specified in web.config. For example, the host
/// application can detect whether or not the user's browser has Silverlight installed, and if not, it can choose
/// to fall back to JavaScript interviews even if its normal preference is Silverlight.
/// </summary>
/// <param name="format">The format (Silverlight or JavaScript) of interview being requested.</param>
/// <returns>An <c>InterviewResult</c>, containing the HTML fragment and any other supporting files required by the interview.</returns>
public InterviewResult GetCurrentInterview(Contracts.InterviewFormat format)
{
InterviewSettings s = DefaultInterviewSettings;
// If a format was specified (e.g., it is not "Unspecified") then use the format provided.
if (format != Contracts.InterviewFormat.Unspecified)
s.Format = format;
return GetCurrentInterview(s, null);
}
/// <summary>
/// Returns the current interview using default interview settings
/// </summary>
/// <returns></returns>
public InterviewResult GetCurrentInterview()
{
return GetCurrentInterview(DefaultInterviewSettings, null);
}
/// <summary>
/// Returns the current interview with the given settings
/// </summary>
/// <param name="settings">Settings to use with the interview.</param>
/// <param name="markedVariables">A list of variable names whose prompts should be "marked" in the interview.</param>
/// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
/// <returns>An <c>InterviewResult</c> containing the HTML fragment and other supporting files for the interview.</returns>
public InterviewResult GetCurrentInterview(InterviewSettings settings, IEnumerable<string> markedVariables, string logRef = "")
{
WorkItem currentWorkItem = CurrentWorkItem;
TextReader answers = new StringReader(AnswerCollection.XmlAnswers);
settings.Title = settings.Title ?? CurrentWorkItem.Template.Title;
return _service.GetInterview(currentWorkItem.Template, answers, settings, markedVariables, logRef);
}
/// <summary>
/// Called by the host application when answers have been posted back from a browser interview.
/// </summary>
/// <param name="interviewAnswers">The answers that were posted back from the interview.</param>
public void FinishInterview(TextReader interviewAnswers)
{
// overlay interviewAnswers over the session answer set,
AnswerCollection.OverlayXml(interviewAnswers);
// skip past completed work items to get the current workItem
WorkItem workItem = null;
int itemIndex = 0;
for (; itemIndex < _workItems.Count; itemIndex++)
{
workItem = _workItems[itemIndex];
if (!workItem.IsCompleted)
break;
workItem = null;
}
if (workItem != null && workItem is InterviewWorkItem)
{
// if the current template is an interview template
if (workItem.Template.TemplateType == TemplateType.InterviewOnly)
{
// "assemble" it...
AssembleDocumentSettings asmOpts = new AssembleDocumentSettings(DefaultAssemblySettings);
asmOpts.Format = DocumentType.Native;
// if this is not the last work item in the queue, force retention of transient answers
asmOpts.RetainTransientAnswers |= (itemIndex < _workItems.Count - 1);
// assemble the item
using (var asmResult = _service.AssembleDocument(workItem.Template, new StringReader(AnswerCollection.XmlAnswers), asmOpts, ""))
{
// replace the session answers with the post-assembly answers
AnswerCollection.ReadXml(asmResult.Answers);
// add pendingAssemblies to the queue as necessary
InsertNewWorkItems(asmResult.PendingAssemblies, itemIndex);
}
}
// mark this interview workitem as complete. (This will cause the WorkSession to advance to the next workItem.)
CurrentWorkItem.IsCompleted = true;
}
}
private void InsertNewWorkItems(IEnumerable<Template> templates, int parentPosition)
{
int insertPosition = parentPosition + 1;
foreach (var template in templates)
{
if (template.HasInterview)
_workItems.Insert(insertPosition++, new InterviewWorkItem(template));
if (template.GeneratesDocument)
_workItems.Insert(insertPosition++, new DocumentWorkItem(template));
}
}
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using PlayFab.Json.Utilities;
using System.Linq;
namespace PlayFab.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public abstract class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected internal enum State
{
/// <summary>
/// The Read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The Close method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _tokenType;
private object _value;
internal char _quoteChar;
internal State _currentState;
internal ReadType _readType;
private JsonPosition _currentPosition;
private CultureInfo _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private readonly List<JsonPosition> _stack;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState
{
get { return _currentState; }
}
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the reader is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the reader is closed; otherwise false. The default is true.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get { return _quoteChar; }
protected internal set { _quoteChar = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get { return _dateParseHandling; }
set { _dateParseHandling = value; }
}
/// <summary>
/// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get { return _floatParseHandling; }
set { _floatParseHandling = value; }
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get { return _maxDepth; }
set
{
if (value <= 0)
throw new ArgumentException("Value must be positive.", "value");
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType
{
get { return _tokenType; }
}
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object Value
{
get { return _value; }
}
/// <summary>
/// Gets The Common Language Runtime (CLR) type for the current JSON token.
/// </summary>
public virtual Type ValueType
{
get { return (_value != null) ? _value.GetType() : null; }
}
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = _stack.Count;
if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
return depth;
else
return depth + 1;
}
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public virtual string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
IEnumerable<JsonPosition> positions = (!insideContainer)
? _stack
: _stack.Concat(new[] {_currentPosition});
return JsonPosition.BuildPath(positions);
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
internal JsonPosition GetPosition(int depth)
{
if (depth < _stack.Count)
return _stack[depth];
return _currentPosition;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_stack = new List<JsonPosition>(4);
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_dateParseHandling = DateParseHandling.DateTime;
_floatParseHandling = FloatParseHandling.Double;
CloseInput = true;
}
private void Push(JsonContainerType value)
{
UpdateScopeWithFinishedValue();
if (_currentPosition.Type == JsonContainerType.None)
{
_currentPosition = new JsonPosition(value);
}
else
{
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
// this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{
_hasExceededMaxDepth = true;
throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
}
}
}
private JsonContainerType Pop()
{
JsonPosition oldPosition;
if (_stack.Count > 0)
{
oldPosition = _currentPosition;
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
oldPosition = _currentPosition;
_currentPosition = new JsonPosition();
}
if (_maxDepth != null && Depth <= _maxDepth)
_hasExceededMaxDepth = false;
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract int? ReadAsInt32();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract string ReadAsString();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public abstract byte[] ReadAsBytes();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract decimal? ReadAsDecimal();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTime? ReadAsDateTime();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTimeOffset? ReadAsDateTimeOffset();
internal virtual bool ReadInternal()
{
throw new NotImplementedException();
}
internal DateTimeOffset? ReadAsDateTimeOffsetInternal()
{
_readType = ReadType.ReadAsDateTimeOffset;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Date)
{
if (Value is DateTime)
SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value));
return (DateTimeOffset)Value;
}
if (t == JsonToken.Null)
return null;
DateTimeOffset dt;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal byte[] ReadAsBytesInternal()
{
_readType = ReadType.ReadAsBytes;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (IsWrappedInTypeObject())
{
byte[] data = ReadAsBytes();
ReadInternal();
SetToken(JsonToken.Bytes, data);
return data;
}
// attempt to convert possible base 64 string to bytes
if (t == JsonToken.String)
{
string s = (string)Value;
byte[] data = (s.Length == 0) ? new byte[0] : Convert.FromBase64String(s);
SetToken(JsonToken.Bytes, data);
return data;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.Bytes)
return (byte[])Value;
if (t == JsonToken.StartArray)
{
List<byte> data = new List<byte>();
while (ReadInternal())
{
t = TokenType;
switch (t)
{
case JsonToken.Integer:
data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
byte[] d = data.ToArray();
SetToken(JsonToken.Bytes, d);
return d;
case JsonToken.Comment:
// skip
break;
default:
throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadAsDecimalInternal()
{
_readType = ReadType.ReadAsDecimal;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is decimal))
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture));
return (decimal)Value;
}
if (t == JsonToken.Null)
return null;
decimal d;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (decimal.TryParse(s, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d);
return d;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadAsInt32Internal()
{
_readType = ReadType.ReadAsInt32;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is int))
SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture));
return (int)Value;
}
if (t == JsonToken.Null)
return null;
int i;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out i))
{
SetToken(JsonToken.Integer, i);
return i;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal string ReadAsStringInternal()
{
_readType = ReadType.ReadAsString;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.String)
return (string)Value;
if (t == JsonToken.Null)
return null;
if (IsPrimitiveToken(t))
{
if (Value != null)
{
string s;
if (Value is IFormattable)
s = ((IFormattable)Value).ToString(null, Culture);
else
s = Value.ToString();
SetToken(JsonToken.String, s);
return s;
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal DateTime? ReadAsDateTimeInternal()
{
_readType = ReadType.ReadAsDateTime;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
} while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Date)
return (DateTime)Value;
if (TokenType == JsonToken.Null)
return null;
DateTime dt;
if (TokenType == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (TokenType == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
private bool IsWrappedInTypeObject()
{
_readType = ReadType.Read;
if (TokenType == JsonToken.StartObject)
{
if (!ReadInternal())
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
if (Value.ToString() == "$type")
{
ReadInternal();
if (Value != null && Value.ToString().StartsWith("System.Byte[]"))
{
ReadInternal();
if (Value.ToString() == "$value")
{
return true;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
return false;
}
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (TokenType == JsonToken.PropertyName)
Read();
if (IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object value)
{
_tokenType = newToken;
_value = value;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonContainerType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonContainerType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
break;
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string) value;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
_currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished;
UpdateScopeWithFinishedValue();
break;
}
}
private void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
_currentPosition.Position++;
}
private void ValidateEnd(JsonToken endToken)
{
JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
_currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished;
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JsonContainerType currentObject = Peek();
switch (currentObject)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Constructor;
break;
case JsonContainerType.None:
_currentState = State.Finished;
break;
default:
throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonContainerType.Object;
case JsonToken.EndArray:
return JsonContainerType.Array;
case JsonToken.EndConstructor:
return JsonContainerType.Constructor;
default:
throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
void IDisposable.Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
Close();
}
/// <summary>
/// Changes the <see cref="State"/> to Closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_tokenType = JsonToken.None;
_value = null;
}
}
}
#endif
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.Project.Automation
{
/// <summary>
/// Contains ProjectItem objects
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ComVisible(true), CLSCompliant(false)]
public class OAProjectItems : OANavigableProjectItems
{
#region ctor
public OAProjectItems(OAProject project, HierarchyNode nodeWithItems)
: base(project, nodeWithItems)
{
}
#endregion
#region EnvDTE.ProjectItems
/// <summary>
/// Creates a new project item from an existing item template file and adds it to the project.
/// </summary>
/// <param name="fileName">The full path and file name of the template project file.</param>
/// <param name="name">The file name to use for the new project item.</param>
/// <returns>A ProjectItem object. </returns>
public override EnvDTE.ProjectItem AddFromTemplate(string fileName, string name)
{
if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed)
{
throw new InvalidOperationException();
}
ProjectNode proj = this.Project.Project;
EnvDTE.ProjectItem itemAdded = null;
using(AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
// Determine the operation based on the extension of the filename.
// We should run the wizard only if the extension is vstemplate
// otherwise it's a clone operation
VSADDITEMOPERATION op;
if(Utilities.IsTemplateFile(fileName))
{
op = VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD;
}
else
{
op = VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE;
}
VSADDRESULT[] result = new VSADDRESULT[1];
// It is not a very good idea to throw since the AddItem might return Cancel or Abort.
// The problem is that up in the call stack the wizard code does not check whether it has received a ProjectItem or not and will crash.
// The other problem is that we cannot get add wizard dialog back if a cancel or abort was returned because we throw and that code will never be executed. Typical catch 22.
ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, name, 0, new string[1] { fileName }, IntPtr.Zero, result));
string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems);
string templateFilePath = System.IO.Path.Combine(fileDirectory, name);
itemAdded = this.EvaluateAddResult(result[0], templateFilePath);
}
return itemAdded;
}
/// <summary>
/// Adds a folder to the collection of ProjectItems with the given name.
///
/// The kind must be null, empty string, or the string value of vsProjectItemKindPhysicalFolder.
/// Virtual folders are not supported by this implementation.
/// </summary>
/// <param name="name">The name of the new folder to add</param>
/// <param name="kind">A string representing a Guid of the folder kind.</param>
/// <returns>A ProjectItem representing the newly added folder.</returns>
public override ProjectItem AddFolder(string name, string kind)
{
if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed)
{
throw new InvalidOperationException();
}
//Verify name is not null or empty
Utilities.ValidateFileName(this.Project.Project.Site, name);
//Verify that kind is null, empty, or a physical folder
if(!(string.IsNullOrEmpty(kind) || kind.Equals(EnvDTE.Constants.vsProjectItemKindPhysicalFolder)))
{
throw new ArgumentException("Parameter specification for AddFolder was not meet", "kind");
}
for(HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
if(child.Caption.Equals(name, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Folder already exists with the name '{0}'", name));
}
}
ProjectNode proj = this.Project.Project;
HierarchyNode newFolder = null;
using(AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
//In the case that we are adding a folder to a folder, we need to build up
//the path to the project node.
name = Path.Combine(this.NodeWithItems.VirtualNodeName, name);
newFolder = proj.CreateFolderNodes(name);
}
return newFolder.GetAutomationObject() as ProjectItem;
}
/// <summary>
/// Copies a source file and adds it to the project.
/// </summary>
/// <param name="filePath">The path and file name of the project item to be added.</param>
/// <returns>A ProjectItem object. </returns>
public override EnvDTE.ProjectItem AddFromFileCopy(string filePath)
{
return this.AddItem(filePath, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE);
}
/// <summary>
/// Adds a project item from a file that is installed in a project directory structure.
/// </summary>
/// <param name="fileName">The file name of the item to add as a project item. </param>
/// <returns>A ProjectItem object. </returns>
public override EnvDTE.ProjectItem AddFromFile(string fileName)
{
// TODO: VSADDITEMOP_LINKTOFILE
return this.AddItem(fileName, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE);
}
#endregion
#region helper methods
/// <summary>
/// Adds an item to the project.
/// </summary>
/// <param name="path">The full path of the item to add.</param>
/// <param name="op">The <paramref name="VSADDITEMOPERATION"/> to use when adding the item.</param>
/// <returns>A ProjectItem object. </returns>
protected virtual EnvDTE.ProjectItem AddItem(string path, VSADDITEMOPERATION op)
{
if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed)
{
throw new InvalidOperationException();
}
ProjectNode proj = this.Project.Project;
EnvDTE.ProjectItem itemAdded = null;
using(AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
VSADDRESULT[] result = new VSADDRESULT[1];
ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, path, 0, new string[1] { path }, IntPtr.Zero, result));
string fileName = System.IO.Path.GetFileName(path);
string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems);
string filePathInProject = System.IO.Path.Combine(fileDirectory, fileName);
itemAdded = this.EvaluateAddResult(result[0], filePathInProject);
}
return itemAdded;
}
/// <summary>
/// Evaluates the result of an add operation.
/// </summary>
/// <param name="result">The <paramref name="VSADDRESULT"/> returned by the Add methods</param>
/// <param name="path">The full path of the item added.</param>
/// <returns>A ProjectItem object.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
protected virtual EnvDTE.ProjectItem EvaluateAddResult(VSADDRESULT result, string path)
{
if(result == VSADDRESULT.ADDRESULT_Success)
{
HierarchyNode nodeAdded = this.NodeWithItems.FindChild(path);
Debug.Assert(nodeAdded != null, "We should have been able to find the new element in the hierarchy");
if(nodeAdded != null)
{
EnvDTE.ProjectItem item = null;
if(nodeAdded is FileNode)
{
item = new OAFileItem(this.Project, nodeAdded as FileNode);
}
else if(nodeAdded is NestedProjectNode)
{
item = new OANestedProjectItem(this.Project, nodeAdded as NestedProjectNode);
}
else
{
item = new OAProjectItem<HierarchyNode>(this.Project, nodeAdded);
}
this.Items.Add(item);
return item;
}
}
return null;
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Input;
using Microsoft.PythonTools.Commands;
using Microsoft.PythonTools.EnvironmentsList;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Options;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
using SR = Microsoft.PythonTools.Project.SR;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
namespace Microsoft.PythonTools.InterpreterList {
[Guid(PythonConstants.InterpreterListToolWindowGuid)]
sealed class InterpreterListToolWindow : ToolWindowPane {
private IServiceProvider _site;
private PythonToolsService _pyService;
private IInterpreterOptionsService _service;
private Redirector _outputWindow;
private IVsStatusbar _statusBar;
public InterpreterListToolWindow() { }
protected override void OnCreate() {
base.OnCreate();
_site = (IServiceProvider)this;
_pyService = _site.GetPythonToolsService();
// TODO: Get PYEnvironment added to image list
BitmapImageMoniker = KnownMonikers.DockPanel;
Caption = SR.GetString(SR.Environments);
_service = _site.GetComponentModel().GetService<IInterpreterOptionsService>();
_outputWindow = OutputWindowRedirector.GetGeneral(_site);
Debug.Assert(_outputWindow != null);
_statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;
var list = new ToolWindow();
list.ViewCreated += List_ViewCreated;
list.CommandBindings.Add(new CommandBinding(
EnvironmentView.OpenInteractiveWindow,
OpenInteractiveWindow_Executed,
OpenInteractiveWindow_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentView.OpenInteractiveOptions,
OpenInteractiveOptions_Executed,
OpenInteractiveOptions_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentPathsExtension.StartInterpreter,
StartInterpreter_Executed,
StartInterpreter_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentPathsExtension.StartWindowsInterpreter,
StartInterpreter_Executed,
StartInterpreter_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
ApplicationCommands.Help,
OnlineHelp_Executed,
OnlineHelp_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
ToolWindow.UnhandledException,
UnhandledException_Executed,
UnhandledException_CanExecute
));
list.Service = _service;
Content = list;
}
private void List_ViewCreated(object sender, EnvironmentViewEventArgs e) {
var view = e.View;
var pep = new PipExtensionProvider(view.Factory);
pep.GetElevateSetting += PipExtensionProvider_GetElevateSetting;
pep.OperationStarted += PipExtensionProvider_OperationStarted;
pep.OutputTextReceived += PipExtensionProvider_OutputTextReceived;
pep.ErrorTextReceived += PipExtensionProvider_ErrorTextReceived;
pep.OperationFinished += PipExtensionProvider_OperationFinished;
view.Extensions.Add(pep);
var _withDb = view.Factory as PythonInterpreterFactoryWithDatabase;
if (_withDb != null) {
view.Extensions.Add(new DBExtensionProvider(_withDb));
}
var model = _site.GetComponentModel();
if (model != null) {
try {
foreach (var provider in model.GetExtensions<IEnvironmentViewExtensionProvider>()) {
try {
var ext = provider.CreateExtension(view);
if (ext != null) {
view.Extensions.Add(ext);
}
} catch (Exception ex) {
LogLoadException(provider, ex);
}
}
} catch (Exception ex2) {
LogLoadException(null, ex2);
}
}
}
private void LogLoadException(IEnvironmentViewExtensionProvider provider, Exception ex) {
string message;
if (provider == null) {
message = SR.GetString(SR.ErrorLoadingEnvironmentViewExtensions, ex);
} else {
message = SR.GetString(SR.ErrorLoadingEnvironmentViewExtension, provider.GetType().FullName, ex);
}
Debug.Fail(message);
var log = _site.GetService(typeof(SVsActivityLog)) as IVsActivityLog;
if (log != null) {
log.LogEntry(
(uint)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR,
SR.ProductName,
message
);
}
}
private void PipExtensionProvider_GetElevateSetting(object sender, ValueEventArgs<bool> e) {
e.Value = _pyService.GeneralOptions.ElevatePip;
}
private void PipExtensionProvider_OperationStarted(object sender, ValueEventArgs<string> e) {
_outputWindow.WriteLine(e.Value);
if (_statusBar != null) {
_statusBar.SetText(e.Value);
}
if (_pyService.GeneralOptions.ShowOutputWindowForPackageInstallation) {
_outputWindow.ShowAndActivate();
}
}
private void PipExtensionProvider_OutputTextReceived(object sender, ValueEventArgs<string> e) {
_outputWindow.WriteLine(e.Value);
}
private void PipExtensionProvider_ErrorTextReceived(object sender, ValueEventArgs<string> e) {
_outputWindow.WriteErrorLine(e.Value);
}
private void PipExtensionProvider_OperationFinished(object sender, ValueEventArgs<string> e) {
_outputWindow.WriteLine(e.Value);
if (_statusBar != null) {
_statusBar.SetText(e.Value);
}
if (_pyService.GeneralOptions.ShowOutputWindowForPackageInstallation) {
_outputWindow.ShowAndActivate();
}
}
private void UnhandledException_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = e.Parameter is ExceptionDispatchInfo;
}
private void UnhandledException_Executed(object sender, ExecutedRoutedEventArgs e) {
var ex = (ExceptionDispatchInfo)e.Parameter;
Debug.Assert(ex != null, "Unhandled exception with no exception object");
if (ex.SourceException is PipException) {
// Don't report Pip exceptions. The output messages have
// already been handled.
return;
}
var td = TaskDialog.ForException(_site, ex.SourceException, String.Empty, PythonConstants.IssueTrackerUrl);
td.Title = SR.ProductName;
td.ShowModal();
}
private void OpenInteractiveWindow_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = view != null &&
view.Factory != null &&
view.Factory.Configuration != null &&
File.Exists(view.Factory.Configuration.InterpreterPath);
}
private void OpenInteractiveWindow_Executed(object sender, ExecutedRoutedEventArgs e) {
var view = (EnvironmentView)e.Parameter;
var factory = view.Factory;
IVsInteractiveWindow window;
var provider = _service.KnownProviders.OfType<LoadedProjectInterpreterFactoryProvider>().FirstOrDefault();
var vsProject = provider == null ?
null :
provider.GetProject(factory);
var project = vsProject == null ? null : vsProject.GetPythonProject();
try {
window = ExecuteInReplCommand.EnsureReplWindow(_site, factory, project);
} catch (InvalidOperationException ex) {
MessageBox.Show(SR.GetString(SR.ErrorOpeningInteractiveWindow, ex), SR.ProductName);
return;
}
if (window != null) {
var pane = window as ToolWindowPane;
if (pane != null) {
ErrorHandler.ThrowOnFailure(((IVsWindowFrame)pane.Frame).Show());
}
window.Show(true);
}
}
private void OpenInteractiveOptions_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = view != null && view.Factory != null && view.Factory.CanBeConfigured();
}
private void OpenInteractiveOptions_Executed(object sender, ExecutedRoutedEventArgs e) {
PythonToolsPackage.ShowOptionPage(
_site,
typeof(PythonInteractiveOptionsPage),
((EnvironmentView)e.Parameter).Factory
);
}
private void StartInterpreter_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = view != null && File.Exists(e.Command == EnvironmentPathsExtension.StartInterpreter ?
view.Factory.Configuration.InterpreterPath :
view.Factory.Configuration.WindowsInterpreterPath);
e.Handled = true;
}
private void StartInterpreter_Executed(object sender, ExecutedRoutedEventArgs e) {
var view = (EnvironmentView)e.Parameter;
var factory = view.Factory;
var psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.FileName = e.Command == EnvironmentPathsExtension.StartInterpreter ?
factory.Configuration.InterpreterPath :
factory.Configuration.WindowsInterpreterPath;
psi.WorkingDirectory = factory.Configuration.PrefixPath;
var provider = _service.KnownProviders.OfType<LoadedProjectInterpreterFactoryProvider>().FirstOrDefault();
var vsProject = provider == null ?
null :
provider.GetProject(factory);
var project = vsProject == null ? null : vsProject.GetPythonProject();
if (project != null) {
psi.EnvironmentVariables[factory.Configuration.PathEnvironmentVariable] =
string.Join(";", project.GetSearchPaths());
} else {
psi.EnvironmentVariables[factory.Configuration.PathEnvironmentVariable] = string.Empty;
}
Process.Start(psi);
}
private void OnlineHelp_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = _site != null;
e.Handled = true;
}
private void OnlineHelp_Executed(object sender, ExecutedRoutedEventArgs e) {
CommonPackage.OpenVsWebBrowser(_site, PythonToolsPackage.InterpreterHelpUrl);
e.Handled = true;
}
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
namespace CocosSharp
{
public class CCSpriteBatchNode : CCNode, ICCTexture
{
const int defaultSpriteBatchCapacity = 29;
#region Properties
public CCTextureAtlas TextureAtlas { get ; private set; }
public CCRawList<CCSprite> Descendants { get; private set; }
public CCBlendFunc BlendFunc { get; set; }
public bool IsAntialiased
{
get { return Texture.IsAntialiased; }
set { Texture.IsAntialiased = value; }
}
public virtual CCTexture2D Texture
{
get { return TextureAtlas.Texture; }
set
{
TextureAtlas.Texture = value;
UpdateBlendFunc();
}
}
// Size of batch node in world space makes no sense
public override CCSize ContentSize
{
get { return CCSize.Zero; }
set
{
}
}
public override CCAffineTransform AffineLocalTransform
{
get { return CCAffineTransform.Identity; }
}
#endregion Properties
#region Constructors
// We need this constructor for all the subclasses that initialise by directly calling InitCCSpriteBatchNode
public CCSpriteBatchNode()
{
}
public CCSpriteBatchNode(CCTexture2D tex, int capacity=defaultSpriteBatchCapacity)
{
InitCCSpriteBatchNode(tex, capacity);
}
public CCSpriteBatchNode(string fileImage, int capacity=defaultSpriteBatchCapacity)
: this(CCTextureCache.SharedTextureCache.AddImage(fileImage), capacity)
{
}
protected void InitCCSpriteBatchNode(CCTexture2D tex, int capacity=defaultSpriteBatchCapacity)
{
BlendFunc = CCBlendFunc.AlphaBlend;
if (capacity == 0)
{
capacity = defaultSpriteBatchCapacity;
}
TextureAtlas = new CCTextureAtlas(tex, capacity);
UpdateBlendFunc();
// no lazy alloc in this node
Children = new CCRawList<CCNode>(capacity);
Descendants = new CCRawList<CCSprite>(capacity);
}
#endregion Constructors
public override void Visit()
{
// CAREFUL:
// This visit is almost identical to CocosNode#visit
// with the exception that it doesn't call visit on it's children
//
// The alternative is to have a void CCSprite#visit, but
// although this is less mantainable, is faster
//
if (!Visible)
{
return;
}
Window.DrawManager.PushMatrix();
if (Grid != null && Grid.Active)
{
Grid.BeforeDraw();
TransformAncestors();
}
SortAllChildren();
CCDrawManager.SharedDrawManager.SetIdentityMatrix();
Draw();
if (Grid != null && Grid.Active)
{
Grid.AfterDraw(this);
}
Window.DrawManager.PopMatrix();
}
protected override void Draw()
{
// Optimization: Fast Dispatch
if (TextureAtlas.TotalQuads == 0)
{
return;
}
Window.DrawManager.BlendFunc(BlendFunc);
TextureAtlas.DrawQuads();
}
#region Child management
public override void AddChild(CCNode child, int zOrder = 0, int tag = CCNode.TagInvalid)
{
Debug.Assert(child != null, "child should not be null");
Debug.Assert(child is CCSprite, "CCSpriteBatchNode only supports CCSprites as children");
var pSprite = (CCSprite) child;
// check CCSprite is using the same texture id
Debug.Assert(pSprite.Texture.Name == TextureAtlas.Texture.Name, "CCSprite is not using the same texture id");
base.AddChild(child, zOrder, tag);
AppendChild(pSprite);
}
public override void ReorderChild(CCNode child, int zOrder)
{
Debug.Assert(child != null, "the child should not be null");
Debug.Assert(Children.Contains(child), "Child doesn't belong to Sprite");
if (zOrder == child.ZOrder)
{
return;
}
//set the z-order and sort later
base.ReorderChild(child, zOrder);
}
public override void RemoveChild(CCNode child, bool cleanup)
{
var pSprite = (CCSprite) child;
Debug.Assert(Children.Contains(pSprite), "sprite batch node should contain the child");
// cleanup before removing
RemoveSpriteFromAtlas(pSprite);
base.RemoveChild(pSprite, cleanup);
}
public void RemoveChildAtIndex(int index, bool doCleanup)
{
RemoveChild((Children[index]), doCleanup);
}
public override void RemoveAllChildren(bool cleanup)
{
// Invalidate atlas index. issue #569
// useSelfRender should be performed on all descendants. issue #1216
CCSprite[] elements = Descendants.Elements;
for (int i = 0, count = Descendants.Count; i < count; i++)
{
elements[i].BatchNode = null;
}
base.RemoveAllChildren(cleanup);
Descendants.Clear();
TextureAtlas.RemoveAllQuads();
}
public override void SortAllChildren()
{
if (IsReorderChildDirty)
{
int count = Children.Count;
CCNode[] elements = Children.Elements;
Array.Sort(elements, 0, count, this);
//sorted now check all children
if (count > 0)
{
//first sort all children recursively based on zOrder
for (int i = 0; i < count; i++)
{
elements[i].SortAllChildren();
}
int index = 0;
//fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact)
// and at the same time reorder descedants and the quads to the right index
for (int i = 0; i < count; i++)
{
UpdateAtlasIndex((CCSprite) elements[i], ref index);
}
}
IsReorderChildDirty = false;
}
}
public void InsertChild(CCSprite sprite, int uIndex)
{
if (TextureAtlas.TotalQuads == TextureAtlas.Capacity)
{
IncreaseAtlasCapacity();
}
TextureAtlas.InsertQuad(ref sprite.transformedQuad, uIndex);
sprite.BatchNode = this;
sprite.AtlasIndex = uIndex;
Descendants.Insert(uIndex, sprite);
// update indices
CCSprite[] delements = Descendants.Elements;
for (int i = uIndex + 1, count = Descendants.Count; i < count; i++)
{
delements[i].AtlasIndex++;
}
// add children recursively
CCRawList<CCNode> children = sprite.Children;
if (children != null && children.Count > 0)
{
CCNode[] elements = children.Elements;
for (int j = 0, count = children.Count; j < count; j++)
{
var child = (CCSprite) elements[j];
uIndex = AtlasIndexForChild(child, child.ZOrder);
InsertChild(child, uIndex);
}
}
}
// addChild helper, faster than insertChild
public void AppendChild(CCSprite sprite)
{
IsReorderChildDirty = true;
sprite.BatchNode = this;
if (TextureAtlas.TotalQuads == TextureAtlas.Capacity)
{
IncreaseAtlasCapacity();
}
Descendants.Add(sprite);
int index = Descendants.Count - 1;
sprite.AtlasIndex = index;
TextureAtlas.UpdateQuad(ref sprite.transformedQuad, index);
// add children recursively
CCRawList<CCNode> children = sprite.Children;
if (children != null && children.Count > 0)
{
CCNode[] elements = children.Elements;
int count = children.Count;
for (int i = 0; i < count; i++)
{
AppendChild((CCSprite) elements[i]);
}
}
}
#endregion Child management
void UpdateAtlasIndex(CCSprite sprite, ref int curIndex)
{
int count = 0;
CCRawList<CCNode> pArray = sprite.Children;
if (pArray != null)
{
count = pArray.Count;
}
int oldIndex = 0;
if (count == 0)
{
oldIndex = sprite.AtlasIndex;
sprite.AtlasIndex = curIndex;
sprite.OrderOfArrival = 0;
if (oldIndex != curIndex)
{
Swap(oldIndex, curIndex);
}
curIndex++;
}
else
{
bool needNewIndex = true;
if (pArray.Elements[0].ZOrder >= 0)
{
//all children are in front of the parent
oldIndex = sprite.AtlasIndex;
sprite.AtlasIndex = curIndex;
sprite.OrderOfArrival = 0;
if (oldIndex != curIndex)
{
Swap(oldIndex, curIndex);
}
curIndex++;
needNewIndex = false;
}
for (int i = 0; i < count; i++)
{
var child = (CCSprite) pArray.Elements[i];
if (needNewIndex && child.ZOrder >= 0)
{
oldIndex = sprite.AtlasIndex;
sprite.AtlasIndex = curIndex;
sprite.OrderOfArrival = 0;
if (oldIndex != curIndex)
{
Swap(oldIndex, curIndex);
}
curIndex++;
needNewIndex = false;
}
UpdateAtlasIndex(child, ref curIndex);
}
if (needNewIndex)
{
//all children have a zOrder < 0)
oldIndex = sprite.AtlasIndex;
sprite.AtlasIndex = curIndex;
sprite.OrderOfArrival = 0;
if (oldIndex != curIndex)
{
Swap(oldIndex, curIndex);
}
curIndex++;
}
}
}
void Swap(int oldIndex, int newIndex)
{
CCSprite[] sprites = Descendants.Elements;
CCRawList<CCV3F_C4B_T2F_Quad> quads = TextureAtlas.Quads;
TextureAtlas.Dirty = true;
CCSprite tempItem = sprites[oldIndex];
CCV3F_C4B_T2F_Quad tempItemQuad = quads[oldIndex];
//update the index of other swapped item
sprites[newIndex].AtlasIndex = oldIndex;
sprites[oldIndex] = sprites[newIndex];
quads[oldIndex] = quads[newIndex];
sprites[newIndex] = tempItem;
quads[newIndex] = tempItemQuad;
}
public void ReorderBatch(bool reorder)
{
IsReorderChildDirty = reorder;
}
public void IncreaseAtlasCapacity()
{
// if we're going beyond the current TextureAtlas's capacity,
// all the previously initialized sprites will need to redo their texture coords
// this is likely computationally expensive
int quantity = (TextureAtlas.Capacity + 1) * 4 / 3;
CCLog.Log(string.Format(
"CocosSharp: CCSpriteBatchNode: resizing TextureAtlas capacity from [{0}] to [{1}].",
TextureAtlas.Capacity, quantity));
TextureAtlas.ResizeCapacity(quantity);
}
public int RebuildIndexInOrder(CCSprite pobParent, int uIndex)
{
CCRawList<CCNode> pChildren = pobParent.Children;
if (pChildren != null && pChildren.Count > 0)
{
CCNode[] elements = pChildren.Elements;
for (int i = 0, count = pChildren.Count; i < count; i++)
{
if (elements[i].ZOrder < 0)
{
uIndex = RebuildIndexInOrder((CCSprite) pChildren[i], uIndex);
}
}
}
// ignore self (batch node)
if (!pobParent.Equals(this))
{
pobParent.AtlasIndex = uIndex;
uIndex++;
}
if (pChildren != null && pChildren.Count > 0)
{
CCNode[] elements = pChildren.Elements;
for (int i = 0, count = pChildren.Count; i < count; i++)
{
if (elements[i].ZOrder >= 0)
{
uIndex = RebuildIndexInOrder((CCSprite) elements[i], uIndex);
}
}
}
return uIndex;
}
public int HighestAtlasIndexInChild(CCSprite pSprite)
{
CCRawList<CCNode> pChildren = pSprite.Children;
if (pChildren == null || pChildren.Count == 0)
{
return pSprite.AtlasIndex;
}
else
{
return HighestAtlasIndexInChild((CCSprite) pChildren.Elements[pChildren.Count - 1]);
}
}
public int LowestAtlasIndexInChild(CCSprite pSprite)
{
CCRawList<CCNode> pChildren = pSprite.Children;
if (pChildren == null || pChildren.Count == 0)
{
return pSprite.AtlasIndex;
}
else
{
return LowestAtlasIndexInChild((CCSprite) pChildren.Elements[0]);
}
}
public int AtlasIndexForChild(CCSprite pobSprite, int nZ)
{
CCRawList<CCNode> pBrothers = pobSprite.Parent.Children;
int uChildIndex = pBrothers.IndexOf(pobSprite);
// ignore parent Z if parent is spriteSheet
bool bIgnoreParent = (pobSprite.Parent == this);
CCSprite pPrevious = null;
if (uChildIndex > 0)
{
pPrevious = (CCSprite) pBrothers[uChildIndex - 1];
}
// first child of the sprite sheet
if (bIgnoreParent)
{
if (uChildIndex == 0)
{
return 0;
}
return HighestAtlasIndexInChild(pPrevious) + 1;
}
// parent is a CCSprite, so, it must be taken into account
// first child of an CCSprite ?
if (uChildIndex == 0)
{
var p = (CCSprite) pobSprite.Parent;
// less than parent and brothers
if (nZ < 0)
{
return p.AtlasIndex;
}
else
{
return p.AtlasIndex + 1;
}
}
else
{
// previous & sprite belong to the same branch
if ((pPrevious.ZOrder < 0 && nZ < 0) || (pPrevious.ZOrder >= 0 && nZ >= 0))
{
return HighestAtlasIndexInChild(pPrevious) + 1;
}
// else (previous < 0 and sprite >= 0 )
var p = (CCSprite) pobSprite.Parent;
return p.AtlasIndex + 1;
}
}
public void RemoveSpriteFromAtlas(CCSprite sprite)
{
// remove from TextureAtlas
TextureAtlas.RemoveQuadAtIndex(sprite.AtlasIndex);
// Cleanup sprite. It might be reused (issue #569)
sprite.BatchNode = null;
int uIndex = Descendants.IndexOf(sprite);
if (uIndex >= 0)
{
Descendants.RemoveAt(uIndex);
// update all sprites beyond this one
int count = Descendants.Count;
CCSprite[] elements = Descendants.Elements;
for (; uIndex < count; ++uIndex)
{
elements[uIndex].AtlasIndex--;
}
}
// remove children recursively
CCRawList<CCNode> pChildren = sprite.Children;
if (pChildren != null && pChildren.Count > 0)
{
CCNode[] elements = pChildren.Elements;
for (int i = 0, count = pChildren.Count; i < count; i++)
{
RemoveSpriteFromAtlas((CCSprite) elements[i]);
}
}
}
void UpdateBlendFunc()
{
if (!TextureAtlas.Texture.HasPremultipliedAlpha)
{
BlendFunc = CCBlendFunc.NonPremultiplied;
}
}
//CCSpriteSheet Extension
//implementation CCSpriteSheet (TMXTiledMapExtension)
protected void InsertQuadFromSprite(CCSprite sprite, int index)
{
Debug.Assert(sprite != null, "Argument must be non-NULL");
while (index >= TextureAtlas.Capacity || TextureAtlas.Capacity == TextureAtlas.TotalQuads)
{
IncreaseAtlasCapacity();
}
//
// update the quad directly. Don't add the sprite to the scene graph
//
sprite.BatchNode = this;
sprite.AtlasIndex = index;
TextureAtlas.InsertQuad(ref sprite.transformedQuad, index);
// XXX: updateTransform will update the textureAtlas too using updateQuad.
// XXX: so, it should be AFTER the insertQuad
sprite.UpdateTransformedSpriteTextureQuads();
}
protected void UpdateQuadFromSprite(CCSprite sprite, int index)
{
Debug.Assert(sprite != null, "Argument must be non-NULL");
while (index >= TextureAtlas.Capacity || TextureAtlas.Capacity == TextureAtlas.TotalQuads)
{
IncreaseAtlasCapacity();
}
//
// update the quad directly. Don't add the sprite to the scene graph
//
sprite.BatchNode = this;
sprite.AtlasIndex = index;
// UpdateTransform updates the textureAtlas quad
sprite.UpdateTransformedSpriteTextureQuads();
}
protected CCSpriteBatchNode AddSpriteWithoutQuad(CCSprite child, int z, int aTag)
{
Debug.Assert(child != null, "Argument must be non-NULL");
// quad index is Z
child.AtlasIndex = z;
// XXX: optimize with a binary search
int i = 0;
if (Descendants.Count > 0)
{
CCSprite[] elements = Descendants.Elements;
for (int j = 0, count = Descendants.Count; j < count; j++)
{
if (elements[i].AtlasIndex >= z)
{
++i;
}
}
}
Descendants.Insert(i, child);
base.AddChild(child, z, aTag);
//#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order
ReorderBatch(false);
return this;
}
}
}
| |
// 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.Text;
using System.Globalization;
using TestLibrary;
public class StringEquals
{
public static string[] InterestingStrings = new string[] { null, "", "a", "1", "-", "A", "!", "abc", "aBc", "a\u0400Bc", "I", "i", "\u0130", "\u0131", "A", "\uFF21", "\uFE57"};
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Compare interesting strings ordinally");
try
{
foreach (string s in InterestingStrings)
{
foreach (string r in InterestingStrings)
{
retVal &= TestStrings(s, r);
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Compare many characters");
try
{
for (int i = 0; i < 40; i++) // Ok, 40 isn't that many... but this takes way too long
{
char c = Generator.GetChar(-55);
if (string.Equals(new string(new char[] { c }), new string(new char[] { c }), StringComparison.Ordinal) != true)
{
TestLibrary.TestFramework.LogError("002.1", "Character " + i.ToString() + " is not equal to itself ordinally!");
retVal = false;
}
for (int j = 0; j < (int)c; j++)
{
bool compareResult = string.Equals(new string(new char[] { c }), new string(new char[] { (char)j }), StringComparison.Ordinal);
if (compareResult != false)
{
TestLibrary.TestFramework.LogError("002.2", "Character " + ((int)c).ToString() + " is equal to " + j.ToString() + ", Compare result: " + compareResult.ToString());
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.4", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Compare many strings");
try
{
for (int i = 0; i < 1000; i++)
{
string str1 = Generator.GetString(-55, false, 5, 20);
string str2 = Generator.GetString(-55, false, 5, 20);
if (string.Equals(str1, str1, StringComparison.Ordinal) != true)
{
TestLibrary.TestFramework.LogError("003.1", "Comparison not as expected! Actual result: " + string.Equals(str1, str1, StringComparison.Ordinal).ToString() + ", Expected result: 0");
TestLibrary.TestFramework.LogInformation("String 1: <" + str1 + "> : " + BytesFromString(str1) + "\nString 2: <" + str1 + "> : " + BytesFromString(str1));
retVal = false;
}
if (string.Equals(str2, str2, StringComparison.Ordinal) != true)
{
TestLibrary.TestFramework.LogError("003.2", "Comparison not as expected! Actual result: " + string.Equals(str2, str2, StringComparison.Ordinal).ToString() + ", Expected result: 0");
TestLibrary.TestFramework.LogInformation("String 1: <" + str2 + "> : " + BytesFromString(str2) + "\nString 2: <" + str2 + "> : " + BytesFromString(str2));
retVal = false;
}
TestStrings(str1, str2);
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.4", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Specific regression cases");
try
{
CultureInfo oldCi = TestLibrary.Utilities.CurrentCulture;
TestLibrary.Utilities.CurrentCulture = new CultureInfo("hu-HU");
retVal &= TestStrings("dzsdzs", "ddzs");
TestLibrary.Utilities.CurrentCulture = oldCi;
retVal &= TestStrings("\u00C0nimal", "A\u0300nimal");
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public static int Main()
{
StringEquals test = new StringEquals();
TestLibrary.TestFramework.BeginTestCase("StringEquals");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private bool TestStrings(string str1, string str2)
{
bool retVal = true;
bool expectValue = PredictValue(str1, str2);
bool actualValue = string.Equals(str1, str2, StringComparison.Ordinal);
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("001.1", "Comparison not as expected! Actual result: " + actualValue + ", Expected result: " + expectValue);
TestLibrary.TestFramework.LogInformation("String 1: <" + str1 + "> : " + BytesFromString(str1) + "\nString 2: <" + str2 + "> : " + BytesFromString(str2));
retVal = false;
}
return retVal;
}
bool PredictValue(string str1, string str2)
{
if (str1 == null)
{
if (str2 == null) return true;
else return false;
}
if (str2 == null) return false;
for (int i = 0; i < str1.Length; i++)
{
if (i >= str2.Length) return false;
if ((int)str1[i] > (int)str2[i]) return false;
if ((int)str1[i] < (int)str2[i]) return false;
}
if (str2.Length > str1.Length) return false;
return true;
}
private static string BytesFromString(string str)
{
if (str == null) return string.Empty;
StringBuilder output = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
output.Append(TestLibrary.Utilities.ByteArrayToString(BitConverter.GetBytes(str[i])));
if (i != (str.Length - 1)) output.Append(", ");
}
return output.ToString();
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using Oranikle.Report.Engine;
namespace Oranikle.Report.Engine
{
/// <summary>
/// Process a custom instance method request.
/// </summary>
[Serializable]
public class FunctionCustomInstance : IExpr
{
string _Cls; // class name
string _Func; // function/operator
IExpr[] _Args; // arguments
ReportClass _Rc; // ReportClass
TypeCode _ReturnTypeCode; // the return type
Type[] _ArgTypes; // argument types
/// <summary>
/// passed ReportClass, function name, and args for evaluation
/// </summary>
public FunctionCustomInstance(ReportClass rc, string f, IExpr[] a, TypeCode type)
{
_Cls = null;
_Func = f;
_Args = a;
_Rc = rc;
_ReturnTypeCode = type;
_ArgTypes = new Type[a.Length];
int i=0;
foreach (IExpr ex in a)
{
_ArgTypes[i++] = XmlUtil.GetTypeFromTypeCode(ex.GetTypeCode());
}
}
public TypeCode GetTypeCode()
{
return _ReturnTypeCode;
}
public bool IsConstant()
{
return false; // Can't know what the function does
}
public IExpr ConstantOptimization()
{
// Do constant optimization on all the arguments
for (int i=0; i < _Args.GetLength(0); i++)
{
IExpr e = (IExpr)_Args[i];
_Args[i] = e.ConstantOptimization();
}
// Can't assume that the function doesn't vary
// based on something other than the args e.g. Now()
return this;
}
// Evaluate is for interpretation (and is relatively slow)
public object Evaluate(Report rpt, Row row)
{
// get the results
object[] argResults = new object[_Args.Length];
int i=0;
bool bUseArg=true;
bool bNull = false;
foreach(IExpr a in _Args)
{
argResults[i] = a.Evaluate(rpt, row);
if (argResults[i] == null)
bNull = true;
else if (argResults[i].GetType() != _ArgTypes[i])
bUseArg = false;
i++;
}
// we build the arguments based on the type
Type[] argTypes = bUseArg || bNull? _ArgTypes: Type.GetTypeArray(argResults);
// We can definitely optimize this by caching some info TODO
// Get ready to call the function
Object returnVal;
object inst = _Rc.Instance(rpt);
Type theClassType=inst.GetType();
MethodInfo mInfo = XmlUtil.GetMethod(theClassType, _Func, argTypes);
if (mInfo == null)
{
throw new Exception(string.Format("{0} method not found in class {1}", _Func, _Cls));
}
returnVal = mInfo.Invoke(inst, argResults);
return returnVal;
}
public double EvaluateDouble(Report rpt, Row row)
{
return Convert.ToDouble(Evaluate(rpt, row));
}
public decimal EvaluateDecimal(Report rpt, Row row)
{
return Convert.ToDecimal(Evaluate(rpt, row));
}
public int EvaluateInt32(Report rpt, Row row)
{
return Convert.ToInt32(Evaluate(rpt, row));
}
public string EvaluateString(Report rpt, Row row)
{
return Convert.ToString(Evaluate(rpt, row));
}
public DateTime EvaluateDateTime(Report rpt, Row row)
{
return Convert.ToDateTime(Evaluate(rpt, row));
}
public bool EvaluateBoolean(Report rpt, Row row)
{
return Convert.ToBoolean(Evaluate(rpt, row));
}
public string Cls
{
get { return _Cls; }
set { _Cls = value; }
}
public string Func
{
get { return _Func; }
set { _Func = value; }
}
public IExpr[] Args
{
get { return _Args; }
set { _Args = value; }
}
}
#if DEBUG
public class TestFunction // for testing CodeModules, Classes, and the Function class
{
int counter=0;
public TestFunction()
{
counter=0;
}
public int count()
{
return counter++;
}
public int count(string s)
{
counter++;
return Convert.ToInt32(s) + counter;
}
static public double sqrt(double x)
{
return Math.Sqrt(x);
}
}
#endif
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// 5.2.58. Used in IFF ATC PDU
/// </summary>
[Serializable]
[XmlRoot]
public partial class SystemID
{
/// <summary>
/// System Type
/// </summary>
private ushort _systemType;
/// <summary>
/// System name, an enumeration
/// </summary>
private ushort _systemName;
/// <summary>
/// System mode
/// </summary>
private byte _systemMode;
/// <summary>
/// Change Options
/// </summary>
private byte _changeOptions;
/// <summary>
/// Initializes a new instance of the <see cref="SystemID"/> class.
/// </summary>
public SystemID()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(SystemID left, SystemID right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(SystemID left, SystemID right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 2; // this._systemType
marshalSize += 2; // this._systemName
marshalSize += 1; // this._systemMode
marshalSize += 1; // this._changeOptions
return marshalSize;
}
/// <summary>
/// Gets or sets the System Type
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "systemType")]
public ushort SystemType
{
get
{
return this._systemType;
}
set
{
this._systemType = value;
}
}
/// <summary>
/// Gets or sets the System name, an enumeration
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "systemName")]
public ushort SystemName
{
get
{
return this._systemName;
}
set
{
this._systemName = value;
}
}
/// <summary>
/// Gets or sets the System mode
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "systemMode")]
public byte SystemMode
{
get
{
return this._systemMode;
}
set
{
this._systemMode = value;
}
}
/// <summary>
/// Gets or sets the Change Options
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "changeOptions")]
public byte ChangeOptions
{
get
{
return this._changeOptions;
}
set
{
this._changeOptions = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteUnsignedShort((ushort)this._systemType);
dos.WriteUnsignedShort((ushort)this._systemName);
dos.WriteUnsignedByte((byte)this._systemMode);
dos.WriteUnsignedByte((byte)this._changeOptions);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._systemType = dis.ReadUnsignedShort();
this._systemName = dis.ReadUnsignedShort();
this._systemMode = dis.ReadUnsignedByte();
this._changeOptions = dis.ReadUnsignedByte();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<SystemID>");
try
{
sb.AppendLine("<systemType type=\"ushort\">" + this._systemType.ToString(CultureInfo.InvariantCulture) + "</systemType>");
sb.AppendLine("<systemName type=\"ushort\">" + this._systemName.ToString(CultureInfo.InvariantCulture) + "</systemName>");
sb.AppendLine("<systemMode type=\"byte\">" + this._systemMode.ToString(CultureInfo.InvariantCulture) + "</systemMode>");
sb.AppendLine("<changeOptions type=\"byte\">" + this._changeOptions.ToString(CultureInfo.InvariantCulture) + "</changeOptions>");
sb.AppendLine("</SystemID>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as SystemID;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(SystemID obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._systemType != obj._systemType)
{
ivarsEqual = false;
}
if (this._systemName != obj._systemName)
{
ivarsEqual = false;
}
if (this._systemMode != obj._systemMode)
{
ivarsEqual = false;
}
if (this._changeOptions != obj._changeOptions)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._systemType.GetHashCode();
result = GenerateHash(result) ^ this._systemName.GetHashCode();
result = GenerateHash(result) ^ this._systemMode.GetHashCode();
result = GenerateHash(result) ^ this._changeOptions.GetHashCode();
return result;
}
}
}
| |
// 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.IO;
using System.Reflection;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Shared;
using Xunit;
namespace Microsoft.Build.UnitTests.XamlDataDrivenToolTask_Tests
{
/// <summary>
/// Test fixture for testing the DataDrivenToolTask class with a fake task generated by XamlTestHelpers.cs
/// Tests to see if certain switches are appended.
/// </summary>
public class GeneratedTask
{
private Assembly _fakeTaskDll;
public GeneratedTask()
{
_fakeTaskDll = XamlTestHelpers.SetupGeneratedCode();
}
/// <summary>
/// Test to see whether all of the correct boolean switches are appended.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestDefaultFlags()
{
object fakeTaskInstance = CreateFakeTask();
CheckCommandLine("/always /Cr:CT", XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
/// <summary>
/// A test to see if all of the reversible flags are generated correctly
/// This test case leaves the default flags the way they are
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestReversibleFlagsWithDefaults()
{
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicReversible", true);
string expectedResult = "/always /Br /Cr:CT";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
/// <summary>
/// A test to see if all of the reversible flags are generated correctly
/// This test case explicitly sets the ComplexReversible to be false
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestReversibleFlagsWithoutDefaults()
{
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicReversible", true);
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexReversible", false);
string expectedResult = "/always /Br /Cr:CF";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
/// <summary>
/// Tests to make sure enums are working well.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestBasicString()
{
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicString", "Enum1");
string expectedResult = "/always /Bs1 /Cr:CT";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestDynamicEnum()
{
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicDynamicEnum", "MyBeforeTarget");
string expectedResult = "/always MyBeforeTarget /Cr:CT";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
/// <summary>
/// Tests the basic string array type
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestBasicStringArray()
{
object fakeTaskInstance = CreateFakeTask();
string[] fakeArray = new string[1];
fakeArray[0] = "FakeStringArray";
XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicStringArray", new object[] { fakeArray });
string expectedResult = "/always /BsaFakeStringArray /Cr:CT";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
/// <summary>
/// Tests the basic string array type, with an array that contains multiple values.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestBasicStringArray_MultipleValues()
{
object fakeTaskInstance = CreateFakeTask();
string[] fakeArray = new string[3];
fakeArray[0] = "Fake";
fakeArray[1] = "String";
fakeArray[2] = "Array";
XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicStringArray", new object[] { fakeArray });
string expectedResult = "/always /BsaFake /BsaString /BsaArray /Cr:CT";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
/// <summary>
/// Tests to see whether the integer appears correctly on the command line
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestInteger()
{
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicInteger", 2);
string expectedResult = "/always /Bi2 /Cr:CT";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
// complex tests
/// <summary>
/// Tests the (full) functionality of a reversible property
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestComplexReversible()
{
// When flag is set to false
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexReversible", false);
string expectedResult = "/always /Cr:CF";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
// When flag is set to true
fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexReversible", true);
expectedResult = "/always /Cr:CT";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestComplexString()
{
// check to see that the resulting value is good
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexString", "LegalValue1");
string expectedResult = "/always /Cr:CT /Lv1";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
/// <summary>
/// Tests the functionality of a string type property
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestComplexStringArray()
{
object fakeTaskInstance = CreateFakeTask();
string[] fakeArray = new string[] { "FakeFile1", "FakeFile2", "FakeFile3" };
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexStringArray", new object[] { fakeArray });
string expectedResult = "/always /Cr:CT /CsaFakeFile1;FakeFile2;FakeFile3";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestComplexIntegerLessThanMin()
{
Assert.Throws<InvalidOperationException>(() =>
{
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexInteger", 2);
}
);
}
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestComplexIntegerGreaterThanMax()
{
Assert.Throws<InvalidOperationException>(() =>
{
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexInteger", 256);
string expectedResult = "/always /Ci256 /Cr:CT";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
);
}
[Fact]
[Trait("Category", "mono-osx-failing")]
public void TestComplexIntegerWithinRange()
{
object fakeTaskInstance = CreateFakeTask();
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexInteger", 128);
string expectedResult = "/always /Cr:CT /Ci128";
CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance));
}
/// <summary>
/// This method checks the generated command line against the expected command line
/// </summary>
/// <param name="expected"></param>
/// <param name="actual"></param>
/// <returns>true if the two are the same, false if they are different</returns>
private void CheckCommandLine(string expected, string actual)
{
Assert.Equal(expected, actual);
}
/// <summary>
/// XamlTaskFactory does not, in and of itself, support the idea of "always" switches or default values. At least
/// for Dev10, the workaround is to create a property as usual, and then specify the required values in the .props
/// file. Since these unit tests are just testing the task itself, this method serves as our ".props file".
/// </summary>
public object CreateFakeTask()
{
object fakeTaskInstance = _fakeTaskDll.CreateInstance("XamlTaskNamespace.FakeTask");
XamlTestHelpers.SetProperty(fakeTaskInstance, "Always", true);
XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexReversible", true);
return fakeTaskInstance;
}
}
/// <summary>
/// Tests for XamlDataDrivenToolTask / XamlTaskFactory in the context of a project file.
/// </summary>
public class ProjectFileTests
{
/// <summary>
/// Tests that when a call to a XamlDataDrivenTask fails, the commandline is reported in the error message.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void CommandLineErrorsReportFullCommandlineAmpersandTemp()
{
string projectFile = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`XamlTaskFactory` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName=`TestTask` TaskFactory=`XamlTaskFactory` AssemblyName=`Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`>
<Task>
<![CDATA[
<ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`>
<Rule Name=`TestTask` ToolName=`findstr.exe`>
<StringProperty Name=`test` />
</Rule>
</ProjectSchemaDefinitions>
]]>
</Task>
</UsingTask>
<Target Name=`XamlTaskFactory`>
<TestTask CommandLineTemplate='findstr'/>
</Target>
</Project>";
string directoryWithAmpersand = "xaml&datadriven";
string newTmp = Path.Combine(Path.GetTempPath(), directoryWithAmpersand);
string oldTmp = Environment.GetEnvironmentVariable("TMP");
try
{
Directory.CreateDirectory(newTmp);
Environment.SetEnvironmentVariable("TMP", newTmp);
Project p = ObjectModelHelpers.CreateInMemoryProject(projectFile);
MockLogger logger = new MockLogger();
bool success = p.Build(logger);
Assert.False(success);
logger.AssertLogContains("FINDSTR");
// Should not be logging ToolTask.ToolCommandFailed, should be logging Xaml.CommandFailed
logger.AssertLogDoesntContain("MSB6006");
logger.AssertLogContains("MSB3721");
}
finally
{
Environment.SetEnvironmentVariable("TMP", oldTmp);
ObjectModelHelpers.DeleteDirectory(newTmp);
if (Directory.Exists(newTmp)) FileUtilities.DeleteWithoutTrailingBackslash(newTmp);
}
}
/// <summary>
/// Tests that when a call to a XamlDataDrivenTask fails, the commandline is reported in the error message.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void CommandLineErrorsReportFullCommandline()
{
string projectFile = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`XamlTaskFactory` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName=`TestTask` TaskFactory=`XamlTaskFactory` AssemblyName=`Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`>
<Task>
<![CDATA[
<ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`>
<Rule Name=`TestTask` ToolName=`echoparameters.exe`>
<StringProperty Name=`test` />
</Rule>
</ProjectSchemaDefinitions>
]]>
</Task>
</UsingTask>
<Target Name=`XamlTaskFactory`>
<TestTask CommandLineTemplate=`where /x` />
</Target>
</Project>";
Project p = ObjectModelHelpers.CreateInMemoryProject(projectFile);
MockLogger logger = new MockLogger();
bool success = p.Build(logger);
Assert.False(success); // "Build should have failed"
// Should not be logging ToolTask.ToolCommandFailed, should be logging Xaml.CommandFailed
logger.AssertLogDoesntContain("MSB6006");
logger.AssertLogContains("MSB3721");
}
/// <summary>
/// Tests that when a call to a XamlDataDrivenTask fails, the commandline is reported in the error message.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void SquareBracketEscaping()
{
string projectFile = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`XamlTaskFactory` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName=`TestTask` TaskFactory=`XamlTaskFactory` AssemblyName=`Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`>
<Task>
<![CDATA[
<ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`>
<Rule Name=`TestTask` ToolName=`echoparameters.exe`>
<StringProperty Name=`test` />
</Rule>
</ProjectSchemaDefinitions>
]]>
</Task>
</UsingTask>
<Target Name=`XamlTaskFactory`>
<TestTask CommandLineTemplate=`echo 1) [test] end` test=`value` />
<TestTask CommandLineTemplate=`echo 2) [[[test] end` test=`value` />
<TestTask CommandLineTemplate=`echo 3) [ [test] end` test=`value` />
<TestTask CommandLineTemplate=`echo 4) [ [test] [test] end` test=`value` />
<TestTask CommandLineTemplate=`echo 5) [test]] end` test=`value` />
<TestTask CommandLineTemplate=`echo 6) [[test]] end` test=`value` />
<TestTask CommandLineTemplate=`echo 7) [[[test]] end` test=`value` />
<TestTask CommandLineTemplate=`echo 8) [notaproperty] end` test=`value` />
<TestTask CommandLineTemplate=`echo 9) [[[notaproperty] end` test=`value` />
<TestTask CommandLineTemplate=`echo 10) [ [notaproperty] end` test=`value` />
<TestTask CommandLineTemplate=`echo 11) [ [nap] [nap] end` test=`value` />
<TestTask CommandLineTemplate=`echo 12) [notaproperty]] end` test=`value` />
<TestTask CommandLineTemplate=`echo 13) [[notaproperty]] end` test=`value` />
<TestTask CommandLineTemplate=`echo 14) [[[notaproperty]] end` test=`value` />
</Target>
</Project>";
Project p = ObjectModelHelpers.CreateInMemoryProject(projectFile);
MockLogger logger = new MockLogger();
bool success = p.Build(logger);
Assert.True(success); // "Build should have succeeded"
logger.AssertLogContains("echo 1) value end");
logger.AssertLogContains("echo 2) [value end");
logger.AssertLogContains("echo 3) [ value end");
logger.AssertLogContains("echo 4) [ value value end");
logger.AssertLogContains("echo 5) value] end");
logger.AssertLogContains("echo 6) [test]] end");
logger.AssertLogContains("echo 7) [value] end");
logger.AssertLogContains("echo 8) [notaproperty] end");
logger.AssertLogContains("echo 9) [[notaproperty] end");
logger.AssertLogContains("echo 10) [ [notaproperty] end");
logger.AssertLogContains("echo 11) [ [nap] [nap] end");
logger.AssertLogContains("echo 12) [notaproperty]] end");
logger.AssertLogContains("echo 13) [notaproperty]] end");
logger.AssertLogContains("echo 14) [[notaproperty]] end");
}
}
}
| |
// 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.Runtime.CompilerServices;
using Xunit;
public static unsafe class MulticastDelegateTests
{
[Fact]
public static void TestGetInvocationList()
{
DFoo dfoo = new C().Foo;
Delegate[] delegates = dfoo.GetInvocationList();
Assert.NotNull(delegates);
Assert.Equal(delegates.Length, 1);
Assert.True(dfoo.Equals(delegates[0]));
}
[Fact]
public static void TestEquals()
{
C c = new C();
DFoo d1 = c.Foo;
DFoo d2 = c.Foo;
Assert.False(RuntimeHelpers.ReferenceEquals(d1, d2));
bool b;
b = d1.Equals(d2);
Assert.True(b);
Assert.True(d1 == d2);
Assert.False(d1 != d2);
d1 = c.Foo;
d2 = c.Goo;
b = d1.Equals(d2);
Assert.False(b);
Assert.False(d1 == d2);
Assert.True(d1 != d2);
d1 = new C().Foo;
d2 = new C().Foo;
b = d1.Equals(d2);
Assert.False(b);
Assert.False(d1 == d2);
Assert.True(d1 != d2);
DGoo dgoo = c.Foo;
d1 = c.Foo;
b = d1.Equals(dgoo);
Assert.False(b);
int h = d1.GetHashCode();
int h2 = d1.GetHashCode();
Assert.Equal(h, h2);
}
[Fact]
public static void TestCombineReturn()
{
Tracker t = new Tracker();
DRet dret1 = new DRet(t.ARet);
DRet dret2 = new DRet(t.BRet);
DRet dret12 = (DRet)Delegate.Combine(dret1, dret2);
string s = dret12(4);
Assert.Equal(s, "BRet4");
Assert.Equal(t.S, "ARet4BRet4");
return;
}
[Fact]
public static void TestCombine()
{
Tracker t1 = new Tracker();
D a = new D(t1.A);
D b = new D(t1.B);
D c = new D(t1.C);
D d = new D(t1.D);
D nothing = (D)(Delegate.Combine());
Assert.Null(nothing);
D one = (D)(Delegate.Combine(a));
t1.Clear();
one(5);
Assert.Equal(t1.S, "A5");
CheckInvokeList(new D[] { a }, one, t1);
D ab = (D)(Delegate.Combine(a, b));
t1.Clear();
ab(5);
Assert.Equal(t1.S, "A5B5");
CheckInvokeList(new D[] { a, b }, ab, t1);
D abc = (D)(Delegate.Combine(a, b, c));
t1.Clear();
abc(5);
Assert.Equal(t1.S, "A5B5C5");
CheckInvokeList(new D[] { a, b, c }, abc, t1);
D abcdabc = (D)(Delegate.Combine(abc, d, abc));
t1.Clear();
abcdabc(9);
Assert.Equal(t1.S, "A9B9C9D9A9B9C9");
CheckInvokeList(new D[] { a, b, c, d, a, b, c }, abcdabc, t1);
return;
}
[Fact]
public static void TestRemove()
{
Tracker t1 = new Tracker();
D a = new D(t1.A);
D b = new D(t1.B);
D c = new D(t1.C);
D d = new D(t1.D);
D e = new D(t1.E);
D abc = (D)(Delegate.Combine(a, b, c));
D abcdabc = (D)(Delegate.Combine(abc, d, abc));
D ab = (D)(Delegate.Combine(a, b));
D dab = (D)(Delegate.Combine(d, ab));
D abcc = (D)(Delegate.Remove(abcdabc, dab));
t1.Clear();
abcc(9);
string s = t1.S;
Assert.Equal(s, "A9B9C9C9");
CheckInvokeList(new D[] { a, b, c, c }, abcc, t1);
// Pattern-match is based on structural equivalence, not reference equality.
D acopy = new D(t1.A);
D bbba = (D)(Delegate.Combine(b, b, b, acopy));
D bbb = (D)(Delegate.Remove(bbba, a));
t1.Clear();
bbb(9);
Assert.Equal(t1.S, "B9B9B9");
CheckInvokeList(new D[] { b, b, b }, bbb, t1);
// In the case of multiple occurrences, Remove() must remove the last one.
D abcd = (D)(Delegate.Remove(abcdabc, abc));
t1.Clear();
abcd(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd, t1);
D d1 = (D)(Delegate.RemoveAll(abcdabc, abc));
t1.Clear();
d1(9);
s = t1.S;
Assert.Equal(t1.S, "D9");
CheckInvokeList(new D[] { d }, d1, t1);
D nothing = (D)(Delegate.Remove(d1, d1));
Assert.Null(nothing);
// The pattern-not-found case.
D abcd1 = (D)(Delegate.Remove(abcd, null));
t1.Clear();
abcd1(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd1, t1);
// The pattern-not-found case.
D abcd2 = (D)(Delegate.Remove(abcd, e));
t1.Clear();
abcd2(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd2, t1);
// The pattern-not-found case.
D abcd3 = (D)(Delegate.RemoveAll(abcd, null));
t1.Clear();
abcd3(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd3, t1);
// The pattern-not-found case.
D abcd4 = (D)(Delegate.RemoveAll(abcd, e));
t1.Clear();
abcd4(9);
Assert.Equal(t1.S, "A9B9C9D9");
CheckInvokeList(new D[] { a, b, c, d }, abcd4, t1);
return;
}
private static void CheckInvokeList(D[] expected, D combo, Tracker target)
{
Delegate[] invokeList = combo.GetInvocationList();
Assert.Equal(invokeList.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
CheckIsSingletonDelegate((D)(expected[i]), (D)(invokeList[i]), target);
}
Assert.True(Object.ReferenceEquals(combo.Target, expected[expected.Length - 1].Target));
Assert.True(Object.ReferenceEquals(combo.Target, target));
}
private static void CheckIsSingletonDelegate(D expected, D actual, Tracker target)
{
Assert.True(expected.Equals(actual));
Delegate[] invokeList = actual.GetInvocationList();
Assert.Equal(invokeList.Length, 1);
bool b = actual.Equals(invokeList[0]);
Assert.True(b);
target.Clear();
expected(9);
string sExpected = target.S;
target.Clear();
actual(9);
string sActual = target.S;
Assert.Equal(sExpected, sActual);
Assert.True(Object.ReferenceEquals(target, actual.Target));
}
private class Tracker
{
public Tracker()
{
S = "";
}
public string S;
public void Clear()
{
S = "";
}
public void A(int x)
{
S = S + "A" + x;
}
public string ARet(int x)
{
S = S + "ARet" + x;
return "ARet" + x;
}
public void B(int x)
{
S = S + "B" + x;
}
public string BRet(int x)
{
S = S + "BRet" + x;
return "BRet" + x;
}
public void C(int x)
{
S = S + "C" + x;
}
public void D(int x)
{
S = S + "D" + x;
}
public void E(int x)
{
S = S + "E" + x;
}
public void F(int x)
{
S = S + "F" + x;
}
}
private delegate void D(int x);
private delegate string DRet(int x);
private delegate string DFoo(int x);
private delegate string DGoo(int x);
private class C
{
public string Foo(int x)
{
return new string('A', x);
}
public string Goo(int x)
{
return new string('A', x);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Dynamic;
using L4p.Common.DumpToLogs;
using L4p.Common.Helpers;
using L4p.Common.Json;
namespace L4p.Common.MsgIsApplications
{
public interface IMsgContext : IHaveDump
{
T Add<T>(T value) where T : class, new();
T Get<T>() where T : class, new();
T Remove<T>() where T : class, new();
T Replace<T>(T value) where T : class, new();
IMsgContext Impl { get; }
IMsgContext Lock { set; }
void SetMsgIsTheApp(MsgIsTheAppEx msgIsTheApp); // friend access only
}
public class MsgContext : IMsgContext
{
#region counters
class Counters
{
public int ValuesAdded;
public int ValuesRemoved;
public int VauesReplaced;
public int ValuesRetrieved;
public int ValueIsNotHere;
public int MsgIsTheAppChanged;
public int SameValueIsAdded;
}
#endregion
#region members
private readonly Counters _counters;
private readonly Dictionary<Type, MsgValueBox> _values;
private IMsgContext _lock;
private IMsgIsTheApp _msgIsTheApp;
#endregion
#region construction
public static IMsgContext New()
{
return
new MsgContext();
}
public static IMsgContext NewSync()
{
var context =
SyncMsgContext.New(
new MsgContext());
context.Lock = context;
return context;
}
private MsgContext()
{
_counters = new Counters();
_values = new Dictionary<Type, MsgValueBox>();
_msgIsTheApp = Null.MsgIsTheApp;
}
#endregion
#region private
private object get_value(Type type)
{
MsgValueBox box;
_values.TryGetValue(type, out box);
if (box == null)
return null;
return box.Value;
}
private void set_value(Type key, object value)
{
var box = new MsgValueBox {
Type = key,
Value = value
};
_values.Add(key, box);
}
#endregion
#region interface
ExpandoObject IHaveDump.Dump(dynamic root)
{
if (root == null)
root = new ExpandoObject();
root.Counters = _counters;
root.Values = _values.Count;
return root;
}
T IMsgContext.Add<T>(T value)
{
Validate.NotNull(value);
var type = value.GetType();
var prev = get_value(type);
if (ReferenceEquals(prev, value))
{
_counters.SameValueIsAdded++;
return value;
}
if (prev != null)
throw new MsgIsTheAppException("Value for type '{0}' is already set; {1}", type.Name, prev.ToJson());
_msgIsTheApp.SetContextFor(this, _lock, value);
set_value(type, value);
_counters.ValuesAdded++;
return value;
}
T IMsgContext.Get<T>()
{
var type = typeof(T);
var value = get_value(type);
if (value != null)
_counters.ValuesRetrieved++;
else
_counters.ValueIsNotHere++;
return (T) value;
}
T IMsgContext.Remove<T>()
{
var type = typeof(T);
var value = get_value(type);
if (_values.Remove(type))
_counters.ValuesRemoved++;
return (T) value;
}
T IMsgContext.Replace<T>(T value)
{
Validate.NotNull(value);
var type = value.GetType();
var prev = get_value(type);
if (ReferenceEquals(value, prev))
return value;
set_value(type, value);
_counters.VauesReplaced++;
return value;
}
IMsgContext IMsgContext.Impl
{
get { return this; }
}
IMsgContext IMsgContext.Lock
{
set { _lock = value; }
}
void IMsgContext.SetMsgIsTheApp(MsgIsTheAppEx msgIsTheApp)
{
Validate.NotNull(msgIsTheApp);
if (ReferenceEquals(msgIsTheApp, _msgIsTheApp))
return;
_counters.MsgIsTheAppChanged++;
_msgIsTheApp = msgIsTheApp;
}
#endregion
}
class SyncMsgContext : IMsgContext
{
private readonly object _mutex = new object();
private readonly IMsgContext _impl;
public static IMsgContext New(IMsgContext impl) { return new SyncMsgContext(impl); }
private SyncMsgContext(IMsgContext impl) { _impl = impl; }
ExpandoObject IHaveDump.Dump(dynamic root) { return _impl.Dump(root); }
IMsgContext IMsgContext.Impl {get { return _impl.Impl; }}
IMsgContext IMsgContext.Lock { set { _impl.Lock = value; } }
T IMsgContext.Add<T>(T value) { lock(_mutex) return _impl.Add(value); }
T IMsgContext.Get<T>() { lock(_mutex) return _impl.Get<T>(); }
T IMsgContext.Remove<T>() { lock (_mutex) return _impl.Remove<T>(); }
T IMsgContext.Replace<T>(T value) { lock(_mutex) return _impl.Replace(value); }
void IMsgContext.SetMsgIsTheApp(MsgIsTheAppEx msgIsTheApp) { _impl.SetMsgIsTheApp(msgIsTheApp); }
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Unmanaged
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Apache.Ignite.Core.Common;
using JNI = IgniteJniNativeMethods;
/// <summary>
/// Unmanaged utility classes.
/// </summary>
internal static unsafe class UnmanagedUtils
{
/** Interop factory ID for .Net. */
private const int InteropFactoryId = 1;
/// <summary>
/// Initializer.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
static UnmanagedUtils()
{
var platform = Environment.Is64BitProcess ? "x64" : "x86";
var resName = string.Format("{0}.{1}", platform, IgniteUtils.FileIgniteJniDll);
var path = IgniteUtils.UnpackEmbeddedResource(resName, IgniteUtils.FileIgniteJniDll);
var ptr = NativeMethods.LoadLibrary(path);
if (ptr == IntPtr.Zero)
throw new IgniteException(string.Format("Failed to load {0}: {1}",
IgniteUtils.FileIgniteJniDll, Marshal.GetLastWin32Error()));
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
JNI.SetConsoleHandler(UnmanagedCallbacks.ConsoleWriteHandler);
}
/// <summary>
/// Handles the DomainUnload event of the current AppDomain.
/// </summary>
private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
// Clean the handler to avoid JVM crash.
var removedCnt = JNI.RemoveConsoleHandler(UnmanagedCallbacks.ConsoleWriteHandler);
Debug.Assert(removedCnt == 1);
}
/// <summary>
/// No-op initializer used to force type loading and static constructor call.
/// </summary>
internal static void Initialize()
{
// No-op.
}
#region NATIVE METHODS: PROCESSOR
internal static void IgnitionStart(UnmanagedContext ctx, string cfgPath, string gridName,
bool clientMode, bool userLogger)
{
using (var mem = IgniteManager.Memory.Allocate().GetStream())
{
mem.WriteBool(clientMode);
mem.WriteBool(userLogger);
sbyte* cfgPath0 = IgniteUtils.StringToUtf8Unmanaged(cfgPath);
sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName);
try
{
// OnStart receives the same InteropProcessor as here (just as another GlobalRef) and stores it.
// Release current reference immediately.
void* res = JNI.IgnitionStart(ctx.NativeContext, cfgPath0, gridName0, InteropFactoryId,
mem.SynchronizeOutput());
JNI.Release(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(cfgPath0));
Marshal.FreeHGlobal(new IntPtr(gridName0));
}
}
}
internal static bool IgnitionStop(void* ctx, string gridName, bool cancel)
{
sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName);
try
{
return JNI.IgnitionStop(ctx, gridName0, cancel);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(gridName0));
}
}
internal static void IgnitionStopAll(void* ctx, bool cancel)
{
JNI.IgnitionStopAll(ctx, cancel);
}
internal static void ProcessorReleaseStart(IUnmanagedTarget target)
{
JNI.ProcessorReleaseStart(target.Context, target.Target);
}
internal static IUnmanagedTarget ProcessorProjection(IUnmanagedTarget target)
{
void* res = JNI.ProcessorProjection(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorCreateCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, long memPtr)
{
void* res = JNI.ProcessorCreateCacheFromConfig(target.Context, target.Target, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorGetOrCreateCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, long memPtr)
{
void* res = JNI.ProcessorGetOrCreateCacheFromConfig(target.Context, target.Target, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorCreateNearCache(IUnmanagedTarget target, string name, long memPtr)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorCreateNearCache(target.Context, target.Target, name0, memPtr);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorGetOrCreateNearCache(IUnmanagedTarget target, string name, long memPtr)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorGetOrCreateNearCache(target.Context, target.Target, name0, memPtr);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static void ProcessorDestroyCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
JNI.ProcessorDestroyCache(target.Context, target.Target, name0);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAffinity(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorAffinity(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorDataStreamer(IUnmanagedTarget target, string name, bool keepBinary)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorDataStreamer(target.Context, target.Target, name0, keepBinary);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorTransactions(IUnmanagedTarget target)
{
void* res = JNI.ProcessorTransactions(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorCompute(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorCompute(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorMessage(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorMessage(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorEvents(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorEvents(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorServices(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorServices(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorExtensions(IUnmanagedTarget target)
{
void* res = JNI.ProcessorExtensions(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorAtomicLong(IUnmanagedTarget target, string name, long initialValue,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicLong(target.Context, target.Target, name0, initialValue, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAtomicSequence(IUnmanagedTarget target, string name, long initialValue,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicSequence(target.Context, target.Target, name0, initialValue, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAtomicReference(IUnmanagedTarget target, string name, long memPtr,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicReference(target.Context, target.Target, name0, memPtr, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static void ProcessorGetIgniteConfiguration(IUnmanagedTarget target, long memPtr)
{
JNI.ProcessorGetIgniteConfiguration(target.Context, target.Target, memPtr);
}
internal static void ProcessorGetCacheNames(IUnmanagedTarget target, long memPtr)
{
JNI.ProcessorGetCacheNames(target.Context, target.Target, memPtr);
}
internal static bool ProcessorLoggerIsLevelEnabled(IUnmanagedTarget target, int level)
{
return JNI.ProcessorLoggerIsLevelEnabled(target.Context, target.Target, level);
}
internal static void ProcessorLoggerLog(IUnmanagedTarget target, int level, string message, string category,
string errorInfo)
{
var message0 = IgniteUtils.StringToUtf8Unmanaged(message);
var category0 = IgniteUtils.StringToUtf8Unmanaged(category);
var errorInfo0 = IgniteUtils.StringToUtf8Unmanaged(errorInfo);
try
{
JNI.ProcessorLoggerLog(target.Context, target.Target, level, message0, category0, errorInfo0);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(message0));
Marshal.FreeHGlobal(new IntPtr(category0));
Marshal.FreeHGlobal(new IntPtr(errorInfo0));
}
}
internal static IUnmanagedTarget ProcessorBinaryProcessor(IUnmanagedTarget target)
{
void* res = JNI.ProcessorBinaryProcessor(target.Context, target.Target);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: TARGET
internal static long TargetInLongOutLong(IUnmanagedTarget target, int opType, long memPtr)
{
return JNI.TargetInLongOutLong(target.Context, target.Target, opType, memPtr);
}
internal static long TargetInStreamOutLong(IUnmanagedTarget target, int opType, long memPtr)
{
return JNI.TargetInStreamOutLong(target.Context, target.Target, opType, memPtr);
}
internal static void TargetInStreamOutStream(IUnmanagedTarget target, int opType, long inMemPtr, long outMemPtr)
{
JNI.TargetInStreamOutStream(target.Context, target.Target, opType, inMemPtr, outMemPtr);
}
internal static IUnmanagedTarget TargetInStreamOutObject(IUnmanagedTarget target, int opType, long inMemPtr)
{
void* res = JNI.TargetInStreamOutObject(target.Context, target.Target, opType, inMemPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget TargetInObjectStreamOutObjectStream(IUnmanagedTarget target, int opType, void* arg, long inMemPtr, long outMemPtr)
{
void* res = JNI.TargetInObjectStreamOutObjectStream(target.Context, target.Target, opType, arg, inMemPtr, outMemPtr);
if (res == null)
return null;
return target.ChangeTarget(res);
}
internal static void TargetOutStream(IUnmanagedTarget target, int opType, long memPtr)
{
JNI.TargetOutStream(target.Context, target.Target, opType, memPtr);
}
internal static IUnmanagedTarget TargetOutObject(IUnmanagedTarget target, int opType)
{
void* res = JNI.TargetOutObject(target.Context, target.Target, opType);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: MISCELANNEOUS
internal static void Reallocate(long memPtr, int cap)
{
int res = JNI.Reallocate(memPtr, cap);
if (res != 0)
throw new IgniteException("Failed to reallocate external memory [ptr=" + memPtr +
", capacity=" + cap + ']');
}
internal static IUnmanagedTarget Acquire(UnmanagedContext ctx, void* target)
{
void* target0 = JNI.Acquire(ctx.NativeContext, target);
return new UnmanagedTarget(ctx, target0);
}
internal static void Release(IUnmanagedTarget target)
{
JNI.Release(target.Target);
}
internal static void ThrowToJava(void* ctx, Exception e)
{
char* msgChars = (char*)IgniteUtils.StringToUtf8Unmanaged(e.Message);
try
{
JNI.ThrowToJava(ctx, msgChars);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(msgChars));
}
}
internal static int HandlersSize()
{
return JNI.HandlersSize();
}
internal static void* CreateContext(void* opts, int optsLen, void* cbs)
{
return JNI.CreateContext(opts, optsLen, cbs);
}
internal static void DeleteContext(void* ctx)
{
JNI.DeleteContext(ctx);
}
internal static void DestroyJvm(void* ctx)
{
JNI.DestroyJvm(ctx);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace OpenMetaverse.TestClient
{
public class LoginDetails
{
public string FirstName;
public string LastName;
public string Password;
public string StartLocation;
public bool GroupCommands;
public string MasterName;
public UUID MasterKey;
public string URI;
}
public class StartPosition
{
public string sim;
public int x;
public int y;
public int z;
public StartPosition()
{
this.sim = null;
this.x = 0;
this.y = 0;
this.z = 0;
}
}
public sealed class ClientManager
{
const string VERSION = "1.0.0";
class Singleton { internal static readonly ClientManager Instance = new ClientManager(); }
public static ClientManager Instance { get { return Singleton.Instance; } }
public Dictionary<UUID, TestClient> Clients = new Dictionary<UUID, TestClient>();
public Dictionary<Simulator, Dictionary<uint, Primitive>> SimPrims = new Dictionary<Simulator, Dictionary<uint, Primitive>>();
public bool Running = true;
public bool GetTextures = false;
public volatile int PendingLogins = 0;
public string onlyAvatar = String.Empty;
ClientManager()
{
}
public void Start(List<LoginDetails> accounts, bool getTextures)
{
GetTextures = getTextures;
foreach (LoginDetails account in accounts)
Login(account);
}
public TestClient Login(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Usage: login firstname lastname password [simname] [login server url]");
return null;
}
LoginDetails account = new LoginDetails();
account.FirstName = args[0];
account.LastName = args[1];
account.Password = args[2];
if (args.Length > 3)
{
// If it looks like a full starting position was specified, parse it
if (args[3].StartsWith("http"))
{
account.URI = args[3];
}
else
{
if (args[3].IndexOf('/') >= 0)
{
char sep = '/';
string[] startbits = args[3].Split(sep);
try
{
account.StartLocation = NetworkManager.StartLocation(startbits[0], Int32.Parse(startbits[1]),
Int32.Parse(startbits[2]), Int32.Parse(startbits[3]));
}
catch (FormatException) { }
}
// Otherwise, use the center of the named region
if (account.StartLocation == null)
account.StartLocation = NetworkManager.StartLocation(args[3], 128, 128, 40);
}
}
if (args.Length > 4)
if (args[4].StartsWith("http"))
account.URI = args[4];
if (string.IsNullOrEmpty(account.URI))
account.URI = Program.LoginURI;
Logger.Log("Using login URI " + account.URI, Helpers.LogLevel.Info);
return Login(account);
}
public TestClient Login(LoginDetails account)
{
// Check if this client is already logged in
foreach (TestClient c in Clients.Values)
{
if (c.Self.FirstName == account.FirstName && c.Self.LastName == account.LastName)
{
Logout(c);
break;
}
}
++PendingLogins;
TestClient client = new TestClient(this);
client.Network.LoginProgress +=
delegate(object sender, LoginProgressEventArgs e)
{
Logger.Log(String.Format("Login {0}: {1}", e.Status, e.Message), Helpers.LogLevel.Info, client);
if (e.Status == LoginStatus.Success)
{
Clients[client.Self.AgentID] = client;
if (client.MasterKey == UUID.Zero)
{
UUID query = UUID.Zero;
EventHandler<DirPeopleReplyEventArgs> peopleDirCallback =
delegate(object sender2, DirPeopleReplyEventArgs dpe)
{
if (dpe.QueryID == query)
{
if (dpe.MatchedPeople.Count != 1)
{
Logger.Log("Unable to resolve master key from " + client.MasterName, Helpers.LogLevel.Warning);
}
else
{
client.MasterKey = dpe.MatchedPeople[0].AgentID;
Logger.Log("Master key resolved to " + client.MasterKey, Helpers.LogLevel.Info);
}
}
};
client.Directory.DirPeopleReply += peopleDirCallback;
query = client.Directory.StartPeopleSearch(client.MasterName, 0);
}
Logger.Log("Logged in " + client.ToString(), Helpers.LogLevel.Info);
--PendingLogins;
}
else if (e.Status == LoginStatus.Failed)
{
Logger.Log("Failed to login " + account.FirstName + " " + account.LastName + ": " +
client.Network.LoginMessage, Helpers.LogLevel.Warning);
--PendingLogins;
}
};
// Optimize the throttle
client.Throttle.Wind = 0;
client.Throttle.Cloud = 0;
client.Throttle.Land = 1000000;
client.Throttle.Task = 1000000;
client.GroupCommands = account.GroupCommands;
client.MasterName = account.MasterName;
client.MasterKey = account.MasterKey;
client.AllowObjectMaster = client.MasterKey != UUID.Zero; // Require UUID for object master.
LoginParams loginParams = client.Network.DefaultLoginParams(
account.FirstName, account.LastName, account.Password, "TestClient", VERSION);
if (!String.IsNullOrEmpty(account.StartLocation))
loginParams.Start = account.StartLocation;
if (!String.IsNullOrEmpty(account.URI))
loginParams.URI = account.URI;
client.Network.BeginLogin(loginParams);
return client;
}
/// <summary>
///
/// </summary>
public void Run()
{
Console.WriteLine("Type quit to exit. Type help for a command list.");
while (Running)
{
PrintPrompt();
string input = Console.ReadLine();
DoCommandAll(input, UUID.Zero);
}
foreach (GridClient client in Clients.Values)
{
if (client.Network.Connected)
client.Network.Logout();
}
}
private void PrintPrompt()
{
int online = 0;
foreach (GridClient client in Clients.Values)
{
if (client.Network.Connected) online++;
}
Console.Write(online + " avatars online> ");
}
/// <summary>
///
/// </summary>
/// <param name="cmd"></param>
/// <param name="fromAgentID"></param>
/// <param name="imSessionID"></param>
public void DoCommandAll(string cmd, UUID fromAgentID)
{
string[] tokens = cmd.Trim().Split(new char[] { ' ', '\t' });
if (tokens.Length == 0)
return;
string firstToken = tokens[0].ToLower();
if (String.IsNullOrEmpty(firstToken))
return;
// Allow for comments when cmdline begins with ';' or '#'
if (firstToken[0] == ';' || firstToken[0] == '#')
return;
if ('@' == firstToken[0]) {
onlyAvatar = String.Empty;
if (tokens.Length == 3) {
bool found = false;
onlyAvatar = tokens[1]+" "+tokens[2];
foreach (TestClient client in Clients.Values) {
if ((client.ToString() == onlyAvatar) && (client.Network.Connected)) {
found = true;
break;
}
}
if (found) {
Logger.Log("Commanding only "+onlyAvatar+" now", Helpers.LogLevel.Info);
} else {
Logger.Log("Commanding nobody now. Avatar "+onlyAvatar+" is offline", Helpers.LogLevel.Info);
}
} else {
Logger.Log("Commanding all avatars now", Helpers.LogLevel.Info);
}
return;
}
string[] args = new string[tokens.Length - 1];
if (args.Length > 0)
Array.Copy(tokens, 1, args, 0, args.Length);
if (firstToken == "login")
{
Login(args);
}
else if (firstToken == "quit")
{
Quit();
Logger.Log("All clients logged out and program finished running.", Helpers.LogLevel.Info);
}
else if (firstToken == "help")
{
if (Clients.Count > 0)
{
foreach (TestClient client in Clients.Values)
{
Console.WriteLine(client.Commands["help"].Execute(args, UUID.Zero));
break;
}
}
else
{
Console.WriteLine("You must login at least one bot to use the help command");
}
}
else if (firstToken == "script")
{
// No reason to pass this to all bots, and we also want to allow it when there are no bots
ScriptCommand command = new ScriptCommand(null);
Logger.Log(command.Execute(args, UUID.Zero), Helpers.LogLevel.Info);
}
else if (firstToken == "waitforlogin")
{
// Special exception to allow this to run before any bots have logged in
if (ClientManager.Instance.PendingLogins > 0)
{
WaitForLoginCommand command = new WaitForLoginCommand(null);
Logger.Log(command.Execute(args, UUID.Zero), Helpers.LogLevel.Info);
}
else
{
Logger.Log("No pending logins", Helpers.LogLevel.Info);
}
}
else
{
// Make an immutable copy of the Clients dictionary to safely iterate over
Dictionary<UUID, TestClient> clientsCopy = new Dictionary<UUID, TestClient>(Clients);
int completed = 0;
foreach (TestClient client in clientsCopy.Values)
{
ThreadPool.QueueUserWorkItem((WaitCallback)
delegate(object state)
{
TestClient testClient = (TestClient)state;
if ((String.Empty == onlyAvatar) || (testClient.ToString() == onlyAvatar)) {
if (testClient.Commands.ContainsKey(firstToken))
Logger.Log(testClient.Commands[firstToken].Execute(args, fromAgentID),
Helpers.LogLevel.Info, testClient);
else
Logger.Log("Unknown command " + firstToken, Helpers.LogLevel.Warning);
}
++completed;
},
client);
}
while (completed < clientsCopy.Count)
Thread.Sleep(50);
}
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public void Logout(TestClient client)
{
Clients.Remove(client.Self.AgentID);
client.Network.Logout();
}
/// <summary>
///
/// </summary>
public void Quit()
{
Running = false;
// TODO: It would be really nice if we could figure out a way to abort the ReadLine here in so that Run() will exit.
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ShareDB.RichText
{
internal static class DiffList
{
/// <summary>
/// Compute and return the source text (all equalities and deletions).
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static string Text1(this List<Diff> diffs)
{
var text = new StringBuilder();
foreach (var aDiff in diffs)
{
if (aDiff.Operation != Operation.Insert)
{
text.Append(aDiff.Text);
}
}
return text.ToString();
}
/// <summary>
/// Compute and return the destination text (all equalities and insertions).
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static string Text2(this List<Diff> diffs)
{
var text = new StringBuilder();
foreach (var aDiff in diffs)
{
if (aDiff.Operation != Operation.Delete)
{
text.Append(aDiff.Text);
}
}
return text.ToString();
}
/// <summary>
/// Compute the Levenshtein distance; the number of inserted, deleted or substituted characters.
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static int Levenshtein(this IEnumerable<Diff> diffs)
{
var levenshtein = 0;
var insertions = 0;
var deletions = 0;
foreach (var aDiff in diffs)
{
switch (aDiff.Operation)
{
case Operation.Insert:
insertions += aDiff.Text.Length;
break;
case Operation.Delete:
deletions += aDiff.Text.Length;
break;
case Operation.Equal:
// A deletion and an insertion is one substitution.
levenshtein += Math.Max(insertions, deletions);
insertions = 0;
deletions = 0;
break;
}
}
levenshtein += Math.Max(insertions, deletions);
return levenshtein;
}
private static StringBuilder AppendHtml(this StringBuilder sb, string tag, string backgroundColor, string content)
{
var openingTag = string.IsNullOrEmpty(backgroundColor) ? $"<{tag}>" : $"<{tag} style=\"background:{backgroundColor};\">";
return sb
.Append(openingTag)
.Append(content)
.Append($"</{tag}>");
}
/// <summary>
/// Convert a Diff list into a pretty HTML report.
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static string PrettyHtml(this IEnumerable<Diff> diffs)
{
var html = new StringBuilder();
foreach (var aDiff in diffs)
{
var text = new StringBuilder(aDiff.Text)
.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">")
.Replace("\n", "¶<br>")
.ToString();
switch (aDiff.Operation)
{
case Operation.Insert:
html.AppendHtml("ins", "#e6ffe6", text);
break;
case Operation.Delete:
html.AppendHtml("del", "#ffe6e6", text);
break;
case Operation.Equal:
html.AppendHtml("span", "", text);
break;
}
}
return html.ToString();
}
static char ToDelta(this Operation o)
{
switch (o)
{
case Operation.Delete: return '-';
case Operation.Insert: return '+';
case Operation.Equal: return '=';
default: throw new ArgumentException($"Unknown Operation: {o}");
}
}
static Operation FromDelta(char c)
{
switch (c)
{
case '-': return Operation.Delete;
case '+': return Operation.Insert;
case '=': return Operation.Equal;
default: throw new ArgumentException($"Invalid Delta Token: {c}");
}
}
/// <summary>
/// Crush the diff into an encoded string which describes the operations
/// required to transform text1 into text2.
/// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
/// Operations are tab-separated. Inserted text is escaped using %xx
/// notation.
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static string ToDelta(this List<Diff> diffs)
{
var s =
from aDiff in diffs
let sign = aDiff.Operation.ToDelta()
let textToAppend = aDiff.Operation == Operation.Insert
? aDiff.Text.UrlEncoded().Replace('+', ' ')
: aDiff.Text.Length.ToString()
select string.Concat(sign, textToAppend);
var delta = string.Join("\t", s).UnescapeForEncodeUriCompatability();
return delta;
}
/// <summary>
/// Given the original text1, and an encoded string which describes the
/// operations required to transform text1 into text2, compute the full diff.
/// </summary>
/// <param name="text1">Source string for the diff.</param>
/// <param name="delta">Delta text.</param>
/// <returns></returns>
public static IEnumerable<Diff> FromDelta(string text1, string delta)
{
var pointer = 0; // Cursor in text1
var tokens = delta.Split(new[] { "\t" }, StringSplitOptions.None);
foreach (var token in tokens)
{
if (token.Length == 0)
{
// Blank tokens are ok (from a trailing \t).
continue;
}
// Each token begins with a one character parameter which specifies the
// operation of this token (delete, insert, equality).
var param = token.Substring(1);
var operation = FromDelta(token[0]);
string text;
switch (operation)
{
case Operation.Insert:
// decode would change all "+" to " "
text = param.Replace("+", "%2b").UrlDecoded();
break;
case Operation.Delete:
case Operation.Equal:
if (!int.TryParse(param, out int n))
{
throw new ArgumentException($"Invalid number in Diff.FromDelta: {param}");
}
if (pointer < 0 || n < 0 || pointer > text1.Length - n)
{
throw new ArgumentException($"Delta length ({pointer}) larger than source text length ({text1.Length}).");
}
text = text1.Substring(pointer, n);
pointer += n;
break;
default: throw new ArgumentException($"Unknown Operation: {operation}");
}
yield return Diff.Create(operation, text);
}
if (pointer != text1.Length)
{
throw new ArgumentException($"Delta length ({pointer}) smaller than source text length ({text1.Length}).");
}
}
/// <summary>
/// Reorder and merge like edit sections. Merge equalities.
/// Any edit section can move as long as it doesn't cross an equality.
/// </summary>
/// <param name="diffs">list of Diffs</param>
public static void CleanupMerge(this List<Diff> diffs)
{
// Add a dummy entry at the end.
diffs.Add(Diff.Equal(string.Empty));
var countDelete = 0;
var countInsert = 0;
var sbDelete = new StringBuilder();
var sbInsert = new StringBuilder();
var pointer = 0;
while (pointer < diffs.Count)
{
switch (diffs[pointer].Operation)
{
case Operation.Insert:
countInsert++;
sbInsert.Append(diffs[pointer].Text);
pointer++;
break;
case Operation.Delete:
countDelete++;
sbDelete.Append(diffs[pointer].Text);
pointer++;
break;
case Operation.Equal:
// Upon reaching an equality, check for prior redundancies.
if (countDelete + countInsert > 1)
{
if (countDelete != 0 && countInsert != 0)
{
// Factor out any common prefixies.
var commonlength = TextUtil.CommonPrefix(sbInsert, sbDelete);
if (commonlength != 0)
{
var commonprefix = sbInsert.ToString(0, commonlength);
sbInsert.Remove(0, commonlength);
sbDelete.Remove(0, commonlength);
var index = pointer - countDelete - countInsert - 1;
if (index >= 0 && diffs[index].Operation == Operation.Equal)
{
diffs[index] = diffs[index].Replace(diffs[index].Text + commonprefix);
}
else
{
diffs.Insert(0, Diff.Equal(commonprefix));
pointer++;
}
}
// Factor out any common suffixies.
commonlength = TextUtil.CommonSuffix(sbInsert, sbDelete);
if (commonlength != 0)
{
var commonsuffix = sbInsert.ToString(sbInsert.Length - commonlength, commonlength);
sbInsert.Remove(sbInsert.Length - commonlength, commonlength);
sbDelete.Remove(sbDelete.Length - commonlength, commonlength);
diffs[pointer] = diffs[pointer].Replace(commonsuffix + diffs[pointer].Text);
}
}
// Delete the offending records and add the merged ones.
if (countDelete == 0)
{
diffs.Splice(pointer - countInsert, countDelete + countInsert, Diff.Insert(sbInsert.ToString()));
}
else if (countInsert == 0)
{
diffs.Splice(pointer - countDelete, countDelete + countInsert, Diff.Delete(sbDelete.ToString()));
}
else
{
diffs.Splice(pointer - countDelete - countInsert,
countDelete + countInsert,
Diff.Delete(sbDelete.ToString()),
Diff.Insert(sbInsert.ToString()));
}
pointer = pointer - countDelete - countInsert +
(countDelete != 0 ? 1 : 0) + (countInsert != 0 ? 1 : 0) + 1;
}
else if (pointer != 0
&& diffs[pointer - 1].Operation == Operation.Equal)
{
// Merge this equality with the previous one.
diffs[pointer - 1] = diffs[pointer - 1].Replace(diffs[pointer - 1].Text + diffs[pointer].Text);
diffs.RemoveAt(pointer);
}
else
{
pointer++;
}
countInsert = 0;
countDelete = 0;
sbDelete.Clear();
sbInsert.Clear();
break;
}
}
if (diffs[diffs.Count - 1].Text.Length == 0)
{
diffs.RemoveAt(diffs.Count - 1); // Remove the dummy entry at the end.
}
// Second pass: look for single edits surrounded on both sides by
// equalities which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
var changes = false;
// Intentionally ignore the first and last element (don't need checking).
for (var i = 1; i < diffs.Count - 1; i++)
{
var previous = diffs[i - 1];
var current = diffs[i];
var next = diffs[i + 1];
if (previous.Operation == Operation.Equal && next.Operation == Operation.Equal)
{
// This is a single edit surrounded by equalities.
if (current.Text.EndsWith(previous.Text, StringComparison.Ordinal))
{
// Shift the edit over the previous equality.
var text = previous.Text + current.Text.Substring(0, current.Text.Length - previous.Text.Length);
diffs[i] = current.Replace(text);
diffs[i + 1] = next.Replace(previous.Text + next.Text);
diffs.Splice(i - 1, 1);
changes = true;
}
else if (current.Text.StartsWith(next.Text,StringComparison.Ordinal))
{
// Shift the edit over the next equality.
diffs[i - 1] = previous.Replace(previous.Text + next.Text);
diffs[i] = current.Replace(current.Text.Substring(next.Text.Length) + next.Text);
diffs.Splice(i + 1, 1);
changes = true;
}
}
}
// If shifts were made, the diff needs reordering and another shift sweep.
if (changes)
{
diffs.CleanupMerge();
}
}
/// <summary>
/// Look for single edits surrounded on both sides by equalities
/// which can be shifted sideways to align the edit to a word boundary.
/// e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
/// </summary>
/// <param name="diffs"></param>
public static void CleanupSemanticLossless(this List<Diff> diffs)
{
var pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while (pointer < diffs.Count - 1)
{
if (diffs[pointer - 1].Operation == Operation.Equal &&
diffs[pointer + 1].Operation == Operation.Equal)
{
// This is a single edit surrounded by equalities.
var equality1 = diffs[pointer - 1].Text;
var edit = diffs[pointer].Text;
var equality2 = diffs[pointer + 1].Text;
// First, shift the edit as far left as possible.
var commonOffset = TextUtil.CommonSuffix(equality1, edit);
if (commonOffset > 0)
{
var commonString = edit.Substring(edit.Length - commonOffset);
equality1 = equality1.Substring(0, equality1.Length - commonOffset);
edit = commonString + edit.Substring(0, edit.Length - commonOffset);
equality2 = commonString + equality2;
}
// Second, step character by character right,
// looking for the best fit.
var bestEquality1 = equality1;
var bestEdit = edit;
var bestEquality2 = equality2;
var bestScore = DiffCleanupSemanticScore(equality1, edit) + DiffCleanupSemanticScore(edit, equality2);
while (edit.Length != 0 && equality2.Length != 0 && edit[0] == equality2[0])
{
equality1 += edit[0];
edit = edit.Substring(1) + equality2[0];
equality2 = equality2.Substring(1);
var score = DiffCleanupSemanticScore(equality1, edit) + DiffCleanupSemanticScore(edit, equality2);
// The >= encourages trailing rather than leading whitespace on
// edits.
if (score >= bestScore)
{
bestScore = score;
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
}
}
if (diffs[pointer - 1].Text != bestEquality1)
{
// We have an improvement, save it back to the diff.
var newDiffs = new[]
{
Diff.Equal(bestEquality1),
diffs[pointer].Replace(bestEdit),
Diff.Equal(bestEquality2)
}.Where(d => !string.IsNullOrEmpty(d.Text))
.ToArray();
diffs.Splice(pointer - 1, 3, newDiffs);
pointer = pointer - (3 - newDiffs.Length);
}
}
pointer++;
}
}
/// <summary>
/// Given two strings, compute a score representing whether the internal
/// boundary falls on logical boundaries.
/// Scores range from 6 (best) to 0 (worst).
/// </summary>
/// <param name="one"></param>
/// <param name="two"></param>
/// <returns>score</returns>
private static int DiffCleanupSemanticScore(string one, string two)
{
if (one.Length == 0 || two.Length == 0)
{
// Edges are the best.
return 6;
}
// Each port of this function behaves slightly differently due to
// subtle differences in each language's definition of things like
// 'whitespace'. Since this function's purpose is largely cosmetic,
// the choice has been made to use each language's native features
// rather than force total conformity.
var char1 = one[one.Length - 1];
var char2 = two[0];
var nonAlphaNumeric1 = !Char.IsLetterOrDigit(char1);
var nonAlphaNumeric2 = !Char.IsLetterOrDigit(char2);
var whitespace1 = nonAlphaNumeric1 && Char.IsWhiteSpace(char1);
var whitespace2 = nonAlphaNumeric2 && Char.IsWhiteSpace(char2);
var lineBreak1 = whitespace1 && Char.IsControl(char1);
var lineBreak2 = whitespace2 && Char.IsControl(char2);
var blankLine1 = lineBreak1 && BlankLineEnd.IsMatch(one);
var blankLine2 = lineBreak2 && BlankLineStart.IsMatch(two);
if (blankLine1 || blankLine2)
{
// Five points for blank lines.
return 5;
}
if (lineBreak1 || lineBreak2)
{
// Four points for line breaks.
return 4;
}
if (nonAlphaNumeric1 && !whitespace1 && whitespace2)
{
// Three points for end of sentences.
return 3;
}
if (whitespace1 || whitespace2)
{
// Two points for whitespace.
return 2;
}
if (nonAlphaNumeric1 || nonAlphaNumeric2)
{
// One point for non-alphanumeric.
return 1;
}
return 0;
}
// Define some regex patterns for matching boundaries.
private static readonly Regex BlankLineEnd = new Regex("\\n\\r?\\n\\Z", RegexOptions.Compiled);
private static readonly Regex BlankLineStart = new Regex("\\A\\r?\\n\\r?\\n", RegexOptions.Compiled);
/// <summary>
/// Reduce the number of edits by eliminating operationally trivial equalities.
/// </summary>
/// <param name="diffs"></param>
/// <param name="diffEditCost"></param>
public static void CleanupEfficiency(this List<Diff> diffs, short diffEditCost = 4)
{
var changes = false;
// Stack of indices where equalities are found.
var equalities = new Stack<int>();
// Always equal to equalities[equalitiesLength-1][1]
var lastequality = string.Empty;
var pointer = 0; // Index of current position.
// Is there an insertion operation before the last equality.
var preIns = false;
// Is there a deletion operation before the last equality.
var preDel = false;
// Is there an insertion operation after the last equality.
var postIns = false;
// Is there a deletion operation after the last equality.
var postDel = false;
while (pointer < diffs.Count)
{
if (diffs[pointer].Operation == Operation.Equal)
{ // Equality found.
if (diffs[pointer].Text.Length < diffEditCost
&& (postIns || postDel))
{
// Candidate found.
equalities.Push(pointer);
preIns = postIns;
preDel = postDel;
lastequality = diffs[pointer].Text;
}
else
{
// Not a candidate, and can never become one.
equalities.Clear();
lastequality = string.Empty;
}
postIns = postDel = false;
}
else
{ // An insertion or deletion.
if (diffs[pointer].Operation == Operation.Delete)
{
postDel = true;
}
else
{
postIns = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if ((lastequality.Length != 0)
&& ((preIns && preDel && postIns && postDel)
|| ((lastequality.Length < diffEditCost / 2)
&& (preIns ? 1 : 0) + (preDel ? 1 : 0) + (postIns ? 1 : 0)
+ (postDel ? 1 : 0) == 3)))
{
diffs.Splice(equalities.Peek(), 1, Diff.Delete(lastequality), Diff.Insert(lastequality));
equalities.Pop(); // Throw away the equality we just deleted.
lastequality = string.Empty;
if (preIns && preDel)
{
// No changes made which could affect previous entry, keep going.
postIns = postDel = true;
equalities.Clear();
}
else
{
if (equalities.Count > 0)
{
equalities.Pop();
}
pointer = equalities.Count > 0 ? equalities.Peek() : -1;
postIns = postDel = false;
}
changes = true;
}
}
pointer++;
}
if (changes)
{
diffs.CleanupMerge();
}
}
/// <summary>
/// Reduce the number of edits by eliminating semantically trivial equalities.
/// </summary>
/// <param name="diffs"></param>
public static void CleanupSemantic(this List<Diff> diffs)
{
// Stack of indices where equalities are found.
var equalities = new Stack<int>();
// Always equal to equalities[equalitiesLength-1][1]
string lastequality = null;
var pointer = 0; // Index of current position.
// Number of characters that changed prior to the equality.
var lengthInsertions1 = 0;
var lengthDeletions1 = 0;
// Number of characters that changed after the equality.
var lengthInsertions2 = 0;
var lengthDeletions2 = 0;
while (pointer < diffs.Count)
{
if (diffs[pointer].Operation == Operation.Equal)
{ // Equality found.
equalities.Push(pointer);
lengthInsertions1 = lengthInsertions2;
lengthDeletions1 = lengthDeletions2;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastequality = diffs[pointer].Text;
}
else
{ // an insertion or deletion
if (diffs[pointer].Operation == Operation.Insert)
{
lengthInsertions2 += diffs[pointer].Text.Length;
}
else
{
lengthDeletions2 += diffs[pointer].Text.Length;
}
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if (lastequality != null && (lastequality.Length
<= Math.Max(lengthInsertions1, lengthDeletions1))
&& (lastequality.Length
<= Math.Max(lengthInsertions2, lengthDeletions2)))
{
// Duplicate record.
diffs.Splice(equalities.Peek(), 1, Diff.Delete(lastequality), Diff.Insert(lastequality));
// Throw away the equality we just deleted.
equalities.Pop();
if (equalities.Count > 0)
{
equalities.Pop();
}
pointer = equalities.Count > 0 ? equalities.Peek() : -1;
lengthInsertions1 = 0; // Reset the counters.
lengthDeletions1 = 0;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastequality = null;
}
}
pointer++;
}
diffs.CleanupMerge();
diffs.CleanupSemanticLossless();
// Find any overlaps between deletions and insertions.
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
// -> <del>abc</del>xxx<ins>def</ins>
// e.g: <del>xxxabc</del><ins>defxxx</ins>
// -> <ins>def</ins>xxx<del>abc</del>
// Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 1;
while (pointer < diffs.Count)
{
if (diffs[pointer - 1].Operation == Operation.Delete &&
diffs[pointer].Operation == Operation.Insert)
{
var deletion = diffs[pointer - 1].Text;
var insertion = diffs[pointer].Text;
var overlapLength1 = TextUtil.CommonOverlap(deletion, insertion);
var overlapLength2 = TextUtil.CommonOverlap(insertion, deletion);
if (overlapLength1 >= overlapLength2)
{
if (overlapLength1 >= deletion.Length / 2.0 ||
overlapLength1 >= insertion.Length / 2.0)
{
// Overlap found.
// Insert an equality and trim the surrounding edits.
var newDiffs = new[]
{
Diff.Delete(deletion.Substring(0, deletion.Length - overlapLength1)),
Diff.Equal(insertion.Substring(0, overlapLength1)),
Diff.Insert(insertion.Substring(overlapLength1))
};
diffs.Splice(pointer - 1, 2, newDiffs);
pointer++;
}
}
else
{
if (overlapLength2 >= deletion.Length / 2.0 ||
overlapLength2 >= insertion.Length / 2.0)
{
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
diffs.Splice(pointer - 1, 2,
Diff.Insert(insertion.Substring(0, insertion.Length - overlapLength2)),
Diff.Equal(deletion.Substring(0, overlapLength2)),
Diff.Delete(deletion.Substring(overlapLength2)
));
pointer++;
}
}
pointer++;
}
pointer++;
}
}
/// <summary>
/// Rehydrate the text in a diff from a string of line hashes to real lines of text.
/// </summary>
/// <param name="diffs"></param>
/// <param name="lineArray">list of unique strings</param>
/// <returns></returns>
public static IEnumerable<Diff> CharsToLines(this ICollection<Diff> diffs, IList<string> lineArray)
{
foreach (var diff in diffs)
{
var text = new StringBuilder();
foreach (var c in diff.Text)
{
text.Append(lineArray[c]);
}
yield return diff.Replace(text.ToString());
}
}
/// <summary>
/// Compute and return equivalent location in target text.
/// </summary>
/// <param name="diffs">list of diffs</param>
/// <param name="location1">location in source</param>
/// <returns>location in target</returns>
public static int FindEquivalentLocation2(this List<Diff> diffs, int location1)
{
var chars1 = 0;
var chars2 = 0;
var lastChars1 = 0;
var lastChars2 = 0;
Diff lastDiff = null;
foreach (var aDiff in diffs)
{
if (aDiff.Operation != Operation.Insert)
{
// Equality or deletion.
chars1 += aDiff.Text.Length;
}
if (aDiff.Operation != Operation.Delete)
{
// Equality or insertion.
chars2 += aDiff.Text.Length;
}
if (chars1 > location1)
{
// Overshot the location.
lastDiff = aDiff;
break;
}
lastChars1 = chars1;
lastChars2 = chars2;
}
if (lastDiff != null && lastDiff.Operation == Operation.Delete)
{
// The location was deleted.
return lastChars2;
}
// Add the remaining character length.
return lastChars2 + (location1 - lastChars1);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Derivco.Orniscient.Proxy.Filters;
using Derivco.Orniscient.Proxy.Grains.Filters;
using Derivco.Orniscient.Proxy.Grains.Models;
using Orleans;
using Orleans.Core;
using Orleans.Runtime;
using Orleans.Streams;
namespace Derivco.Orniscient.Proxy.Grains
{
public class DashboardInstanceGrain : Grain, IDashboardInstanceGrain
{
private IOrniscientLinkMap _orniscientLink;
public DashboardInstanceGrain()
{}
internal DashboardInstanceGrain(IGrainIdentity identity, IGrainRuntime runtime,IOrniscientLinkMap orniscientLink) : base(identity, runtime)
{
_orniscientLink = orniscientLink;
}
private IDashboardCollectorGrain _dashboardCollectorGrain;
private AppliedFilter _currentFilter;
private Logger _logger;
private IStreamProvider _streamProvider;
private int SessionId => (int) this.GetPrimaryKeyLong();
private int _summaryViewLimit = 100;
internal List<UpdateModel> CurrentStats = new List<UpdateModel>();
private bool InSummaryMode => CurrentStats != null && CurrentStats.Count > _summaryViewLimit;
private IAsyncStream<DiffModel> _dashboardInstanceStream;
public override async Task OnActivateAsync()
{
if (_orniscientLink==null)
{
_orniscientLink = OrniscientLinkMap.Instance;
}
await base.OnActivateAsync();
_logger = GetLogger("DashboardInstanceGrain");
_dashboardCollectorGrain = GrainFactory.GetGrain<IDashboardCollectorGrain>(Guid.Empty);
_streamProvider = GetStreamProvider(StreamKeys.StreamProvider);
var stream = _streamProvider.GetStream<DiffModel>(Guid.Empty, StreamKeys.OrniscientChanges);
await stream.SubscribeAsync(OnNextAsync);
_dashboardInstanceStream = _streamProvider.GetStream<DiffModel>(Guid.Empty, StreamKeys.OrniscientClient);
_logger.Info("DashboardInstanceGrain Activated.");
}
public async Task<DiffModel> GetAll(AppliedFilter filter = null)
{
_logger.Verbose($"GetAll called DashboardInstance Grain [Id : {this.GetPrimaryKeyLong()}][CurrentStatsCount : {CurrentStats?.Count}]");
_currentFilter = filter;
CurrentStats = await ApplyFilter(await _dashboardCollectorGrain.GetAll());
_logger.Verbose($"GetAll called DashboardInstance Grain [Id : {this.GetPrimaryKeyLong()}][CurrentStatsCount : {CurrentStats?.Count}]");
//if we are over the summaryViewLimit we need to keep the summary model details, then the counts will be updated every time new items are pushed here from the DashboardCollecterGrain/
if (InSummaryMode)
{
return new DiffModel
{
SummaryView = InSummaryMode,
NewGrains = GetGrainSummaries(),
SummaryViewLinks = GetGrainSummaryLinks()
};
}
//under normal circumstances we just returned the detail grains.
return new DiffModel
{
NewGrains = CurrentStats
};
}
public Task<GrainType[]> GetGrainTypes()
{
return _dashboardCollectorGrain.GetGrainTypes();
}
public Task SetSummaryViewLimit(int limit)
{
_summaryViewLimit = limit > 0 ? limit : _summaryViewLimit;
return TaskDone.Done;
}
private async Task<List<UpdateModel>> ApplyFilter(List<UpdateModel> grains = null)
{
_logger.Verbose($"Applying filters");
if (_currentFilter == null || grains == null)
return grains;
//order of filtering applies here.
//1. Grain Id & Silo
var grainQuery =
grains.Where(
p => (string.IsNullOrEmpty(_currentFilter.GrainId) || p.GrainId.ToLower().Contains(_currentFilter.GrainId.ToLower())) &&
(_currentFilter.SelectedSilos == null || _currentFilter.SelectedSilos.Length == 0 ||
_currentFilter.SelectedSilos.Contains(p.Silo)));
//2. Type filters
if (_currentFilter.TypeFilters != null)
{
var filterList = new Dictionary<string, List<string>>();
var sourceGrainTypes =
grains.Where(p => _currentFilter.TypeFilters.Any(cf => cf.TypeName == p.Type))
.Select(p => p.Type)
.Distinct()
.ToList();
foreach (var sourceGrainType in sourceGrainTypes)
{
var appliedTypeFilter = _currentFilter.TypeFilters.FirstOrDefault(p => p.TypeName == sourceGrainType);
var grainIdsGrainType = new List<string>();
if (appliedTypeFilter?.SelectedValues != null && appliedTypeFilter.SelectedValues.Any())
{
//fetch the filters
var filterGrain = GrainFactory.GetGrain<IFilterGrain>(Guid.Empty);
var currentTypeFilters = await filterGrain.GetFilters(_currentFilter.TypeFilters.Select(p => p.TypeName).ToArray());
foreach (var currentTypeFilter in currentTypeFilters)
{
grainIdsGrainType.AddRange(currentTypeFilter.Filters.
Where(
p =>
appliedTypeFilter.SelectedValues.ContainsKey(p.FilterName) &&
appliedTypeFilter.SelectedValues[p.FilterName].Contains(p.Value)
).Select(p => p.GrainId).ToList());
}
}
filterList.Add(sourceGrainType, grainIdsGrainType);
}
grainQuery = grainQuery.Where(p => filterList.ContainsKey(p.Type) && (filterList[p.Type] == null || filterList[p.Type].Any() == false || filterList[p.Type].Contains(p.GrainId)));
}
return grainQuery.ToList();
}
public async Task OnNextAsync(DiffModel item, StreamSequenceToken token = null)
{
_logger.Verbose($"OnNextAsync called with {item.NewGrains.Count} items");
var newGrains = await ApplyFilter(item.NewGrains);
CurrentStats?.AddRange(newGrains);
if (InSummaryMode)
{
await _dashboardInstanceStream.OnNextAsync(new DiffModel
{
SummaryView = InSummaryMode,
TypeCounts = item.TypeCounts,
NewGrains = GetGrainSummaries(),
SummaryViewLinks = GetGrainSummaryLinks(),
SessionId = SessionId
});
}
else
{
item.NewGrains = newGrains;
_logger.Verbose($"OnNextAsync called with {item.NewGrains.Count} items");
if (item.NewGrains != null && (item.NewGrains.Any() || item.RemovedGrains.Any()))
{
item.SummaryView = InSummaryMode;
item.SessionId = SessionId;
await _dashboardInstanceStream.OnNextAsync(item);
}
}
}
private List<Link> GetGrainSummaryLinks()
{
//add the orniscient info here......
var summaryLinks = new List<Link>();
foreach (var updateModel in CurrentStats)
{
var orniscientInfo = _orniscientLink.GetLinkFromType(updateModel.Type);
if (orniscientInfo.HasLinkFromType)
{
var linkToGrain = CurrentStats.FirstOrDefault(p => p.Id == updateModel.LinkToId);
if (linkToGrain != null)
{
string linkToGrainSummaryId = $"{linkToGrain.Type}_{linkToGrain.Silo}";
string fromGrainSummaryId = $"{updateModel.Type}_{updateModel.Silo}";
var link = summaryLinks.FirstOrDefault(p => p.FromId == fromGrainSummaryId && p.ToId == linkToGrainSummaryId);
if (link != null)
{
link.Count++;
}
else
{
summaryLinks.Add(new Link
{
Count = 1,
FromId = fromGrainSummaryId,
ToId = linkToGrainSummaryId
});
}
}
}
}
return summaryLinks;
}
private List<UpdateModel> GetGrainSummaries()
{
var changedSummaries = (from grain in CurrentStats
group grain by new { grain.Type, grain.Silo, grain.Colour }
into grp
select new UpdateModel
{
Type = grp.Key.Type,
Silo = grp.Key.Silo,
Colour = grp.Key.Colour,
Count = grp.Count(),
GrainId = $"{grp.Key.Type}_{grp.Key.Silo}",
Id = $"{grp.Key.Type}_{grp.Key.Silo}"
}).ToList();
return changedSummaries;
}
public Task OnCompletedAsync()
{
return TaskDone.Done;
}
public Task OnErrorAsync(Exception ex)
{
return TaskDone.Done;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.IO.Tests
{
public class File_Delete : FileSystemTest
{
#region Utilities
public virtual void Delete(string path)
{
File.Delete(path);
}
public virtual FileInfo Create(string path)
{
var ret = new FileInfo(path);
ret.Create().Dispose();
return ret;
}
#endregion
#region UniversalTests
[Fact]
public void NullParameters()
{
Assert.Throws<ArgumentNullException>(() => Delete(null));
}
[Fact]
public void InvalidParameters()
{
Assert.Throws<ArgumentException>(() => Delete(string.Empty));
}
[Fact]
public void DeleteDot_ThrowsUnauthorizedAccessException()
{
Assert.Throws<UnauthorizedAccessException>(() => Delete("."));
}
[Fact]
public void ShouldBeAbleToDeleteHiddenFile()
{
FileInfo testFile = Create(GetTestFilePath());
testFile.Attributes = FileAttributes.Hidden;
Delete(testFile.FullName);
Assert.False(testFile.Exists);
}
[Fact]
public void DeleteNonEmptyFile()
{
FileInfo testFile = Create(GetTestFilePath());
File.WriteAllText(testFile.FullName, "This is content");
Delete(testFile.FullName);
Assert.False(testFile.Exists);
}
[Fact]
public void PositiveTest()
{
FileInfo testFile = Create(GetTestFilePath());
Delete(testFile.FullName);
Assert.False(testFile.Exists);
}
[Fact]
public void NonExistentFile()
{
Delete(GetTestFilePath());
}
[Fact]
public void ShouldThrowIOExceptionDeletingDirectory()
{
Assert.Throws<UnauthorizedAccessException>(() => Delete(TestDirectory));
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void DeletingSymLinkDoesntDeleteTarget()
{
var path = GetTestFilePath();
var linkPath = GetTestFilePath();
File.Create(path).Dispose();
Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false));
// Both the symlink and the target exist
Assert.True(File.Exists(path), "path should exist");
Assert.True(File.Exists(linkPath), "linkPath should exist");
// Delete the symlink
File.Delete(linkPath);
// Target should still exist
Assert.True(File.Exists(path), "path should still exist");
Assert.False(File.Exists(linkPath), "linkPath should no longer exist");
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting non-existent path throws
public void Windows_NonExistentPath_Throws_DirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(TestDirectory, GetTestFileName(), "C")));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting non-existent path doesn't throw
public void Unix_NonExistentPath_Nop()
{
Delete(Path.Combine(TestDirectory, GetTestFileName(), "C"));
}
[Fact]
[OuterLoop("Needs sudo access")]
[PlatformSpecific(TestPlatforms.Linux)]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void Unix_NonExistentPath_ReadOnlyVolume()
{
if (PlatformDetection.IsRedHatFamily6)
return; // [ActiveIssue(https://github.com/dotnet/corefx/issues/21920)]
ReadOnly_FileSystemHelper(readOnlyDirectory =>
{
Delete(Path.Combine(readOnlyDirectory, "DoesNotExist"));
});
}
[Fact]
[OuterLoop("Needs sudo access")]
[PlatformSpecific(TestPlatforms.Linux)]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void Unix_ExistingDirectory_ReadOnlyVolume()
{
if (PlatformDetection.IsRedHatFamily6)
return; // [ActiveIssue(https://github.com/dotnet/corefx/issues/21920)]
ReadOnly_FileSystemHelper(readOnlyDirectory =>
{
Assert.Throws<IOException>(() => Delete(Path.Combine(readOnlyDirectory, "subdir")));
}, subDirectoryName: "subdir");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting already-open file throws
public void Windows_File_Already_Open_Throws_IOException()
{
string path = GetTestFilePath();
using (File.Create(path))
{
Assert.Throws<IOException>(() => Delete(path));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting already-open file allowed
public void Unix_File_Already_Open_Allowed()
{
string path = GetTestFilePath();
using (File.Create(path))
{
Delete(path);
Assert.False(File.Exists(path));
}
Assert.False(File.Exists(path));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting readonly file throws
public void WindowsDeleteReadOnlyFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
File.SetAttributes(path, FileAttributes.ReadOnly);
Assert.Throws<UnauthorizedAccessException>(() => Delete(path));
Assert.True(File.Exists(path));
File.SetAttributes(path, FileAttributes.Normal);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting readonly file allowed
public void UnixDeleteReadOnlyFile()
{
FileInfo testFile = Create(GetTestFilePath());
testFile.Attributes = FileAttributes.ReadOnly;
Delete(testFile.FullName);
Assert.False(testFile.Exists);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RestSharp;
using Systran.NlpClientLib.Client;
using Systran.NlpClientLib.Model;
namespace Systran.NlpClientLib.Api {
public interface ISegmentationApi {
/// <summary>
/// Segment\n Segment an input text.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationSegmentResponse</returns>
SegmentationSegmentResponse NlpSegmentationSegmentGet (string InputFile, string Input, string Lang, int? Profile, string Callback);
/// <summary>
/// Segment\n Segment an input text.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationSegmentResponse</returns>
Task<SegmentationSegmentResponse> NlpSegmentationSegmentGetAsync (string InputFile, string Input, string Lang, int? Profile, string Callback);
/// <summary>
/// Segment and tokenize\n Segment an input text, then tokenize each segment.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationSegmentAndTokenizeResponse</returns>
SegmentationSegmentAndTokenizeResponse NlpSegmentationSegmentAndTokenizeGet (string InputFile, string Input, string Lang, int? Profile, string Callback);
/// <summary>
/// Segment and tokenize\n Segment an input text, then tokenize each segment.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationSegmentAndTokenizeResponse</returns>
Task<SegmentationSegmentAndTokenizeResponse> NlpSegmentationSegmentAndTokenizeGetAsync (string InputFile, string Input, string Lang, int? Profile, string Callback);
/// <summary>
/// Supported Languages List of languages in which Segmentation is supported.
/// </summary>
/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SupportedLanguagesResponse</returns>
SupportedLanguagesResponse NlpSegmentationSupportedLanguagesGet (string Callback);
/// <summary>
/// Supported Languages List of languages in which Segmentation is supported.
/// </summary>
/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SupportedLanguagesResponse</returns>
Task<SupportedLanguagesResponse> NlpSegmentationSupportedLanguagesGetAsync (string Callback);
/// <summary>
/// Tokenize\n Tokenize an input text.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationTokenizeResponse</returns>
SegmentationTokenizeResponse NlpSegmentationTokenizeGet (string InputFile, string Input, string Lang, int? Profile, string Callback);
/// <summary>
/// Tokenize\n Tokenize an input text.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationTokenizeResponse</returns>
Task<SegmentationTokenizeResponse> NlpSegmentationTokenizeGetAsync (string InputFile, string Input, string Lang, int? Profile, string Callback);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class SegmentationApi : ISegmentationApi {
/// <summary>
/// Initializes a new instance of the <see cref="SegmentationApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
public SegmentationApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SegmentationApi"/> class.
/// </summary>
/// <returns></returns>
public SegmentationApi(String basePath)
{
this.apiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
public ApiClient apiClient {get; set;}
/// <summary>
/// Segment\n Segment an input text.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationSegmentResponse</returns>
public SegmentationSegmentResponse NlpSegmentationSegmentGet (string InputFile, string Input, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpSegmentationSegmentGet");
var path = "/nlp/segmentation/segment";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpSegmentationSegmentGet: " + response.Content, response.Content);
}
return (SegmentationSegmentResponse) apiClient.Deserialize(response.Content, typeof(SegmentationSegmentResponse));
}
/// <summary>
/// Segment\n Segment an input text.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationSegmentResponse</returns>
public async Task<SegmentationSegmentResponse> NlpSegmentationSegmentGetAsync (string InputFile, string Input, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpSegmentationSegmentGet");
var path = "/nlp/segmentation/segment";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpSegmentationSegmentGet: " + response.Content, response.Content);
}
return (SegmentationSegmentResponse) apiClient.Deserialize(response.Content, typeof(SegmentationSegmentResponse));
}
/// <summary>
/// Segment and tokenize\n Segment an input text, then tokenize each segment.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationSegmentAndTokenizeResponse</returns>
public SegmentationSegmentAndTokenizeResponse NlpSegmentationSegmentAndTokenizeGet (string InputFile, string Input, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpSegmentationSegmentAndTokenizeGet");
var path = "/nlp/segmentation/segmentAndTokenize";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpSegmentationSegmentAndTokenizeGet: " + response.Content, response.Content);
}
return (SegmentationSegmentAndTokenizeResponse) apiClient.Deserialize(response.Content, typeof(SegmentationSegmentAndTokenizeResponse));
}
/// <summary>
/// Segment and tokenize\n Segment an input text, then tokenize each segment.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationSegmentAndTokenizeResponse</returns>
public async Task<SegmentationSegmentAndTokenizeResponse> NlpSegmentationSegmentAndTokenizeGetAsync (string InputFile, string Input, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpSegmentationSegmentAndTokenizeGet");
var path = "/nlp/segmentation/segmentAndTokenize";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpSegmentationSegmentAndTokenizeGet: " + response.Content, response.Content);
}
return (SegmentationSegmentAndTokenizeResponse) apiClient.Deserialize(response.Content, typeof(SegmentationSegmentAndTokenizeResponse));
}
/// <summary>
/// Supported Languages List of languages in which Segmentation is supported.
/// </summary>
/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SupportedLanguagesResponse</returns>
public SupportedLanguagesResponse NlpSegmentationSupportedLanguagesGet (string Callback) {
var path = "/nlp/segmentation/supportedLanguages";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpSegmentationSupportedLanguagesGet: " + response.Content, response.Content);
}
return (SupportedLanguagesResponse) apiClient.Deserialize(response.Content, typeof(SupportedLanguagesResponse));
}
/// <summary>
/// Supported Languages List of languages in which Segmentation is supported.
/// </summary>
/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SupportedLanguagesResponse</returns>
public async Task<SupportedLanguagesResponse> NlpSegmentationSupportedLanguagesGetAsync (string Callback) {
var path = "/nlp/segmentation/supportedLanguages";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpSegmentationSupportedLanguagesGet: " + response.Content, response.Content);
}
return (SupportedLanguagesResponse) apiClient.Deserialize(response.Content, typeof(SupportedLanguagesResponse));
}
/// <summary>
/// Tokenize\n Tokenize an input text.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationTokenizeResponse</returns>
public SegmentationTokenizeResponse NlpSegmentationTokenizeGet (string InputFile, string Input, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpSegmentationTokenizeGet");
var path = "/nlp/segmentation/tokenize";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpSegmentationTokenizeGet: " + response.Content, response.Content);
}
return (SegmentationTokenizeResponse) apiClient.Deserialize(response.Content, typeof(SegmentationTokenizeResponse));
}
/// <summary>
/// Tokenize\n Tokenize an input text.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Lang">Language code of the input ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>SegmentationTokenizeResponse</returns>
public async Task<SegmentationTokenizeResponse> NlpSegmentationTokenizeGetAsync (string InputFile, string Input, string Lang, int? Profile, string Callback) {
// verify the required parameter 'Lang' is set
if (Lang == null) throw new ApiException(400, "Missing required parameter 'Lang' when calling NlpSegmentationTokenizeGet");
var path = "/nlp/segmentation/tokenize";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Lang != null) queryParams.Add("lang", apiClient.ParameterToString(Lang)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpSegmentationTokenizeGet: " + response.Content, response.Content);
}
return (SegmentationTokenizeResponse) apiClient.Deserialize(response.Content, typeof(SegmentationTokenizeResponse));
}
}
}
| |
// 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>
/// Solution Feed
///<para>SObject Name: SolutionFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfSolutionFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "SolutionFeed"; }
}
///<summary>
/// Feed Item 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>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: Solution
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfSolution Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { 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>
/// 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>
/// 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>
/// 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>
/// 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>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
/*
* 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.Collections.Generic;
using System.Text;
namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{
public class Atom : IUnifiable
{
private static Dictionary<string, Atom> _atomStore = new Dictionary<string, Atom>();
public readonly string _name;
public readonly Atom _module;
/// <summary>
/// You should not call this constructor, but use Atom.a instead.
/// </summary>
/// <param name="name"></param>
/// <param name="module"></param>
private Atom(string name, Atom module)
{
_name = name;
_module = module;
}
/// <summary>
/// Return the unique Atom object for name where module is null. You should use this to create
/// an Atom instead of calling the Atom constructor.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Atom a(string name)
{
Atom atom;
if (!_atomStore.TryGetValue(name, out atom))
{
atom = new Atom(name, null);
_atomStore[name] = atom;
}
return atom;
}
/// <summary>
/// Return an Atom object with the name and module. If module is null or Atom.NIL,
/// this behaves like Atom.a(name) and returns the unique object where the module is null.
/// If module is not null or Atom.NIL, this may or may not be the same object as another Atom
/// with the same name and module.
/// </summary>
/// <param name="name"></param>
/// <param name="module"></param>
/// <returns></returns>
public static Atom a(string name, Atom module)
{
if (module == null || module == Atom.NIL)
return a(name);
return new Atom(name, module);
}
/// <summary>
/// If Obj is an Atom unify its _module with Module. If the Atom's _module is null, use Atom.NIL.
/// </summary>
/// <param name="Atom"></param>
/// <param name="Module"></param>
/// <returns></returns>
public static IEnumerable<bool> module(object Obj, object Module)
{
Obj = YP.getValue(Obj);
if (Obj is Atom)
{
if (((Atom)Obj)._module == null)
return YP.unify(Module, Atom.NIL);
else
return YP.unify(Module, ((Atom)Obj)._module);
}
return YP.fail();
}
public static readonly Atom NIL = Atom.a("[]");
public static readonly Atom DOT = Atom.a(".");
public static readonly Atom F = Atom.a("f");
public static readonly Atom SLASH = Atom.a("/");
public static readonly Atom HAT = Atom.a("^");
public static readonly Atom RULE = Atom.a(":-");
public IEnumerable<bool> unify(object arg)
{
arg = YP.getValue(arg);
if (arg is Atom)
return Equals(arg) ? YP.succeed() : YP.fail();
else if (arg is Variable)
return ((Variable)arg).unify(this);
else
return YP.fail();
}
public void addUniqueVariables(List<Variable> variableSet)
{
// Atom does not contain variables.
}
public object makeCopy(Variable.CopyStore copyStore)
{
// Atom does not contain variables that need to be copied.
return this;
}
public bool termEqual(object term)
{
return Equals(YP.getValue(term));
}
public bool ground()
{
// Atom is always ground.
return true;
}
public override bool Equals(object obj)
{
if (obj is Atom)
{
if (_module == null && ((Atom)obj)._module == null)
// When _declaringClass is null, we always use an identical object from _atomStore.
return this == obj;
// Otherwise, ignore _declaringClass and do a normal string compare on the _name.
return _name == ((Atom)obj)._name;
}
return false;
}
public override string ToString()
{
return _name;
}
public override int GetHashCode()
{
// Debug: need to check _declaringClass.
return _name.GetHashCode();
}
public string toQuotedString()
{
if (_name.Length == 0)
return "''";
else if (this == Atom.NIL)
return "[]";
StringBuilder result = new StringBuilder(_name.Length);
bool useQuotes = false;
foreach (char c in _name)
{
int cInt = (int)c;
if (c == '\'')
{
result.Append("''");
useQuotes = true;
}
else if (c == '_' || cInt >= (int)'a' && cInt <= (int)'z' ||
cInt >= (int)'A' && cInt <= (int)'Z' || cInt >= (int)'0' && cInt <= (int)'9')
result.Append(c);
else
{
// Debug: Need to handle non-printable chars.
result.Append(c);
useQuotes = true;
}
}
if (!useQuotes && (int)_name[0] >= (int)'a' && (int)_name[0] <= (int)'z')
return result.ToString();
else
{
// Surround in single quotes.
result.Append('\'');
return "'" + result;
}
}
/// <summary>
/// Return true if _name is lexicographically less than atom._name.
/// </summary>
/// <param name="atom"></param>
/// <returns></returns>
public bool lessThan(Atom atom)
{
return _name.CompareTo(atom._name) < 0;
}
}
}
| |
// 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.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// A lock-free, concurrent queue primitive, and its associated debugger view type.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents a thread-safe first-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the queue.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[ComVisible(false)]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
[HostProtection(Synchronization = true, ExternalThreading = true)]
[Serializable]
public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
//fields of ConcurrentQueue
[NonSerialized]
private volatile Segment m_head;
[NonSerialized]
private volatile Segment m_tail;
private T[] m_serializationArray; // Used for custom serialization.
private const int SEGMENT_SIZE = 32;
//number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot.
[NonSerialized]
internal volatile int m_numSnapshotTakers = 0;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
/// </summary>
public ConcurrentQueue()
{
m_head = m_tail = new Segment(0, this);
}
/// <summary>
/// Initializes the contents of the queue from an existing collection.
/// </summary>
/// <param name="collection">A collection from which to copy elements.</param>
private void InitializeFromCollection(IEnumerable<T> collection)
{
Segment localTail = new Segment(0, this);//use this local variable to avoid the extra volatile read/write. this is safe because it is only called from ctor
m_head = localTail;
int index = 0;
foreach (T element in collection)
{
Contract.Assert(index >= 0 && index < SEGMENT_SIZE);
localTail.UnsafeAdd(element);
index++;
if (index >= SEGMENT_SIZE)
{
localTail = localTail.UnsafeGrow();
index = 0;
}
}
m_tail = localTail;
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/>
/// class that contains elements copied from the specified collection
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new <see
/// cref="ConcurrentQueue{T}"/>.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is
/// null.</exception>
public ConcurrentQueue(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
InitializeFromCollection(collection);
}
/// <summary>
/// Get the data array to be serialized
/// </summary>
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
// save the data into the serialization array to be saved
m_serializationArray = ToArray();
}
/// <summary>
/// Construct the queue from a previously seiralized one
/// </summary>
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
Contract.Assert(m_serializationArray != null);
InitializeFromCollection(m_serializationArray);
m_serializationArray = null;
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
/// cref="T:System.Array"/>, starting at a particular
/// <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="T:System.Collections.Concurrent.ConcurrentBag"/>. The <see
/// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
// Validate arguments.
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
((ICollection)ToList()).CopyTo(array, index);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized
{
// Gets a value indicating whether access to this collection is synchronized. Always returns
// false. The reason is subtle. While access is in face thread safe, it's not the case that
// locking on the SyncRoot would have prevented concurrent pushes and pops, as this property
// would typically indicate; that's because we internally use CAS operations vs. true locks.
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="T:System.Collections.ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception>
object ICollection.SyncRoot
{
get
{
throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported"));
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
/// <summary>
/// Attempts to add an object to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
/// reference (Nothing in Visual Basic) for reference types.
/// </param>
/// <returns>true if the object was added successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the
/// end of the <see cref="ConcurrentQueue{T}"/>
/// and return true.</remarks>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Enqueue(item);
return true;
}
/// <summary>
/// Attempts to remove and return an object from the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object
/// from the beginning of the <see cref="ConcurrentQueue{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake(out T item)
{
return TryDequeue(out item);
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty
{
get
{
Segment head = m_head;
if (!head.IsEmpty)
//fast route 1:
//if current head is not empty, then queue is not empty
return false;
else if (head.Next == null)
//fast route 2:
//if current head is empty and it's the last segment
//then queue is empty
return true;
else
//slow route:
//current head is empty and it is NOT the last segment,
//it means another thread is growing new segment
{
SpinWait spin = new SpinWait();
while (head.IsEmpty)
{
if (head.Next == null)
return true;
spin.SpinOnce();
head = m_head;
}
return false;
}
}
}
/// <summary>
/// Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array.
/// </summary>
/// <returns>A new array containing a snapshot of elements copied from the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
public T[] ToArray()
{
return ToList().ToArray();
}
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to a new <see
/// cref="T:System.Collections.Generic.List{T}"/>.
/// </summary>
/// <returns>A new <see cref="T:System.Collections.Generic.List{T}"/> containing a snapshot of
/// elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns>
private List<T> ToList()
{
// Increments the number of active snapshot takers. This increment must happen before the snapshot is
// taken. At the same time, Decrement must happen after list copying is over. Only in this way, can it
// eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0.
Interlocked.Increment(ref m_numSnapshotTakers);
List<T> list = new List<T>();
try
{
//store head and tail positions in buffer,
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
if (head == tail)
{
head.AddToList(list, headLow, tailHigh);
}
else
{
head.AddToList(list, headLow, SEGMENT_SIZE - 1);
Segment curr = head.Next;
while (curr != tail)
{
curr.AddToList(list, 0, SEGMENT_SIZE - 1);
curr = curr.Next;
}
//Add tail segment
tail.AddToList(list, 0, tailHigh);
}
}
finally
{
// This Decrement must happen after copying is over.
Interlocked.Decrement(ref m_numSnapshotTakers);
}
return list;
}
/// <summary>
/// Store the position of the current head and tail positions.
/// </summary>
/// <param name="head">return the head segment</param>
/// <param name="tail">return the tail segment</param>
/// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param>
/// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param>
private void GetHeadTailPositions(out Segment head, out Segment tail,
out int headLow, out int tailHigh)
{
head = m_head;
tail = m_tail;
headLow = head.Low;
tailHigh = tail.High;
SpinWait spin = new SpinWait();
//we loop until the observed values are stable and sensible.
//This ensures that any update order by other methods can be tolerated.
while (
//if head and tail changed, retry
head != m_head || tail != m_tail
//if low and high pointers, retry
|| headLow != head.Low || tailHigh != tail.High
//if head jumps ahead of tail because of concurrent grow and dequeue, retry
|| head.m_index > tail.m_index)
{
spin.SpinOnce();
head = m_head;
tail = m_tail;
headLow = head.Low;
tailHigh = tail.High;
}
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
/// property and comparing it to 0.
/// </remarks>
public int Count
{
get
{
//store head and tail positions in buffer,
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
if (head == tail)
{
return tailHigh - headLow + 1;
}
//head segment
int count = SEGMENT_SIZE - headLow;
//middle segment(s), if any, are full.
//We don't deal with overflow to be consistent with the behavior of generic types in CLR.
count += SEGMENT_SIZE * ((int)(tail.m_index - head.m_index - 1));
//tail segment
count += tailHigh + 1;
return count;
}
}
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see
/// cref="T:System.Array">Array</see>, starting at the specified array index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentQueue{T}"/>. The <see cref="T:System.Array">Array</see> must have zero-based
/// indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the
/// available space from <paramref name="index"/> to the end of the destination <paramref
/// name="array"/>.
/// </exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
ToList().CopyTo(array, index);
}
/// <summary>
/// Returns an enumerator that iterates through the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the queue. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the queue.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
// Increments the number of active snapshot takers. This increment must happen before the snapshot is
// taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it
// eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0.
Interlocked.Increment(ref m_numSnapshotTakers);
// Takes a snapshot of the queue.
// A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot
// wrap the following with a try/finally block, otherwise the decrement will happen before the yield return
// statements in the GetEnumerator (head, tail, headLow, tailHigh) method.
Segment head, tail;
int headLow, tailHigh;
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);
//If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
// the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called.
// This is inconsistent with existing generic collections. In order to prevent it, we capture the
// value of m_head in a buffer and call out to a helper method.
//The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an
// unnecessary perfomance hit.
return GetEnumerator(head, tail, headLow, tailHigh);
}
/// <summary>
/// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation.
/// </summary>
private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh)
{
try
{
SpinWait spin = new SpinWait();
if (head == tail)
{
for (int i = headLow; i <= tailHigh; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!head.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return head.m_array[i];
}
}
else
{
//iterate on head segment
for (int i = headLow; i < SEGMENT_SIZE; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!head.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return head.m_array[i];
}
//iterate on middle segments
Segment curr = head.Next;
while (curr != tail)
{
for (int i = 0; i < SEGMENT_SIZE; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!curr.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return curr.m_array[i];
}
curr = curr.Next;
}
//iterate on tail segment
for (int i = 0; i <= tailHigh; i++)
{
// If the position is reserved by an Enqueue operation, but the value is not written into,
// spin until the value is available.
spin.Reset();
while (!tail.m_state[i].m_value)
{
spin.SpinOnce();
}
yield return tail.m_array[i];
}
}
}
finally
{
// This Decrement must happen after the enumeration is over.
Interlocked.Decrement(ref m_numSnapshotTakers);
}
}
/// <summary>
/// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="item">The object to add to the end of the <see
/// cref="ConcurrentQueue{T}"/>. The value can be a null reference
/// (Nothing in Visual Basic) for reference types.
/// </param>
public void Enqueue(T item)
{
SpinWait spin = new SpinWait();
while (true)
{
Segment tail = m_tail;
if (tail.TryAppend(item))
return;
spin.SpinOnce();
}
}
/// <summary>
/// Attempts to remove and return the object at the beginning of the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="result">
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned from the beggining of the <see
/// cref="ConcurrentQueue{T}"/>
/// succesfully; otherwise, false.</returns>
public bool TryDequeue(out T result)
{
while (!IsEmpty)
{
Segment head = m_head;
if (head.TryRemove(out result))
return true;
//since method IsEmpty spins, we don't need to spin in the while loop
}
result = default(T);
return false;
}
/// <summary>
/// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from
/// the beginning of the <see cref="T:System.Collections.Concurrent.ConccurrentQueue{T}"/> or an
/// unspecified value if the operation failed.</param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
public bool TryPeek(out T result)
{
Interlocked.Increment(ref m_numSnapshotTakers);
while (!IsEmpty)
{
Segment head = m_head;
if (head.TryPeek(out result))
{
Interlocked.Decrement(ref m_numSnapshotTakers);
return true;
}
//since method IsEmpty spins, we don't need to spin in the while loop
}
result = default(T);
Interlocked.Decrement(ref m_numSnapshotTakers);
return false;
}
/// <summary>
/// private class for ConcurrentQueue.
/// a queue is a linked list of small arrays, each node is called a segment.
/// A segment contains an array, a pointer to the next segment, and m_low, m_high indices recording
/// the first and last valid elements of the array.
/// </summary>
private class Segment
{
//we define two volatile arrays: m_array and m_state. Note that the accesses to the array items
//do not get volatile treatment. But we don't need to worry about loading adjacent elements or
//store/load on adjacent elements would suffer reordering.
// - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe.
// - Two loads: because one item from two volatile arrays are accessed, the loads of the array references
// are sufficient to prevent reordering of the loads of the elements.
internal volatile T[] m_array;
// For each entry in m_array, the corresponding entry in m_state indicates whether this position contains
// a valid value. m_state is initially all false.
internal volatile VolatileBool[] m_state;
//pointer to the next segment. null if the current segment is the last segment
private volatile Segment m_next;
//We use this zero based index to track how many segments have been created for the queue, and
//to compute how many active segments are there currently.
// * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1;
// * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely
// assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4
// billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years.
internal readonly long m_index;
//indices of where the first and last valid values
// - m_low points to the position of the next element to pop from this segment, range [0, infinity)
// m_low >= SEGMENT_SIZE implies the segment is disposable
// - m_high points to the position of the latest pushed element, range [-1, infinity)
// m_high == -1 implies the segment is new and empty
// m_high >= SEGMENT_SIZE-1 means this segment is ready to grow.
// and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment
// - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty
// - initially m_low =0 and m_high=-1;
private volatile int m_low;
private volatile int m_high;
private volatile ConcurrentQueue<T> m_source;
/// <summary>
/// Create and initialize a segment with the specified index.
/// </summary>
internal Segment(long index, ConcurrentQueue<T> source)
{
m_array = new T[SEGMENT_SIZE];
m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
m_high = -1;
Contract.Assert(index >= 0);
m_index = index;
m_source = source;
}
/// <summary>
/// return the next segment
/// </summary>
internal Segment Next
{
get { return m_next; }
}
/// <summary>
/// return true if the current segment is empty (doesn't have any element available to dequeue,
/// false otherwise
/// </summary>
internal bool IsEmpty
{
get { return (Low > High); }
}
/// <summary>
/// Add an element to the tail of the current segment
/// exclusively called by ConcurrentQueue.InitializedFromCollection
/// InitializeFromCollection is responsible to guaratee that there is no index overflow,
/// and there is no contention
/// </summary>
/// <param name="value"></param>
internal void UnsafeAdd(T value)
{
Contract.Assert(m_high < SEGMENT_SIZE - 1);
m_high++;
m_array[m_high] = value;
m_state[m_high].m_value = true;
}
/// <summary>
/// Create a new segment and append to the current one
/// Does not update the m_tail pointer
/// exclusively called by ConcurrentQueue.InitializedFromCollection
/// InitializeFromCollection is responsible to guaratee that there is no index overflow,
/// and there is no contention
/// </summary>
/// <returns>the reference to the new Segment</returns>
internal Segment UnsafeGrow()
{
Contract.Assert(m_high >= SEGMENT_SIZE - 1);
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
m_next = newSegment;
return newSegment;
}
/// <summary>
/// Create a new segment and append to the current one
/// Update the m_tail pointer
/// This method is called when there is no contention
/// </summary>
internal void Grow()
{
//no CAS is needed, since there is no contention (other threads are blocked, busy waiting)
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
m_next = newSegment;
Contract.Assert(m_source.m_tail == this);
m_source.m_tail = m_next;
}
/// <summary>
/// Try to append an element at the end of this segment.
/// </summary>
/// <param name="value">the element to append</param>
/// <param name="tail">The tail.</param>
/// <returns>true if the element is appended, false if the current segment is full</returns>
/// <remarks>if appending the specified element succeeds, and after which the segment is full,
/// then grow the segment</remarks>
internal bool TryAppend(T value)
{
//quickly check if m_high is already over the boundary, if so, bail out
if (m_high >= SEGMENT_SIZE - 1)
{
return false;
}
//Now we will use a CAS to increment m_high, and store the result in newhigh.
//Depending on how many free spots left in this segment and how many threads are doing this Increment
//at this time, the returning "newhigh" can be
// 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value
// 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment
// 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to
// Queue.Enqueue method, telling it to try again in the next segment.
int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary
//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
//without interuption. This is to prevent anything from happening between them, and another dequeue
//thread maybe spinning forever to wait for m_state[] to be true;
try
{ }
finally
{
newhigh = Interlocked.Increment(ref m_high);
if (newhigh <= SEGMENT_SIZE - 1)
{
m_array[newhigh] = value;
m_state[newhigh].m_value = true;
}
//if this thread takes up the last slot in the segment, then this thread is responsible
//to grow a new segment. Calling Grow must be in the finally block too for reliability reason:
//if thread abort during Grow, other threads will be left busy spinning forever.
if (newhigh == SEGMENT_SIZE - 1)
{
Grow();
}
}
//if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot
return newhigh <= SEGMENT_SIZE - 1;
}
/// <summary>
/// try to remove an element from the head of current segment
/// </summary>
/// <param name="result">The result.</param>
/// <param name="head">The head.</param>
/// <returns>return false only if the current segment is empty</returns>
internal bool TryRemove(out T result)
{
SpinWait spin = new SpinWait();
int lowLocal = Low, highLocal = High;
while (lowLocal <= highLocal)
{
//try to update m_low
if (Interlocked.CompareExchange(ref m_low, lowLocal + 1, lowLocal) == lowLocal)
{
//if the specified value is not available (this spot is taken by a push operation,
// but the value is not written into yet), then spin
SpinWait spinLocal = new SpinWait();
while (!m_state[lowLocal].m_value)
{
spinLocal.SpinOnce();
}
result = m_array[lowLocal];
// If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null.
// It is ok if after this conditional check m_numSnapshotTakers becomes > 0, because new snapshots won't include
// the deleted entry at m_array[lowLocal].
if (m_source.m_numSnapshotTakers <= 0)
{
m_array[lowLocal] = default(T); //release the reference to the object.
}
//if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes
//disposable, then this thread is responsible to dispose this segment, and reset m_head
if (lowLocal + 1 >= SEGMENT_SIZE)
{
// Invariant: we only dispose the current m_head, not any other segment
// In usual situation, disposing a segment is simply seting m_head to m_head.m_next
// But there is one special case, where m_head and m_tail points to the same and ONLY
//segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow,
//while the *current* thread is doing *this* Dequeue operation, and finds that it needs to
//dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its
//Grow operation, this is the reason of having the following while loop
spinLocal = new SpinWait();
while (m_next == null)
{
spinLocal.SpinOnce();
}
Contract.Assert(m_source.m_head == this);
m_source.m_head = m_next;
}
return true;
}
else
{
//CAS failed due to contention: spin briefly and retry
spin.SpinOnce();
lowLocal = Low; highLocal = High;
}
}//end of while
result = default(T);
return false;
}
/// <summary>
/// try to peek the current segment
/// </summary>
/// <param name="result">holds the return value of the element at the head position,
/// value set to default(T) if there is no such an element</param>
/// <returns>true if there are elements in the current segment, false otherwise</returns>
internal bool TryPeek(out T result)
{
result = default(T);
int lowLocal = Low;
if (lowLocal > High)
return false;
SpinWait spin = new SpinWait();
while (!m_state[lowLocal].m_value)
{
spin.SpinOnce();
}
result = m_array[lowLocal];
return true;
}
/// <summary>
/// Adds part or all of the current segment into a List.
/// </summary>
/// <param name="list">the list to which to add</param>
/// <param name="start">the start position</param>
/// <param name="end">the end position</param>
internal void AddToList(List<T> list, int start, int end)
{
for (int i = start; i <= end; i++)
{
SpinWait spin = new SpinWait();
while (!m_state[i].m_value)
{
spin.SpinOnce();
}
list.Add(m_array[i]);
}
}
/// <summary>
/// return the position of the head of the current segment
/// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty
/// </summary>
internal int Low
{
get
{
return Math.Min(m_low, SEGMENT_SIZE);
}
}
/// <summary>
/// return the logical position of the tail of the current segment
/// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet
/// </summary>
internal int High
{
get
{
//if m_high > SEGMENT_SIZE, it means it's out of range, we should return
//SEGMENT_SIZE-1 as the logical position
return Math.Min(m_high, SEGMENT_SIZE - 1);
}
}
}
}//end of class Segment
/// <summary>
/// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile
/// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile
/// </summary>
struct VolatileBool
{
public VolatileBool(bool value)
{
m_value = value;
}
public volatile bool m_value;
}
}
| |
// 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 AlignRightUInt320()
{
var test = new ImmBinaryOpTest__AlignRightUInt320();
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__AlignRightUInt320
{
private struct TestStruct
{
public Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__AlignRightUInt320 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<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable;
static ImmBinaryOpTest__AlignRightUInt320()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public ImmBinaryOpTest__AlignRightUInt320()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[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<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_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((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_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((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_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<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(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<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(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<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)),
(byte)0
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(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<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt32>>(_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((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt32*)(_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((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt32*)(_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__AlignRightUInt320();
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<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] 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)}<UInt32>(Vector256<UInt32>.0, Vector256<UInt32>): {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;
}
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kodestruct.Common.CalculationLogger;
using Kodestruct.Common.Mathematics;
using Kodestruct.Concrete.ACI;
using Kodestruct.Concrete.ACI318_14.Materials;
using Kodestruct.Common.Section.General;
using Kodestruct.Concrete.ACI.Entities;
namespace Kodestruct.Concrete.ACI318_14
{
public partial class FlexuralSectionFactory
{
// public ConcreteSectionFlexure GetRectangularSectionWithBoundaryZones(double b, double h,
//double A_sBoundary, double L_Boundary, RebarDesignation curtainBar, double s_curtain, int N_curtains, IConcreteMaterial mat, IRebarMaterial rebarMaterial,
// ConfinementReinforcementType ConfinementReinforcementType, int NumberOfSubdivisions = 20)
// {
// double YTop = h / 2.0 - c_centTopBottom;
// double YBottom = -h / 2.0 + c_centTopBottom;
// double XLeft = -b / 2.0 + c_centLeftRight;
// double XRight = b / 2.0 - c_centLeftRight;
// Point2D P1 = new Point2D(XLeft, YTop);
// Point2D P2 = new Point2D(XRight, YTop);
// Point2D P3 = new Point2D(XRight, YBottom);
// Point2D P4 = new Point2D(XLeft, YBottom);
// RebarLine topLine = null;
// RebarLine bottomLine = null;
// RebarLine leftLine = null;
// RebarLine rightLine = null;
// if (NumberOfSubdivisions == 0)
// {
// topLine = new RebarLine(A_sTopBottom, P1, P2, rebarMaterial, false);
// bottomLine = new RebarLine(A_sTopBottom, P3, P4, rebarMaterial, false);
// if (A_sLeftRight > 0)
// {
// leftLine = new RebarLine(A_sLeftRight, P2, P3, rebarMaterial, true);
// rightLine = new RebarLine(A_sLeftRight, P4, P1, rebarMaterial, true);
// }
// }
// else
// {
// topLine = new RebarLine(A_sTopBottom, P1, P2, rebarMaterial, false, false, NumberOfSubdivisions);
// bottomLine = new RebarLine(A_sTopBottom, P3, P4, rebarMaterial, false, false, NumberOfSubdivisions);
// if (A_sLeftRight > 0)
// {
// leftLine = new RebarLine(A_sLeftRight, P2, P3, rebarMaterial, true, false, NumberOfSubdivisions);
// rightLine = new RebarLine(A_sLeftRight, P4, P1, rebarMaterial, true, false, NumberOfSubdivisions);
// }
// }
// List<RebarPoint> LongitudinalBars = new List<RebarPoint>();
// if (topLine != null) LongitudinalBars.AddRange(topLine.RebarPoints);
// if (bottomLine != null) LongitudinalBars.AddRange(bottomLine.RebarPoints);
// if (leftLine != null) LongitudinalBars.AddRange(leftLine.RebarPoints);
// if (rightLine != null) LongitudinalBars.AddRange(rightLine.RebarPoints);
// CrossSectionRectangularShape section = new CrossSectionRectangularShape(mat, null, b, h);
// CalcLog log = new CalcLog();
// ConcreteSectionFlexure sectionFlexure = new ConcreteSectionFlexure(section, LongitudinalBars, log, ConfinementReinforcementType);
// return sectionFlexure;
// }
public ConcreteSectionFlexure GetRectangularSectionFourSidesDistributed(double b, double h,
double A_sTopBottom, double A_sLeftRight, double c_centTopBottom, double c_centLeftRight, IConcreteMaterial mat, IRebarMaterial rebarMaterial,
ConfinementReinforcementType ConfinementReinforcementType, int NumberOfSubdivisions =0)
{
double YTop = h / 2.0 - c_centTopBottom;
double YBottom = -h / 2.0 + c_centTopBottom;
double XLeft = -b / 2.0 + c_centLeftRight;
double XRight = b / 2.0 - c_centLeftRight;
Point2D P1 = new Point2D(XLeft, YTop);
Point2D P2 = new Point2D(XRight, YTop);
Point2D P3 = new Point2D(XRight, YBottom);
Point2D P4 = new Point2D(XLeft, YBottom);
RebarLine topLine =null;
RebarLine bottomLine=null;
RebarLine leftLine =null;
RebarLine rightLine =null;
if (NumberOfSubdivisions == 0)
{
topLine = new RebarLine(A_sTopBottom, P1, P2, rebarMaterial, false);
bottomLine = new RebarLine(A_sTopBottom, P3, P4, rebarMaterial, false);
if (A_sLeftRight>0)
{
leftLine = new RebarLine(A_sLeftRight, P2, P3, rebarMaterial, true);
rightLine = new RebarLine(A_sLeftRight, P4, P1, rebarMaterial, true);
}
}
else
{
topLine = new RebarLine(A_sTopBottom, P1, P2, rebarMaterial, false, false, NumberOfSubdivisions);
bottomLine = new RebarLine(A_sTopBottom, P3, P4, rebarMaterial, false,false, NumberOfSubdivisions);
if (A_sLeftRight > 0)
{
leftLine = new RebarLine(A_sLeftRight, P2, P3, rebarMaterial, true, false, NumberOfSubdivisions);
rightLine = new RebarLine(A_sLeftRight, P4, P1, rebarMaterial, true, false, NumberOfSubdivisions);
}
}
List<RebarPoint> LongitudinalBars = new List<RebarPoint>();
if (topLine!= null ) LongitudinalBars.AddRange(topLine.RebarPoints);
if (bottomLine!= null) LongitudinalBars.AddRange(bottomLine.RebarPoints);
if (leftLine!= null ) LongitudinalBars.AddRange(leftLine.RebarPoints);
if (rightLine!= null ) LongitudinalBars.AddRange(rightLine.RebarPoints);
CrossSectionRectangularShape section = new CrossSectionRectangularShape(mat, null, b, h);
CalcLog log = new CalcLog();
ConcreteSectionFlexure sectionFlexure = new ConcreteSectionFlexure(section, LongitudinalBars, log, ConfinementReinforcementType);
return sectionFlexure;
}
public ConcreteSectionFlexure GetNonPrestressedDoublyReinforcedRectangularSection(double b, double h,
double A_s1,double A_s2,double c_cntr1,double c_cntr2,
ConcreteMaterial concreteMaterial, IRebarMaterial rebarMaterial, ConfinementReinforcementType ConfinementReinforcementType)
{
return GetNonPrestressedDoublyReinforcedRectangularSection(b, h, A_s1, A_s2, c_cntr1, c_cntr2, 0, 0, 0, 0, concreteMaterial, rebarMaterial, ConfinementReinforcementType);
}
public ConcreteSectionFlexure GetNonPrestressedDoublyReinforcedRectangularSection(double b, double h,
double A_s1,double A_s2,double c_cntr1,double c_cntr2,
double A_s_prime1,double A_s_prime2, double c_cntr_prime1, double c_cntr_prime2,
ConcreteMaterial concrete, IRebarMaterial rebar, ConfinementReinforcementType ConfinementReinforcementType)
{
CrossSectionRectangularShape Section = new CrossSectionRectangularShape(concrete, null, b, h);
List<RebarPoint> LongitudinalBars = new List<RebarPoint>();
Rebar bottom1 = new Rebar(A_s1, rebar);
RebarPoint pointBottom1 = new RebarPoint(bottom1, new RebarCoordinate() { X = 0, Y = -h / 2.0 + c_cntr1 });
LongitudinalBars.Add(pointBottom1);
if (A_s2!=0)
{
Rebar bottom2 = new Rebar(A_s2, rebar);
RebarPoint pointBottom2 = new RebarPoint(bottom2, new RebarCoordinate() { X = 0, Y = -h / 2.0 + c_cntr2 });
LongitudinalBars.Add(pointBottom2);
}
if (A_s_prime1 != 0)
{
Rebar top1 = new Rebar(A_s_prime1, rebar);
RebarPoint pointTop1 = new RebarPoint(top1, new RebarCoordinate() { X = 0, Y = h / 2.0 - c_cntr_prime1 });
LongitudinalBars.Add(pointTop1);
}
if (A_s_prime2 != 0)
{
Rebar top2 = new Rebar(A_s_prime2, rebar);
RebarPoint pointTop2 = new RebarPoint(top2, new RebarCoordinate() { X = 0, Y = h / 2.0 - c_cntr_prime2 });
LongitudinalBars.Add(pointTop2);
}
CalcLog log = new CalcLog();
ConcreteSectionFlexure beam = new ConcreteSectionFlexure(Section, LongitudinalBars, log, ConfinementReinforcementType);
return beam;
}
/// <summary>
/// Concrete generic shape
/// </summary>
/// <param name="PolygonPoints">Points representing closed polyline describing the outline of concrete shape</param>
/// <param name="Concrete">Concrete material</param>
/// <param name="RebarPoints">Points representing vertical rebar. Rebar points have associated rebar material and location</param>
/// <param name="b_w">Section width (required for shear strength calculations)</param>
/// <param name="ConfinementReinforcementType"></param>
/// <param name="d">Distance from tension rebar centroid to the furthermost compressed point (required for shear strength calculations)</param>
/// <returns></returns>
public ConcreteSectionFlexure GetGeneralSection(List<Point2D> PolygonPoints,
IConcreteMaterial Concrete, List<RebarPoint> RebarPoints, double b_w, double d,
ConfinementReinforcementType ConfinementReinforcementType= ConfinementReinforcementType.NoReinforcement)
{
CalcLog log = new CalcLog();
var GenericShape = new PolygonShape(PolygonPoints);
CrossSectionGeneralShape Section = new CrossSectionGeneralShape(Concrete, null, GenericShape, b_w, d);
ConcreteSectionFlexure beam = new ConcreteSectionFlexure(Section, RebarPoints, log, ConfinementReinforcementType);
return beam;
}
}
}
| |
/*
* Copyright (c) 2006-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
/// <summary>
/// Class for controlling various system settings.
/// </summary>
/// <remarks>Some values are readonly because they affect things that
/// happen when the GridClient object is initialized, so changing them at
/// runtime won't do any good. Non-readonly values may affect things that
/// happen at login or dynamically</remarks>
public class Settings
{
#region Login/Networking Settings
/// <summary>Main grid login server</summary>
public const string AGNI_LOGIN_SERVER = "https://login.agni.lindenlab.com/cgi-bin/login.cgi";
/// <summary>Beta grid login server</summary>
public const string ADITI_LOGIN_SERVER = "https://login.aditi.lindenlab.com/cgi-bin/login.cgi";
/// <summary>The relative directory where external resources are kept</summary>
public static string RESOURCE_DIR = "openmetaverse_data";
/// <summary>Login server to connect to</summary>
public string LOGIN_SERVER = AGNI_LOGIN_SERVER;
/// <summary>IP Address the client will bind to</summary>
public static System.Net.IPAddress BIND_ADDR = System.Net.IPAddress.Any;
/// <summary>Use XML-RPC Login or LLSD Login, default is XML-RPC Login</summary>
public bool USE_LLSD_LOGIN = false;
#endregion
#region Inventory
/// <summary>
/// InventoryManager requests inventory information on login,
/// GridClient initializes an Inventory store for main inventory.
/// </summary>
public const bool ENABLE_INVENTORY_STORE = true;
/// <summary>
/// InventoryManager requests library information on login,
/// GridClient initializes an Inventory store for the library.
/// </summary>
public const bool ENABLE_LIBRARY_STORE = true;
/// <summary>
/// Use Caps for fetching inventory where available
/// </summary>
public bool HTTP_INVENTORY = true;
#endregion
#region Timeouts and Intervals
/// <summary>Number of milliseconds before an asset transfer will time
/// out</summary>
public int TRANSFER_TIMEOUT = 90 * 1000;
/// <summary>Number of milliseconds before a teleport attempt will time
/// out</summary>
public int TELEPORT_TIMEOUT = 40 * 1000;
/// <summary>Number of milliseconds before NetworkManager.Logout() will
/// time out</summary>
public int LOGOUT_TIMEOUT = 5 * 1000;
/// <summary>Number of milliseconds before a CAPS call will time out</summary>
/// <remarks>Setting this too low will cause web requests time out and
/// possibly retry repeatedly</remarks>
public int CAPS_TIMEOUT = 60 * 1000;
/// <summary>Number of milliseconds for xml-rpc to timeout</summary>
public int LOGIN_TIMEOUT = 60 * 1000;
/// <summary>Milliseconds before a packet is assumed lost and resent</summary>
public int RESEND_TIMEOUT = 4000;
/// <summary>Milliseconds without receiving a packet before the
/// connection to a simulator is assumed lost</summary>
public int SIMULATOR_TIMEOUT = 30 * 1000;
/// <summary>Milliseconds to wait for a simulator info request through
/// the grid interface</summary>
public int MAP_REQUEST_TIMEOUT = 5 * 1000;
/// <summary>Number of milliseconds between sending pings to each sim</summary>
public const int PING_INTERVAL = 2200;
/// <summary>Number of milliseconds between sending camera updates</summary>
public const int DEFAULT_AGENT_UPDATE_INTERVAL = 500;
/// <summary>Number of milliseconds between updating the current
/// positions of moving, non-accelerating and non-colliding objects</summary>
public const int INTERPOLATION_INTERVAL = 250;
/// <summary>Millisecond interval between ticks, where all ACKs are
/// sent out and the age of unACKed packets is checked</summary>
public const int NETWORK_TICK_INTERVAL = 500;
#endregion
#region Sizes
/// <summary>The initial size of the packet inbox, where packets are
/// stored before processing</summary>
public const int PACKET_INBOX_SIZE = 100;
/// <summary>Maximum size of packet that we want to send over the wire</summary>
public const int MAX_PACKET_SIZE = 1200;
/// <summary>The maximum value of a packet sequence number before it
/// rolls over back to one</summary>
public const int MAX_SEQUENCE = 0xFFFFFF;
/// <summary>The maximum size of the sequence number archive, used to
/// check for resent and/or duplicate packets</summary>
public static int PACKET_ARCHIVE_SIZE = 1000;
/// <summary>Maximum number of queued ACKs to be sent before SendAcks()
/// is forced</summary>
public int MAX_PENDING_ACKS = 10;
/// <summary>Network stats queue length (seconds)</summary>
public int STATS_QUEUE_SIZE = 5;
#endregion
#region Experimental options
/// <summary>
/// Primitives will be reused when falling in/out of interest list (and shared between clients)
/// prims returning to interest list do not need re-requested
/// Helps also in not re-requesting prim.Properties for code that checks for a Properties == null per client
/// </summary>
public bool CACHE_PRIMITIVES = false;
/// <summary>
/// Pool parcel data between clients (saves on requesting multiple times when all clients may need it)
/// </summary>
public bool POOL_PARCEL_DATA = false;
/// <summary>
/// How long to preserve cached data when no client is connected to a simulator
/// The reason for setting it to something like 2 minutes is in case a client
/// is running back and forth between region edges or a sim is comming and going
/// </summary>
public static int SIMULATOR_POOL_TIMEOUT = 2 * 60 * 1000;
#endregion
#region Configuration options (mostly booleans)
/// <summary>Enable/disable storing terrain heightmaps in the
/// TerrainManager</summary>
public bool STORE_LAND_PATCHES = false;
/// <summary>Enable/disable sending periodic camera updates</summary>
public bool SEND_AGENT_UPDATES = true;
/// <summary>Enable/disable automatically setting agent appearance at
/// login and after sim crossing</summary>
public bool SEND_AGENT_APPEARANCE = true;
/// <summary>Enable/disable automatically setting the bandwidth throttle
/// after connecting to each simulator</summary>
/// <remarks>The default throttle uses the equivalent of the maximum
/// bandwidth setting in the official client. If you do not set a
/// throttle your connection will by default be throttled well below
/// the minimum values and you may experience connection problems</remarks>
public bool SEND_AGENT_THROTTLE = true;
/// <summary>Enable/disable the sending of pings to monitor lag and
/// packet loss</summary>
public bool SEND_PINGS = true;
/// <summary>Should we connect to multiple sims? This will allow
/// viewing in to neighboring simulators and sim crossings
/// (Experimental)</summary>
public bool MULTIPLE_SIMS = true;
/// <summary>If true, all object update packets will be decoded in to
/// native objects. If false, only updates for our own agent will be
/// decoded. Registering an event handler will force objects for that
/// type to always be decoded. If this is disabled the object tracking
/// will have missing or partial prim and avatar information</summary>
public bool ALWAYS_DECODE_OBJECTS = true;
/// <summary>If true, when a cached object check is received from the
/// server the full object info will automatically be requested</summary>
public bool ALWAYS_REQUEST_OBJECTS = true;
/// <summary>Whether to establish connections to HTTP capabilities
/// servers for simulators</summary>
public bool ENABLE_CAPS = true;
/// <summary>Whether to decode sim stats</summary>
public bool ENABLE_SIMSTATS = true;
/// <summary>The capabilities servers are currently designed to
/// periodically return a 502 error which signals for the client to
/// re-establish a connection. Set this to true to log those 502 errors</summary>
public bool LOG_ALL_CAPS_ERRORS = false;
/// <summary>If true, any reference received for a folder or item
/// the library is not aware of will automatically be fetched</summary>
public bool FETCH_MISSING_INVENTORY = true;
/// <summary>If true, and <code>SEND_AGENT_UPDATES</code> is true,
/// AgentUpdate packets will continuously be sent out to give the bot
/// smoother movement and autopiloting</summary>
public bool DISABLE_AGENT_UPDATE_DUPLICATE_CHECK = true;
/// <summary>If true, currently visible avatars will be stored
/// in dictionaries inside <code>Simulator.ObjectAvatars</code>.
/// If false, a new Avatar or Primitive object will be created
/// each time an object update packet is received</summary>
public bool AVATAR_TRACKING = true;
/// <summary>If true, currently visible avatars will be stored
/// in dictionaries inside <code>Simulator.ObjectPrimitives</code>.
/// If false, a new Avatar or Primitive object will be created
/// each time an object update packet is received</summary>
public bool OBJECT_TRACKING = true;
/// <summary>If true, position and velocity will periodically be
/// interpolated (extrapolated, technically) for objects and
/// avatars that are being tracked by the library. This is
/// necessary to increase the accuracy of speed and position
/// estimates for simulated objects</summary>
public bool USE_INTERPOLATION_TIMER = true;
/// <summary>
/// If true, utilization statistics will be tracked. There is a minor penalty
/// in CPU time for enabling this option.
/// </summary>
public bool TRACK_UTILIZATION = false;
#endregion
#region Parcel Tracking
/// <summary>If true, parcel details will be stored in the
/// <code>Simulator.Parcels</code> dictionary as they are received</summary>
public bool PARCEL_TRACKING = true;
/// <summary>
/// If true, an incoming parcel properties reply will automatically send
/// a request for the parcel access list
/// </summary>
public bool ALWAYS_REQUEST_PARCEL_ACL = true;
/// <summary>
/// if true, an incoming parcel properties reply will automatically send
/// a request for the traffic count.
/// </summary>
public bool ALWAYS_REQUEST_PARCEL_DWELL = true;
#endregion
#region Asset Cache
/// <summary>
/// If true, images, and other assets downloaded from the server
/// will be cached in a local directory
/// </summary>
public bool USE_ASSET_CACHE = true;
/// <summary>Path to store cached texture data</summary>
public string ASSET_CACHE_DIR = RESOURCE_DIR + "/cache";
/// <summary>Maximum size cached files are allowed to take on disk (bytes)</summary>
public long ASSET_CACHE_MAX_SIZE = 1024 * 1024 * 1024; // 1GB
#endregion
#region Misc
/// <summary>Default color used for viewer particle effects</summary>
public Color4 DEFAULT_EFFECT_COLOR = new Color4(255, 0, 0, 255);
/// <summary>Cost of uploading an asset</summary>
/// <remarks>Read-only since this value is dynamically fetched at login</remarks>
public int UPLOAD_COST { get { return priceUpload; } }
/// <summary>Maximum number of times to resend a failed packet</summary>
public int MAX_RESEND_COUNT = 3;
/// <summary>Throttle outgoing packet rate</summary>
public bool THROTTLE_OUTGOING_PACKETS = true;
/// <summary>UUID of a texture used by some viewers to indentify type of client used</summary>
public UUID CLIENT_IDENTIFICATION_TAG = UUID.Zero;
#endregion
#region Texture Pipeline
/// <summary>
/// Download textures using GetTexture capability when available
/// </summary>
public bool USE_HTTP_TEXTURES = true;
/// <summary>The maximum number of concurrent texture downloads allowed</summary>
/// <remarks>Increasing this number will not necessarily increase texture retrieval times due to
/// simulator throttles</remarks>
public int MAX_CONCURRENT_TEXTURE_DOWNLOADS = 4;
/// <summary>
/// The Refresh timer inteval is used to set the delay between checks for stalled texture downloads
/// </summary>
/// <remarks>This is a static variable which applies to all instances</remarks>
public static float PIPELINE_REFRESH_INTERVAL = 500.0f;
/// <summary>
/// Textures taking longer than this value will be flagged as timed out and removed from the pipeline
/// </summary>
public int PIPELINE_REQUEST_TIMEOUT = 45*1000;
#endregion
#region Logging Configuration
/// <summary>
/// Get or set the minimum log level to output to the console by default
///
/// If the library is not compiled with DEBUG defined and this level is set to DEBUG
/// You will get no output on the console. This behavior can be overriden by creating
/// a logger configuration file for log4net
/// </summary>
public static Helpers.LogLevel LOG_LEVEL = Helpers.LogLevel.Debug;
/// <summary>Attach avatar names to log messages</summary>
public bool LOG_NAMES = true;
/// <summary>Log packet retransmission info</summary>
public bool LOG_RESENDS = true;
/// <summary>Log disk cache misses and other info</summary>
public bool LOG_DISKCACHE = true;
#endregion
#region Private Fields
private GridClient Client;
private int priceUpload = 0;
public static bool SORT_INVENTORY = false;
/// <summary>Constructor</summary>
/// <param name="client">Reference to a GridClient object</param>
public Settings(GridClient client)
{
Client = client;
Client.Network.RegisterCallback(Packets.PacketType.EconomyData, EconomyDataHandler);
}
#endregion
#region Packet Callbacks
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void EconomyDataHandler(object sender, PacketReceivedEventArgs e)
{
EconomyDataPacket econ = (EconomyDataPacket)e.Packet;
priceUpload = econ.Info.PriceUpload;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
using FluentNHibernate.Mapping;
using FluentNHibernate.MappingModel.Collections;
using Iesi.Collections.Generic;
using NUnit.Framework;
namespace FluentNHibernate.Testing.DomainModel.Mapping
{
// NOTE TO MAINTAINERS
//
// Most of the tests for many-to-many mapping are still located in the ClassMapXmlCreationTester
// MY ADVICE:
// - Any time you have to ADD a test for many-to-many, add it HERE not THERE
// - Any time you have to MODIFY a test for many-to-many THERE, move it HERE, FIRST.
// Thanks! 10-NOV-2008 Chad Myers
public class ManyToManyTarget
{
public virtual int Id { get; set; }
public virtual ISet<ChildObject> SetOfChildren { get; set; }
public virtual IList<ChildObject> BagOfChildren { get; set; }
public virtual IList<ChildObject> ListOfChildren { get; set; }
public virtual IDictionary<string, ChildObject> MapOfChildren { get; set; }
public virtual ChildObject[] ArrayOfChildren { get; set; }
public virtual IList<string> ListOfSimpleChildren { get; set; }
public virtual CustomCollection<ChildObject> CustomCollection { get; set; }
public virtual IDictionary<ChildObject, ChildObject> GenericTernaryMapOfChildren { get; set; }
public virtual IDictionary<ChildObject, bool> MapOfChildrenToBools{ get; set; }
public virtual IDictionary NonGenericTernaryMapOfChildren { get; set; }
private IList<ChildObject> otherChildren = new List<ChildObject>();
public virtual IList<ChildObject> GetOtherChildren() { return otherChildren; }
}
public class Left
{
public virtual int Id { get; set; }
public virtual IList<Right> Rights { get; set; }
public virtual IList<Right> SecondRights { get; set; }
}
public class Right
{
public virtual int Id { get; set; }
public virtual IList<Left> Lefts { get; set; }
public virtual IList<Left> SecondLefts { get; set; }
public virtual IList<Left> ThirdLefts { get; set; }
}
[TestFixture]
public class ManyToManyTester
{
[Test]
public void ManyToManyMapping_with_private_backing_field()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(m =>
m.HasManyToMany(x => x.GetOtherChildren())
.Access.CamelCaseField())
.Element("class/bag")
.HasAttribute("name", "otherChildren")
.HasAttribute("access", "field.camelcase");
}
[Test]
public void ManyToManyMapping_with_foreign_key_name()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(m => m.HasManyToMany(x => x.GetOtherChildren()).ForeignKeyConstraintNames("FK_Parent", "FK_Child"))
.Element("class/bag/key")
.HasAttribute("foreign-key", "FK_Parent")
.Element("class/bag/many-to-many")
.HasAttribute("foreign-key", "FK_Child");
}
[Test]
public void Can_use_custom_collection_implicitly()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map => map.HasManyToMany(x => x.CustomCollection))
.Element("class/bag").HasAttribute("collection-type", typeof(CustomCollection<ChildObject>).AssemblyQualifiedName);
}
[Test]
public void Can_use_custom_collection_explicitly_generic()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.BagOfChildren)
.CollectionType<CustomCollection<ChildObject>>()
)
.Element("class/bag").HasAttribute("collection-type", typeof(CustomCollection<ChildObject>).AssemblyQualifiedName);
}
[Test]
public void Can_use_custom_collection_explicitly()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.BagOfChildren)
.CollectionType(typeof(CustomCollection<ChildObject>))
)
.Element("class/bag").HasAttribute("collection-type", typeof(CustomCollection<ChildObject>).AssemblyQualifiedName);
}
[Test]
public void Can_use_custom_collection_explicitly_name()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.BagOfChildren)
.CollectionType("name")
)
.Element("class/bag").HasAttribute("collection-type", "name");
}
[Test]
public void CanSpecifyCollectionTypeAsMapWithStringColumnName()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map => map
.HasManyToMany(x => x.MapOfChildren)
.AsMap(null)
.AsSimpleAssociation("Name", "ChildObject")
.ParentKeyColumn("ParentId"))
.Element("class/map/key/column").HasAttribute("name", "ParentId")
.Element("class/map/index/column").HasAttribute("name", "Name")
.Element("class/map/many-to-many").HasAttribute("class", typeof(ChildObject).AssemblyQualifiedName);
}
[Test]
public void NotFound_sets_attribute()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.BagOfChildren)
.NotFound.Ignore())
.Element("class/bag/many-to-many").HasAttribute("not-found", "ignore");
}
[Test]
public void ShouldWriteCacheElementWhenAssigned()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.SetOfChildren)
.Cache.ReadWrite())
.Element("class/set/cache").ShouldNotBeNull();
}
[Test]
public void ShouldNotWriteCacheElementWhenEmpty()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.SetOfChildren))
.Element("class/set/cache").DoesntExist();
}
[Test]
public void ShouldWriteCacheElementFirst()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.SetOfChildren)
.Cache.ReadWrite())
.Element("class/set/cache").ShouldBeInParentAtPosition(0);
}
[Test]
public void ShouldWriteBatchSizeAttributeWhenAssigned()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.SetOfChildren)
.BatchSize(15))
.Element("class/set").HasAttribute("batch-size", "15");
}
[Test]
public void ShouldNotWriteBatchSizeAttributeWhenEmpty()
{
new MappingTester<OneToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.SetOfChildren))
.Element("class/set").DoesntHaveAttribute("batch-size");
}
[Test]
public void ArrayHasIndexElement()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map => map.HasManyToMany(x => x.ArrayOfChildren).AsArray(x => x.Position))
.Element("class/array/index").Exists();
}
[Test]
public void ShouldWriteIndexWhenAssigned()
{
new MappingTester<OneToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.SetOfChildren)
.AsMap("indexColumn"))
.Element("class/map/index").ShouldNotBeNull();
}
[Test]
public void ShouldWriteIndexAtCorrectPosition()
{
new MappingTester<OneToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.SetOfChildren)
.AsMap("indexColumn")
.ParentKeyColumn("ParentID")
.ChildKeyColumn("ChildID")
.Cache.ReadWrite())
.Element("class/map/index").ShouldBeInParentAtPosition(2);
}
[Test]
public void TernaryAssociationShouldWriteIndexManyToManyForGeneric()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.GenericTernaryMapOfChildren)
.AsMap("keyColumn")
.AsTernaryAssociation())
.Element("class/map/index-many-to-many").ShouldBeInParentAtPosition(0 + 1);
}
[Test]
public void TernaryAssociationShouldWriteManyToManyElementForGeneric()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.GenericTernaryMapOfChildren)
.AsMap("keyColumn")
.AsTernaryAssociation())
.Element("class/map/many-to-many").ShouldBeInParentAtPosition(0 + 2);
}
[Test]
public void TernaryAssociationShouldWriteColumnNamesWhenSpecifiedForGeneric()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.GenericTernaryMapOfChildren)
.AsMap("keyColumn")
.AsTernaryAssociation("index1", "index2"))
.Element("class/map/index-many-to-many/column").HasAttribute("name", "index1")
.Element("class/map/many-to-many/column").HasAttribute("name", "index2");
}
[Test]
public void TernaryAssociationShouldWriteIndexManyToManyForNonGeneric()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany<IDictionary>(x => x.NonGenericTernaryMapOfChildren)
.AsMap("keyColumn")
.AsTernaryAssociation(typeof(ChildObject), typeof(ChildObject)))
.Element("class/map/index-many-to-many").ShouldBeInParentAtPosition(0 + 1);
}
[Test]
public void TernaryAssociationShouldWriteManyToManyElementForNonGeneric()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany<IDictionary>(x => x.NonGenericTernaryMapOfChildren)
.AsMap("keyColumn")
.AsTernaryAssociation(typeof(ChildObject), typeof(ChildObject)))
.Element("class/map/many-to-many").ShouldBeInParentAtPosition(0 + 2);
}
[Test]
public void TernaryAssociationShouldWriteColumnNamesWhenSpecifiedForNonGeneric()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany<IDictionary>(x => x.NonGenericTernaryMapOfChildren)
.AsMap("keyColumn")
.AsTernaryAssociation(typeof(ChildObject), "index1", typeof(ChildObject), "index2"))
.Element("class/map/index-many-to-many/column").HasAttribute("name", "index1")
.Element("class/map/many-to-many/column").HasAttribute("name", "index2");
}
[Test]
public void TernaryAssociationCanBeUsedWithElement()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(map =>
map.HasManyToMany(x => x.MapOfChildrenToBools)
.AsMap(null)
.AsTernaryAssociation()
.Element("IsManager", ep => ep.Type<bool>()))
.Element("class/map/index-many-to-many").HasAttribute("class", typeof(ChildObject).AssemblyQualifiedName)
.Element("class/map/element").HasAttribute("type", typeof(bool).AssemblyQualifiedName);
}
[Test]
public void CanSpecifyOrderByClause()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(m => m.HasManyToMany(x => x.BagOfChildren).OrderBy("foo"))
.Element("class/bag").HasAttribute("order-by", "foo");
}
[Test]
public void OrderByClauseIgnoredForUnorderableCollections()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(m => m.HasManyToMany(x => x.MapOfChildren).AsMap("indexCol"))
.Element("class/map").DoesntHaveAttribute("order-by");
}
[Test]
public void CanSpecifyMultipleParentKeyColumns()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(m => m.HasManyToMany(x => x.BagOfChildren)
.ParentKeyColumns.Add("ID1")
.ParentKeyColumns.Add("ID2"))
.Element("class/bag/key/column[@name='ID1']").Exists()
.Element("class/bag/key/column[@name='ID2']").Exists();
}
[Test]
public void CanSpecifyMultipleChildKeyColumns()
{
new MappingTester<ManyToManyTarget>()
.ForMapping(m => m.HasManyToMany(x => x.BagOfChildren)
.ChildKeyColumns.Add("ID1")
.ChildKeyColumns.Add("ID2"))
.Element("class/bag/many-to-many/column[@name='ID1']").Exists()
.Element("class/bag/many-to-many/column[@name='ID2']").Exists();
}
}
}
| |
//
// OAuth framework for TweetStation
//
// Author;
// Miguel de Icaza (miguel@gnome.org)
//
// Possible optimizations:
// Instead of sorting every time, keep things sorted
// Reuse the same dictionary, update the values
//
// Copyright 2010 Miguel de Icaza
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.Security.Cryptography;
using ServiceStack.ServiceModel;
namespace ServiceStack.ServiceInterface.Auth
{
//
// Configuration information for an OAuth client
//
//public class OAuthConfig {
// keys, callbacks
//public string ConsumerKey, Callback, ConsumerSecret;
// Urls
//public string RequestTokenUrl, AccessTokenUrl, AuthorizeUrl;
//}
//
// The authorizer uses a provider and an optional xAuth user/password
// to perform the OAuth authorization process as well as signing
// outgoing http requests
//
// To get an access token, you use these methods in the workflow:
// AcquireRequestToken
// AuthorizeUser
//
// These static methods only require the access token:
// AuthorizeRequest
// AuthorizeTwitPic
//
public class OAuthAuthorizer
{
// Settable by the user
public string xAuthUsername, xAuthPassword;
OAuthProvider provider;
public string RequestToken, RequestTokenSecret;
public string AuthorizationToken, AuthorizationVerifier;
public string AccessToken, AccessTokenSecret;//, AccessScreenName;
//public long AccessId;
public Dictionary<string, string> AuthInfo = new Dictionary<string, string>();
// Constructor for standard OAuth
public OAuthAuthorizer(OAuthProvider provider)
{
this.provider = provider;
}
static Random random = new Random();
static DateTime UnixBaseTime = new DateTime(1970, 1, 1);
// 16-byte lower-case or digit string
static string MakeNonce()
{
var ret = new char[16];
for (int i = 0; i < ret.Length; i++)
{
int n = random.Next(35);
if (n < 10)
ret[i] = (char)(n + '0');
else
ret[i] = (char)(n - 10 + 'a');
}
return new string(ret);
}
static string MakeTimestamp()
{
return ((long)(DateTime.UtcNow - UnixBaseTime).TotalSeconds).ToString();
}
// Makes an OAuth signature out of the HTTP method, the base URI and the headers
static string MakeSignature(string method, string base_uri, Dictionary<string, string> headers)
{
var items = from k in headers.Keys
orderby k
select k + "%3D" + OAuthUtils.PercentEncode(headers[k]);
return method + "&" + OAuthUtils.PercentEncode(base_uri) + "&" +
string.Join("%26", items.ToArray());
}
static string MakeSigningKey(string consumerSecret, string oauthTokenSecret)
{
return OAuthUtils.PercentEncode(consumerSecret) + "&" + (oauthTokenSecret != null ? OAuthUtils.PercentEncode(oauthTokenSecret) : "");
}
static string MakeOAuthSignature(string compositeSigningKey, string signatureBase)
{
var sha1 = new HMACSHA1(Encoding.UTF8.GetBytes(compositeSigningKey));
return Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBase)));
}
static string HeadersToOAuth(Dictionary<string, string> headers)
{
return "OAuth " + String.Join(",", (from x in headers.Keys select String.Format("{0}=\"{1}\"", x, headers[x])).ToArray());
}
public bool AcquireRequestToken()
{
var headers = new Dictionary<string, string>() {
{ "oauth_callback", OAuthUtils.PercentEncode (provider.CallbackUrl) },
{ "oauth_consumer_key", provider.ConsumerKey },
{ "oauth_nonce", MakeNonce () },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp () },
{ "oauth_version", "1.0" }};
var uri = new Uri(provider.RequestTokenUrl);
var signatureHeaders = new Dictionary<string, string>(headers);
var nvc = HttpUtility.ParseQueryString(uri.Query);
foreach (string key in nvc)
{
if (key != null)
signatureHeaders.Add(key, OAuthUtils.PercentEncode(nvc[key]));
}
string signature = MakeSignature("POST", uri.GetLeftPart(UriPartial.Path), signatureHeaders);
string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, null);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
var wc = new WebClient();
headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
wc.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers);
try
{
var result = HttpUtility.ParseQueryString(wc.UploadString(new Uri(provider.RequestTokenUrl), ""));
if (result["oauth_callback_confirmed"] != null)
{
RequestToken = result["oauth_token"];
RequestTokenSecret = result["oauth_token_secret"];
return true;
}
}
catch (Exception e)
{
Console.WriteLine(e);
// fallthrough for errors
}
return false;
}
// Invoked after the user has authorized us
//
// TODO: this should return the stream error for invalid passwords instead of
// just true/false.
public bool AcquireAccessToken()
{
var headers = new Dictionary<string, string>() {
{ "oauth_consumer_key", provider.ConsumerKey },
{ "oauth_nonce", MakeNonce () },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp () },
{ "oauth_version", "1.0" }};
var content = "";
if (xAuthUsername == null)
{
headers.Add("oauth_token", OAuthUtils.PercentEncode(AuthorizationToken));
headers.Add("oauth_verifier", OAuthUtils.PercentEncode(AuthorizationVerifier));
}
else
{
headers.Add("x_auth_username", OAuthUtils.PercentEncode(xAuthUsername));
headers.Add("x_auth_password", OAuthUtils.PercentEncode(xAuthPassword));
headers.Add("x_auth_mode", "client_auth");
content = String.Format("x_auth_mode=client_auth&x_auth_password={0}&x_auth_username={1}", OAuthUtils.PercentEncode(xAuthPassword), OAuthUtils.PercentEncode(xAuthUsername));
}
string signature = MakeSignature("POST", provider.AccessTokenUrl, headers);
string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, RequestTokenSecret);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
var wc = new WebClient();
headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
if (xAuthUsername != null)
{
headers.Remove("x_auth_username");
headers.Remove("x_auth_password");
headers.Remove("x_auth_mode");
}
wc.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers);
try
{
var result = HttpUtility.ParseQueryString(wc.UploadString(new Uri(provider.AccessTokenUrl), content));
if (result["oauth_token"] != null)
{
AccessToken = result["oauth_token"];
AccessTokenSecret = result["oauth_token_secret"];
AuthInfo = result.ToDictionary();
return true;
}
}
catch (WebException e)
{
var x = e.Response.GetResponseStream();
var j = new System.IO.StreamReader(x);
Console.WriteLine(j.ReadToEnd());
Console.WriteLine(e);
// fallthrough for errors
}
return false;
}
//
// Assign the result to the Authorization header, like this:
// request.Headers [HttpRequestHeader.Authorization] = AuthorizeRequest (...)
//
public static string AuthorizeRequest(OAuthProvider provider, string oauthToken, string oauthTokenSecret, string method, Uri uri, string data)
{
var headers = new Dictionary<string, string>() {
{ "oauth_consumer_key", provider.ConsumerKey },
{ "oauth_nonce", MakeNonce () },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp () },
{ "oauth_token", oauthToken },
{ "oauth_version", "1.0" }};
var signatureHeaders = new Dictionary<string, string>(headers);
// Add the data and URL query string to the copy of the headers for computing the signature
if (data != null && data != "")
{
var parsed = HttpUtility.ParseQueryString(data);
foreach (string k in parsed.Keys)
{
signatureHeaders.Add(k, OAuthUtils.PercentEncode(parsed[k]));
}
}
var nvc = HttpUtility.ParseQueryString(uri.Query);
foreach (string key in nvc)
{
if (key != null)
signatureHeaders.Add(key, OAuthUtils.PercentEncode(nvc[key]));
}
string signature = MakeSignature(method, uri.GetLeftPart(UriPartial.Path), signatureHeaders);
string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, oauthTokenSecret);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
return HeadersToOAuth(headers);
}
//
// Used to authorize an HTTP request going to TwitPic
//
public static void AuthorizeTwitPic(OAuthProvider provider, HttpWebRequest wc, string oauthToken, string oauthTokenSecret)
{
var headers = new Dictionary<string, string>() {
{ "oauth_consumer_key", provider.ConsumerKey },
{ "oauth_nonce", MakeNonce () },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp () },
{ "oauth_token", oauthToken },
{ "oauth_version", "1.0" },
//{ "realm", "http://api.twitter.com" }
};
string signurl = "http://api.twitter.com/1/account/verify_credentials.xml";
// The signature is not done against the *actual* url, it is done against the verify_credentials.json one
string signature = MakeSignature("GET", signurl, headers);
string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, oauthTokenSecret);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
//Util.Log ("Headers: " + HeadersToOAuth (headers));
wc.Headers.Add("X-Verify-Credentials-Authorization", HeadersToOAuth(headers));
wc.Headers.Add("X-Auth-Service-Provider", signurl);
}
}
public static class OAuthUtils
{
//
// This url encoder is different than regular Url encoding found in .NET
// as it is used to compute the signature based on a url. Every document
// on the web omits this little detail leading to wasting everyone's time.
//
// This has got to be one of the lamest specs and requirements ever produced
//
public static string PercentEncode(string s)
{
var sb = new StringBuilder();
foreach (byte c in Encoding.UTF8.GetBytes(s))
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~')
sb.Append((char)c);
else
{
sb.AppendFormat("%{0:X2}", c);
}
}
return sb.ToString();
}
}
}
| |
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright 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 Facebook.Unity
{
using Facebook.Unity.Mobile.Android;
using UnityEngine;
internal static class FacebookLogger
{
private const string UnityAndroidTag = "Facebook.Unity.FBDebug";
static FacebookLogger()
{
FacebookLogger.Instance = new CustomLogger();
}
internal static IFacebookLogger Instance { private get; set; }
public static void Log(string msg)
{
FacebookLogger.Instance.Log(msg);
}
public static void Log(string format, params string[] args)
{
FacebookLogger.Log(string.Format(format, args));
}
public static void Info(string msg)
{
FacebookLogger.Instance.Info(msg);
}
public static void Info(string format, params string[] args)
{
FacebookLogger.Info(string.Format(format, args));
}
public static void Warn(string msg)
{
FacebookLogger.Instance.Warn(msg);
}
public static void Warn(string format, params string[] args)
{
FacebookLogger.Warn(string.Format(format, args));
}
public static void Error(string msg)
{
FacebookLogger.Instance.Error(msg);
}
public static void Error(string format, params string[] args)
{
FacebookLogger.Error(string.Format(format, args));
}
private class CustomLogger : IFacebookLogger
{
private IFacebookLogger logger;
public CustomLogger()
{
#if UNITY_EDITOR
this.logger = new EditorLogger();
#elif UNITY_ANDROID
this.logger = new AndroidLogger();
#elif UNITY_IOS
this.logger = new IOSLogger();
#else
this.logger = new CanvasLogger();
#endif
}
public void Log(string msg)
{
if (Debug.isDebugBuild)
{
Debug.Log(msg);
this.logger.Log(msg);
}
}
public void Info(string msg)
{
Debug.Log(msg);
this.logger.Info(msg);
}
public void Warn(string msg)
{
Debug.LogWarning(msg);
this.logger.Warn(msg);
}
public void Error(string msg)
{
Debug.LogError(msg);
this.logger.Error(msg);
}
}
#if UNITY_EDITOR
private class EditorLogger : IFacebookLogger
{
public void Log(string msg)
{
}
public void Info(string msg)
{
}
public void Warn(string msg)
{
}
public void Error(string msg)
{
}
}
#elif UNITY_ANDROID
private class AndroidLogger : IFacebookLogger
{
public void Log(string msg)
{
using (AndroidJavaClass androidLogger = new AndroidJavaClass("android.util.Log"))
{
androidLogger.CallStatic<int>("v", UnityAndroidTag, msg);
}
}
public void Info(string msg)
{
using (AndroidJavaClass androidLogger = new AndroidJavaClass("android.util.Log"))
{
androidLogger.CallStatic<int>("i", UnityAndroidTag, msg);
}
}
public void Warn(string msg)
{
using (AndroidJavaClass androidLogger = new AndroidJavaClass("android.util.Log"))
{
androidLogger.CallStatic<int>("w", UnityAndroidTag, msg);
}
}
public void Error(string msg)
{
using (AndroidJavaClass androidLogger = new AndroidJavaClass("android.util.Log"))
{
androidLogger.CallStatic<int>("e", UnityAndroidTag, msg);
}
}
}
#elif UNITY_IOS
private class IOSLogger: IFacebookLogger
{
public void Log(string msg)
{
// TODO
}
public void Info(string msg)
{
// TODO
}
public void Warn(string msg)
{
// TODO
}
public void Error(string msg)
{
// TODO
}
}
#else
private class CanvasLogger : IFacebookLogger
{
public void Log(string msg)
{
Application.ExternalCall("console.log", msg);
}
public void Info(string msg)
{
Application.ExternalCall("console.info", msg);
}
public void Warn(string msg)
{
Application.ExternalCall("console.warn", msg);
}
public void Error(string msg)
{
Application.ExternalCall("console.error", msg);
}
}
#endif
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Index;
using IndexReader = Lucene.Net.Index.IndexReader;
namespace Lucene.Net.Search
{
/// <summary> A query that wraps a filter and simply returns a constant score equal to the
/// query boost for every document in the filter.
/// </summary>
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
public class ConstantScoreQuery:Query
{
protected internal Filter internalFilter;
public ConstantScoreQuery(Filter filter)
{
this.internalFilter = filter;
}
/// <summary>Returns the encapsulated filter </summary>
public virtual Filter Filter
{
get { return internalFilter; }
}
public override Query Rewrite(IndexReader reader)
{
return this;
}
public override void ExtractTerms(System.Collections.Generic.ISet<Term> terms)
{
// OK to not add any terms when used for MultiSearcher,
// but may not be OK for highlighting
}
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
protected internal class ConstantWeight:Weight
{
private void InitBlock(ConstantScoreQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private ConstantScoreQuery enclosingInstance;
public ConstantScoreQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private readonly Similarity similarity;
private float queryNorm;
private float queryWeight;
public ConstantWeight(ConstantScoreQuery enclosingInstance, Searcher searcher)
{
InitBlock(enclosingInstance);
this.similarity = Enclosing_Instance.GetSimilarity(searcher);
}
public override Query Query
{
get { return Enclosing_Instance; }
}
public override float Value
{
get { return queryWeight; }
}
public override float GetSumOfSquaredWeights()
{
queryWeight = Enclosing_Instance.Boost;
return queryWeight*queryWeight;
}
public override void Normalize(float norm)
{
this.queryNorm = norm;
queryWeight *= this.queryNorm;
}
public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer)
{
return new ConstantScorer(enclosingInstance, similarity, reader, this);
}
public override Explanation Explain(IndexReader reader, int doc)
{
var cs = new ConstantScorer(enclosingInstance, similarity, reader, this);
bool exists = cs.docIdSetIterator.Advance(doc) == doc;
var result = new ComplexExplanation();
if (exists)
{
result.Description = "ConstantScoreQuery(" + Enclosing_Instance.internalFilter + "), product of:";
result.Value = queryWeight;
System.Boolean tempAux = true;
result.Match = tempAux;
result.AddDetail(new Explanation(Enclosing_Instance.Boost, "boost"));
result.AddDetail(new Explanation(queryNorm, "queryNorm"));
}
else
{
result.Description = "ConstantScoreQuery(" + Enclosing_Instance.internalFilter + ") doesn't match id " + doc;
result.Value = 0;
System.Boolean tempAux2 = false;
result.Match = tempAux2;
}
return result;
}
}
protected internal class ConstantScorer : Scorer
{
private void InitBlock(ConstantScoreQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private ConstantScoreQuery enclosingInstance;
public ConstantScoreQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal DocIdSetIterator docIdSetIterator;
internal float theScore;
internal int doc = - 1;
public ConstantScorer(ConstantScoreQuery enclosingInstance, Similarity similarity, IndexReader reader, Weight w):base(similarity)
{
InitBlock(enclosingInstance);
theScore = w.Value;
DocIdSet docIdSet = Enclosing_Instance.internalFilter.GetDocIdSet(reader);
if (docIdSet == null)
{
docIdSetIterator = DocIdSet.EMPTY_DOCIDSET.Iterator();
}
else
{
DocIdSetIterator iter = docIdSet.Iterator();
if (iter == null)
{
docIdSetIterator = DocIdSet.EMPTY_DOCIDSET.Iterator();
}
else
{
docIdSetIterator = iter;
}
}
}
public override int NextDoc()
{
return docIdSetIterator.NextDoc();
}
public override int DocID()
{
return docIdSetIterator.DocID();
}
public override float Score()
{
return theScore;
}
public override int Advance(int target)
{
return docIdSetIterator.Advance(target);
}
}
public override Weight CreateWeight(Searcher searcher)
{
return new ConstantScoreQuery.ConstantWeight(this, searcher);
}
/// <summary>Prints a user-readable version of this query. </summary>
public override System.String ToString(string field)
{
return "ConstantScore(" + internalFilter + (Boost == 1.0?")":"^" + Boost);
}
/// <summary>Returns true if <c>o</c> is equal to this. </summary>
public override bool Equals(System.Object o)
{
if (this == o)
return true;
if (!(o is ConstantScoreQuery))
return false;
ConstantScoreQuery other = (ConstantScoreQuery) o;
return this.Boost == other.Boost && internalFilter.Equals(other.internalFilter);
}
/// <summary>Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
// Simple add is OK since no existing filter hashcode has a float component.
return internalFilter.GetHashCode() + BitConverter.ToInt32(BitConverter.GetBytes(Boost), 0);
}
override public System.Object Clone()
{
// {{Aroush-1.9}} is this all that we need to clone?!
ConstantScoreQuery clone = (ConstantScoreQuery)base.Clone();
clone.internalFilter = (Filter)this.internalFilter;
return clone;
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Xml;
using System.Text;
using OpenSource.UPnP;
using System.Reflection;
using System.Collections;
using OpenSource.Utilities;
using System.Runtime.Serialization;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// Class can represent any ContentDirectory approved
/// upnp or dublin-core metadata elements that are
/// simple ulong values without any attributes.
/// </summary>
[Serializable()]
public sealed class PropertyULong : ICdsElement, IToXmlData, IDeserializationCallback
{
/// <summary>
/// Returns same value as StringValue
/// </summary>
/// <returns></returns>
public override string ToString() { return this.StringValue; }
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public static IList GetPossibleAttributes()
{
return new object[0];
}
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public IList PossibleAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public IList ValidAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// No attributes, so always returns null
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public IComparable ExtractAttribute(string attribute) { return null; }
/// <summary>
/// Returns the underlying ulong value.
/// </summary>
public IComparable ComparableValue { get { return m_value; } }
/// <summary>
/// Returns the underlying ulong value.
/// </summary>
public object Value { get { return m_value; } }
/// <summary>
/// Returns the string representation of the ulong value.
/// </summary>
public string StringValue { get { return m_value.ToString(); } }
/// <summary>
/// Prints the XML representation of the metadata element.
/// <para>
/// Implementation calls the <see cref="ToXmlData.ToXml"/>
/// method for its implementation.
/// </para>
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
/// <exception cref="InvalidCastException">
/// Thrown if the "data" argument is not a <see cref="ToXmlData"/> object.
/// </exception>
public void ToXml (ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
ToXmlData.ToXml(this, formatter, (ToXmlData) data, xmlWriter);
}
/// <summary>
/// Instructs the "xmlWriter" argument to start the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void StartElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteStartElement(this.ns_tag);
}
/// <summary>
/// Instructs the "xmlWriter" argument to write the value of
/// the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void WriteValue(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteString(this.StringValue);
}
/// <summary>
/// Instructs the "xmlWriter" argument to close the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void EndElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteEndElement();
}
/// <summary>
/// Empty - this element has no child xml elements.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void WriteInnerXml(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
}
/// <summary>
/// Attempts to case compareToThis as an ulong
/// to do the comparison. If the cast
/// fails, then it compares the current
/// value against ulong.MinValue.
/// </summary>
/// <param name="compareToThis"></param>
/// <returns></returns>
public int CompareTo (object compareToThis)
{
System.Type type = compareToThis.GetType();
ulong compareTo = ulong.MinValue;
try
{
if (type == typeof(PropertyULong))
{
compareTo = ((PropertyULong)compareToThis).m_value;
}
else if (type == typeof(string))
{
compareTo = ulong.Parse(compareToThis.ToString());
}
else
{
compareTo = (ulong) compareToThis;
}
}
catch
{
compareTo = ulong.MinValue;
}
return this.m_value.CompareTo(compareTo);
}
/// <summary>
/// Extracts the Name of the element and uses
/// the InnerText as the value.
/// </summary>
/// <param name="element"></param>
public PropertyULong(XmlElement element)
{
this.m_value = ulong.Parse(element.InnerText);
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(element.Name);
}
/// <summary>
/// Instantiates a new property that can represent an xml element with
/// an ulong as its value.
/// </summary>
/// <param name="namespace_tag">property obtained from Tags[CommonPropertyNames.value]</param>
/// <param name="val"></param>
public PropertyULong (string namespace_tag, ulong val)
{
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(namespace_tag);
this.m_value = val;
}
/// <summary>
/// Assume the name has been read.
/// </summary>
/// <param name="reader"></param>
public PropertyULong(XmlReader reader)
{
this.m_value = XmlConvert.ToUInt64(reader.Value);
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(reader.Name);
}
/// <summary>
/// Underlying ulong value.
/// </summary>
public ulong _Value { get { return this.m_value; } }
internal ulong m_value;
/// <summary>
/// the namespace and element name to represent
/// </summary>
private string ns_tag;
public void OnDeserialization(object sender)
{
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(this.ns_tag);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public class HtmlHelperTest
{
public static TheoryData<object, KeyValuePair<string, object>> IgnoreCaseTestData
{
get
{
return new TheoryData<object, KeyValuePair<string, object>>
{
{
new
{
selected = true,
SeLeCtEd = false
},
new KeyValuePair<string, object>("selected", false)
},
{
new
{
SeLeCtEd = false,
selected = true
},
new KeyValuePair<string, object>("SeLeCtEd", true)
},
{
new
{
SelECTeD = false,
SeLECTED = true
},
new KeyValuePair<string, object>("SelECTeD", true)
}
};
}
}
// value, expectedString
public static TheoryData<object, string> EncodeDynamicTestData
{
get
{
var data = new TheoryData<object, string>
{
{ null, string.Empty },
// Dynamic implementation calls the string overload when possible.
{ string.Empty, string.Empty },
{ "<\">", "HtmlEncode[[<\">]]" },
{ "<br />", "HtmlEncode[[<br />]]" },
{ "<b>bold</b>", "HtmlEncode[[<b>bold</b>]]" },
{ new ObjectWithToStringOverride(), "HtmlEncode[[<b>boldFromObject</b>]]" },
};
return data;
}
}
// value, expectedString
public static TheoryData<object, string> EncodeObjectTestData
{
get
{
var data = new TheoryData<object, string>
{
{ null, string.Empty },
{ string.Empty, string.Empty },
{ "<\">", "HtmlEncode[[<\">]]" },
{ "<br />", "HtmlEncode[[<br />]]" },
{ "<b>bold</b>", "HtmlEncode[[<b>bold</b>]]" },
{ new ObjectWithToStringOverride(), "HtmlEncode[[<b>boldFromObject</b>]]" },
};
return data;
}
}
// value, expectedString
public static TheoryData<string, string> EncodeStringTestData
{
get
{
return new TheoryData<string, string>
{
{ null, string.Empty },
// String overload does not encode the empty string.
{ string.Empty, string.Empty },
{ "<\">", "HtmlEncode[[<\">]]" },
{ "<br />", "HtmlEncode[[<br />]]" },
{ "<b>bold</b>", "HtmlEncode[[<b>bold</b>]]" },
};
}
}
// value, expectedString
public static TheoryData<object, string> RawObjectTestData
{
get
{
var data = new TheoryData<object, string>
{
{ new ObjectWithToStringOverride(), "<b>boldFromObject</b>" },
};
foreach (var item in RawStringTestData)
{
data.Add(item[0], (string)item[1]);
}
return data;
}
}
// value, expectedString
public static TheoryData<string, string> RawStringTestData
{
get
{
return new TheoryData<string, string>
{
{ null, string.Empty },
{ string.Empty, string.Empty },
{ "<\">", "<\">" },
{ "<br />", "<br />" },
{ "<b>bold</b>", "<b>bold</b>" },
};
}
}
[Theory]
[MemberData(nameof(IgnoreCaseTestData))]
public void AnonymousObjectToHtmlAttributes_IgnoresPropertyCase(
object htmlAttributeObject,
KeyValuePair<string, object> expectedEntry)
{
// Act
var result = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributeObject);
// Assert
var entry = Assert.Single(result);
Assert.Equal(expectedEntry, entry);
}
[Theory]
[MemberData(nameof(EncodeDynamicTestData))]
public void EncodeDynamic_ReturnsExpectedString(object value, string expectedString)
{
// Arrange
// Important to preserve these particular variable types. Otherwise may end up testing different runtime
// (not compiler) behaviors.
dynamic dynamicValue = value;
IHtmlHelper<DefaultTemplatesUtilities.ObjectTemplateModel> helper =
DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Encode(dynamicValue);
// Assert
Assert.Equal(expectedString, result);
}
[Theory]
[MemberData(nameof(EncodeDynamicTestData))]
public void EncodeDynamic_ReturnsExpectedString_WithBaseHelper(object value, string expectedString)
{
// Arrange
// Important to preserve these particular variable types. Otherwise may end up testing different runtime
// (not compiler) behaviors.
dynamic dynamicValue = value;
IHtmlHelper helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Encode(dynamicValue);
// Assert
Assert.Equal(expectedString, result);
}
[Theory]
[MemberData(nameof(EncodeObjectTestData))]
public void EncodeObject_ReturnsExpectedString(object value, string expectedString)
{
// Arrange
// Important to preserve this particular variable type and the (object) type of the value parameter.
// Otherwise may end up testing different runtime (not compiler) behaviors.
IHtmlHelper<DefaultTemplatesUtilities.ObjectTemplateModel> helper =
DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Encode(value);
// Assert
Assert.Equal(expectedString, result);
}
[Theory]
[MemberData(nameof(EncodeStringTestData))]
public void EncodeString_ReturnsExpectedString(string value, string expectedString)
{
// Arrange
// Important to preserve this particular variable type and the (string) type of the value parameter.
// Otherwise may end up testing different runtime (not compiler) behaviors.
IHtmlHelper<DefaultTemplatesUtilities.ObjectTemplateModel> helper =
DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Encode(value);
// Assert
Assert.Equal(expectedString, result);
}
[Theory]
[MemberData(nameof(RawObjectTestData))]
public void RawDynamic_ReturnsExpectedString(object value, string expectedString)
{
// Arrange
// Important to preserve these particular variable types. Otherwise may end up testing different runtime
// (not compiler) behaviors.
dynamic dynamicValue = value;
IHtmlHelper<DefaultTemplatesUtilities.ObjectTemplateModel> helper =
DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Raw(dynamicValue);
// Assert
Assert.Equal(expectedString, result.ToString());
}
[Theory]
[MemberData(nameof(RawObjectTestData))]
public void RawDynamic_ReturnsExpectedString_WithBaseHelper(object value, string expectedString)
{
// Arrange
// Important to preserve these particular variable types. Otherwise may end up testing different runtime
// (not compiler) behaviors.
dynamic dynamicValue = value;
IHtmlHelper helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Raw(dynamicValue);
// Assert
Assert.Equal(expectedString, result.ToString());
}
[Theory]
[MemberData(nameof(RawObjectTestData))]
public void RawObject_ReturnsExpectedString(object value, string expectedString)
{
// Arrange
// Important to preserve this particular variable type and the (object) type of the value parameter.
// Otherwise may end up testing different runtime (not compiler) behaviors.
IHtmlHelper<DefaultTemplatesUtilities.ObjectTemplateModel> helper =
DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Raw(value);
// Assert
Assert.Equal(expectedString, result.ToString());
}
[Theory]
[MemberData(nameof(RawStringTestData))]
public void RawString_ReturnsExpectedString(string value, string expectedString)
{
// Arrange
// Important to preserve this particular variable type and the (string) type of the value parameter.
// Otherwise may end up testing different runtime (not compiler) behaviors.
IHtmlHelper<DefaultTemplatesUtilities.ObjectTemplateModel> helper =
DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.Raw(value);
// Assert
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public void Contextualize_WorksWithCovariantViewDataDictionary()
{
// Arrange
var helperToContextualize = DefaultTemplatesUtilities
.GetHtmlHelper<BaseModel>(model: null);
var viewContext = DefaultTemplatesUtilities
.GetHtmlHelper<DerivedModel>(model: null)
.ViewContext;
// Act
helperToContextualize.Contextualize(viewContext);
// Assert
Assert.IsType<ViewDataDictionary<BaseModel>>(
helperToContextualize.ViewData);
Assert.Same(helperToContextualize.ViewContext, viewContext);
}
[Fact]
public void Contextualize_ThrowsIfViewDataDictionariesAreNotCompatible()
{
// Arrange
var helperToContextualize = DefaultTemplatesUtilities
.GetHtmlHelper<BaseModel>(model: null);
var viewContext = DefaultTemplatesUtilities
.GetHtmlHelper<NonDerivedModel>(model: null)
.ViewContext;
var expectedMessage = $"Property '{nameof(ViewContext.ViewData)}' is of type " +
$"'{typeof(ViewDataDictionary<NonDerivedModel>).FullName}'," +
$" but this method requires a value of type '{typeof(ViewDataDictionary<BaseModel>).FullName}'.";
// Act & Assert
var exception = Assert.Throws<ArgumentException>("viewContext", () => helperToContextualize.Contextualize(viewContext));
Assert.Contains(expectedMessage, exception.Message);
}
[Fact]
public void Contextualize_ThrowsForNonGenericViewDataDictionaries()
{
// Arrange
var helperToContextualize = DefaultTemplatesUtilities
.GetHtmlHelper<BaseModel>(model: null);
var viewContext = DefaultTemplatesUtilities
.GetHtmlHelper<BaseModel>(model: null)
.ViewContext;
viewContext.ViewData = new ViewDataDictionary(viewContext.ViewData);
var expectedMessage = $"Property '{nameof(ViewContext.ViewData)}' is of type " +
$"'{typeof(ViewDataDictionary).FullName}'," +
$" but this method requires a value of type '{typeof(ViewDataDictionary<BaseModel>).FullName}'.";
// Act & Assert
var exception = Assert.Throws<ArgumentException>("viewContext", () => helperToContextualize.Contextualize(viewContext));
Assert.Contains(expectedMessage, exception.Message);
}
private class BaseModel
{
public string Name { get; set; }
}
private class DerivedModel : BaseModel
{
}
private class NonDerivedModel
{
}
[Theory]
[InlineData("SomeName", "SomeName")]
[InlineData("Obj1.Prop1", "Obj1_Prop1")]
[InlineData("Obj1.Prop1[0]", "Obj1_Prop1_0_")]
[InlineData("Obj1.Prop1[0].Prop2", "Obj1_Prop1_0__Prop2")]
public void GenerateIdFromName_ReturnsExpectedValues(string fullname, string expected)
{
// Arrange
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.GenerateIdFromName(fullname);
// Assert
Assert.Equal(expected, result);
}
[Theory]
[InlineData(FormMethod.Get, "get")]
[InlineData(FormMethod.Post, "post")]
[InlineData((FormMethod)42, "post")]
public void GetFormMethodString_ReturnsExpectedValues(FormMethod method, string expected)
{
// Act
var result = HtmlHelper.GetFormMethodString(method);
// Assert
Assert.Equal(expected, result);
}
[Theory]
[InlineData("-{0}-", "-<b>boldFromObject</b>-")]
[InlineData("-%{0}%-", "-%<b>boldFromObject</b>%-")]
[InlineData("-=={0}=={0}==-", "-==<b>boldFromObject</b>==<b>boldFromObject</b>==-")]
public void FormatValue_ReturnsExpectedValues(string format, string expected)
{
// Arrange
var value = new ObjectWithToStringOverride();
var helper = DefaultTemplatesUtilities.GetHtmlHelper();
// Act
var result = helper.FormatValue(value, format);
// Assert
Assert.Equal(expected, result);
}
private class ObjectWithToStringOverride
{
public override string ToString()
{
return "<b>boldFromObject</b>";
}
}
}
}
| |
// Copyright (c) 2013-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using System.Collections.Generic;
using SharpNav.Geometry;
#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif
namespace SharpNav
{
/// <summary>
/// The class of Poly mesh.
/// </summary>
public class PolyMesh
{
public const int NullId = -1;
private const int DiagonalFlag = unchecked((int)0x80000000);
private const int NeighborEdgeFlag = unchecked((int)0x80000000);
private PolyVertex[] vertices;
private Polygon[] polygons;
private int numVertsPerPoly;
//copied data from CompactHeightfield
private BBox3 bounds;
private float cellSize;
private float cellHeight;
private int borderSize;
//HACK borderSize is 0 here. Fix with borderSize.
/// <summary>
/// Initializes a new instance of the <see cref="PolyMesh"/> class.
/// </summary>
/// <param name="contSet">The <see cref="ContourSet"/> to generate polygons from.</param>
/// <param name="settings">The settings to build with.</param>
public PolyMesh(ContourSet contSet, NavMeshGenerationSettings settings)
: this(contSet, settings.CellSize, settings.CellHeight, 0, settings.VertsPerPoly)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PolyMesh"/> class by creating polygons from contours.
/// </summary>
/// <param name="contSet">The <see cref="ContourSet"/> to generate polygons from.</param>
/// <param name="cellSize">The size of one voxel/cell.</param>
/// <param name="cellHeight">The height of one voxel/cell.</param>
/// <param name="borderSize">The size of the border around the mesh.</param>
/// <param name="numVertsPerPoly">The maximum number of vertices per polygon.</param>
public PolyMesh(ContourSet contSet, float cellSize, float cellHeight, int borderSize, int numVertsPerPoly)
{
//copy contour data
this.bounds = contSet.Bounds;
this.cellSize = cellSize;
this.cellHeight = cellHeight;
this.borderSize = borderSize;
//get maximum limits
//TODO move to ContourSet?
int maxVertices = 0;
int maxTris = 0;
int maxVertsPerCont = 0;
foreach (var cont in contSet)
{
int vertCount = cont.Vertices.Length;
//skip null contours
if (vertCount < 3)
continue;
maxVertices += vertCount;
maxTris += vertCount - 2;
maxVertsPerCont = Math.Max(maxVertsPerCont, vertCount);
}
//initialize the mesh members
var verts = new List<PolyVertex>(maxVertices);
var polys = new List<Polygon>(maxTris);
Queue<int> vertRemoveQueue = new Queue<int>(maxVertices);
this.numVertsPerPoly = numVertsPerPoly;
var vertDict = new Dictionary<PolyVertex, int>(new PolyVertex.RoughYEqualityComparer(2));
int[] indices = new int[maxVertsPerCont]; //keep track of vertex hash codes
Triangle[] tris = new Triangle[maxVertsPerCont];
List<Polygon> contPolys = new List<Polygon>(maxVertsPerCont + 1);
//extract contour data
foreach (Contour cont in contSet)
{
//skip null contours
if (cont.IsNull)
continue;
PolyVertex[] vertices = new PolyVertex[cont.Vertices.Length];
//triangulate contours
for (int i = 0; i < cont.Vertices.Length; i++)
{
var cv = cont.Vertices[i];
vertices[i] = new PolyVertex(cv.X, cv.Y, cv.Z);
indices[i] = i;
}
//Form triangles inside the area bounded by the contours
int ntris = Triangulate(vertices, indices, tris);
if (ntris <= 0) //TODO notify user when this happens. Logging?
ntris = -ntris;
//add and merge vertices
for (int i = 0; i < cont.Vertices.Length; i++)
{
var cv = cont.Vertices[i];
var pv = vertices[i];
//save the hash code for each vertex
indices[i] = AddVertex(vertDict, pv, verts);
if (RegionId.HasFlags(cv.RegionId, RegionFlags.VertexBorder))
{
//the vertex should be removed
vertRemoveQueue.Enqueue(indices[i]);
}
}
contPolys.Clear();
//iterate through all the triangles
for (int i = 0; i < ntris; i++)
{
Triangle ti = tris[i];
//make sure there are three distinct vertices. anything less can't be a polygon.
if (ti.Index0 == ti.Index1
|| ti.Index0 == ti.Index2
|| ti.Index1 == ti.Index2)
continue;
//each polygon has numVertsPerPoly
//index 0, 1, 2 store triangle vertices
//other polygon indexes (3 to numVertsPerPoly - 1) should be used for storing extra vertices when two polygons merge together
Polygon p = new Polygon(numVertsPerPoly, Area.Null, RegionId.Null, 0);
p.Vertices[0] = RemoveDiagonalFlag(indices[ti.Index0]);
p.Vertices[1] = RemoveDiagonalFlag(indices[ti.Index1]);
p.Vertices[2] = RemoveDiagonalFlag(indices[ti.Index2]);
contPolys.Add(p);
}
//no polygons generated, so skip
if (contPolys.Count == 0)
continue;
//merge polygons
if (numVertsPerPoly > 3)
{
while (true)
{
//find best polygons
int bestMergeVal = 0;
int bestPolyA = 0, bestPolyB = 0, bestEdgeA = 0, bestEdgeB = 0;
for (int i = 0; i < contPolys.Count - 1; i++)
{
int pj = i;
for (int j = i + 1; j < contPolys.Count; j++)
{
int pk = j;
int ea = 0, eb = 0;
int v = GetPolyMergeValue(contPolys, pj, pk, verts, out ea, out eb);
if (v > bestMergeVal)
{
bestMergeVal = v;
bestPolyA = i;
bestPolyB = j;
bestEdgeA = ea;
bestEdgeB = eb;
}
}
}
if (bestMergeVal > 0)
{
int pa = bestPolyA;
int pb = bestPolyB;
MergePolys(contPolys, pa, pb, bestEdgeA, bestEdgeB);
contPolys[pb] = contPolys[contPolys.Count - 1];
contPolys.RemoveAt(contPolys.Count - 1);
}
else
{
//no more merging
break;
}
}
}
//store polygons
for (int i = 0; i < contPolys.Count; i++)
{
Polygon p = contPolys[i];
Polygon p2 = new Polygon(numVertsPerPoly, cont.Area, cont.RegionId, 0);
Buffer.BlockCopy(p.Vertices, 0, p2.Vertices, 0, numVertsPerPoly * sizeof(int));
polys.Add(p2);
}
}
//remove edge vertices
while (vertRemoveQueue.Count > 0)
{
int i = vertRemoveQueue.Dequeue();
if (CanRemoveVertex(polys, i))
RemoveVertex(verts, polys, i);
}
//calculate adjacency (edges)
BuildMeshAdjacency(verts, polys, numVertsPerPoly);
//find portal edges
if (this.borderSize > 0)
{
//iterate through all the polygons
for (int i = 0; i < polys.Count; i++)
{
Polygon p = polys[i];
//iterate through all the vertices
for (int j = 0; j < numVertsPerPoly; j++)
{
if (p.Vertices[j] == NullId)
break;
//skip connected edges
if (p.NeighborEdges[j] != NullId)
continue;
int nj = j + 1;
if (nj >= numVertsPerPoly || p.Vertices[nj] == NullId)
nj = 0;
//grab two consecutive vertices
int va = p.Vertices[j];
int vb = p.Vertices[nj];
//set some flags
if (verts[va].X == 0 && verts[vb].X == 0)
p.NeighborEdges[j] = NeighborEdgeFlag | 0;
else if (verts[va].Z == contSet.Height && verts[vb].Z == contSet.Height)
p.NeighborEdges[j] = NeighborEdgeFlag | 1;
else if (verts[va].X == contSet.Width && verts[vb].X == contSet.Width)
p.NeighborEdges[j] = NeighborEdgeFlag | 2;
else if (verts[va].Z == 0 && verts[vb].Z == 0)
p.NeighborEdges[j] = NeighborEdgeFlag | 3;
}
}
}
this.vertices = verts.ToArray();
this.polygons = polys.ToArray();
}
/// <summary>
/// Gets the number of vertices
/// </summary>
public int VertCount
{
get
{
return vertices.Length;
}
}
/// <summary>
/// Gets the number of polygons
/// </summary>
public int PolyCount
{
get
{
return polygons.Length;
}
}
/// <summary>
/// Gets the number of vertices per polygon
/// </summary>
public int NumVertsPerPoly
{
get
{
return numVertsPerPoly;
}
}
/// <summary>
/// Gets the vertex data
/// </summary>
public PolyVertex[] Verts
{
get
{
return vertices;
}
}
/// <summary>
/// Gets the polygon data
/// </summary>
public Polygon[] Polys
{
get
{
return polygons;
}
}
/// <summary>
/// Gets the bounds.
/// </summary>
/// <value>The bounds.</value>
public BBox3 Bounds
{
get
{
return bounds;
}
}
/// <summary>
/// Gets the cell size
/// </summary>
public float CellSize
{
get
{
return cellSize;
}
}
/// <summary>
/// Gets the cell height
/// </summary>
public float CellHeight
{
get
{
return cellHeight;
}
}
/// <summary>
/// Gets the border size
/// </summary>
public int BorderSize
{
get
{
return borderSize;
}
}
/// <summary>
/// Determines if it is a boundary edge with the specified flag.
/// </summary>
/// <returns><c>true</c> if is boundary edge the specified flag; otherwise, <c>false</c>.</returns>
/// <param name="flag">The flag.</param>
public static bool IsBoundaryEdge(int flag)
{
return (flag & NeighborEdgeFlag) != 0;
}
/// <summary>
/// Determines if it is an interior edge with the specified flag.
/// </summary>
/// <returns><c>true</c> if is interior edge the specified flag; otherwise, <c>false</c>.</returns>
/// <param name="flag">The flag.</param>
public static bool IsInteriorEdge(int flag)
{
return (flag & NeighborEdgeFlag) == 0;
}
/// <summary>
/// Determines if it is a diagonal flag on the specified index.
/// </summary>
/// <param name="index">The index</param>
/// <returns><c>true</c> if it is a diagonal flag on the specified index; otherwise, <c>false</c>.</returns>
public static bool HasDiagonalFlag(int index)
{
return (index & DiagonalFlag) != 0;
}
/// <summary>
/// True if and only if (v[i], v[j]) is a proper internal diagonal of polygon.
/// </summary>
/// <param name="i">Vertex index i</param>
/// <param name="j">Vertex index j</param>
/// <param name="verts">Contour vertices</param>
/// <param name="indices">PolyMesh indices</param>
/// <returns>True, if internal diagonal. False, if otherwise.</returns>
public static bool Diagonal(int i, int j, PolyVertex[] verts, int[] indices)
{
return InCone(i, j, verts, indices) && Diagonalie(i, j, verts, indices);
}
/// <summary>
/// True if and only if diagonal (i, j) is strictly internal to polygon
/// in neighborhood of i endpoint.
/// </summary>
/// <param name="i">Vertex index i</param>
/// <param name="j">Vertex index j</param>
/// <param name="verts">Contour vertices</param>
/// <param name="indices">PolyMesh indices</param>
/// <returns>True, if internal. False, if otherwise.</returns>
public static bool InCone(int i, int j, PolyVertex[] verts, int[] indices)
{
int pi = RemoveDiagonalFlag(indices[i]);
int pj = RemoveDiagonalFlag(indices[j]);
int pi1 = RemoveDiagonalFlag(indices[Next(i, verts.Length)]);
int pin1 = RemoveDiagonalFlag(indices[Prev(i, verts.Length)]);
//if P[i] is convex vertex (i + 1 left or on (i - 1, i))
if (PolyVertex.IsLeftOn(ref verts[pin1], ref verts[pi], ref verts[pi1]))
return PolyVertex.IsLeft(ref verts[pi], ref verts[pj], ref verts[pin1]) && PolyVertex.IsLeft(ref verts[pj], ref verts[pi], ref verts[pi1]);
//assume (i - 1, i, i + 1) not collinear
return !(PolyVertex.IsLeftOn(ref verts[pi], ref verts[pj], ref verts[pi1]) && PolyVertex.IsLeftOn(ref verts[pj], ref verts[pi], ref verts[pin1]));
}
/// <summary>
/// True if and only if (v[i], v[j]) is internal or external diagonal
/// ignoring edges incident to v[i] or v[j].
/// </summary>
/// <param name="i">Vertex index i</param>
/// <param name="j">Vertex index j</param>
/// <param name="verts">Contour vertices</param>
/// <param name="indices">PolyMesh indices</param>
/// <returns>True, if internal or external diagonal. False, if otherwise.</returns>
public static bool Diagonalie(int i, int j, PolyVertex[] verts, int[] indices)
{
int d0 = RemoveDiagonalFlag(indices[i]);
int d1 = RemoveDiagonalFlag(indices[j]);
//for each edge (k, k + 1)
for (int k = 0; k < verts.Length; k++)
{
int k1 = Next(k, verts.Length);
//skip edges incident to i or j
if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
{
int p0 = RemoveDiagonalFlag(indices[k]);
int p1 = RemoveDiagonalFlag(indices[k1]);
if (PolyVertex.Equal2D(ref verts[d0], ref verts[p0]) ||
PolyVertex.Equal2D(ref verts[d1], ref verts[p0]) ||
PolyVertex.Equal2D(ref verts[d0], ref verts[p1]) ||
PolyVertex.Equal2D(ref verts[d1], ref verts[p1]))
continue;
if (PolyVertex.Intersect(ref verts[d0], ref verts[d1], ref verts[p0], ref verts[p1]))
return false;
}
}
return true;
}
/// <summary>
/// Gets the previous vertex index
/// </summary>
/// <param name="i">The current index</param>
/// <param name="n">The max number of vertices</param>
/// <returns>The previous index</returns>
private static int Prev(int i, int n)
{
return i - 1 >= 0 ? i - 1 : n - 1;
}
/// <summary>
/// Gets the next vertex index
/// </summary>
/// <param name="i">The current index</param>
/// <param name="n">The max number of vertices</param>
/// <returns>The next index</returns>
private static int Next(int i, int n)
{
return i + 1 < n ? i + 1 : 0;
}
/// <summary>
/// Determines whether the vertices follow a certain order
/// </summary>
/// <param name="a">Vertex A</param>
/// <param name="b">Vertex B</param>
/// <param name="c">Vertex C</param>
/// <returns>True if conditions met, false if not</returns>
private static bool ULeft(PolyVertex a, PolyVertex b, PolyVertex c)
{
return (b.X - a.X) * (c.Z - a.Z) -
(c.X - a.X) * (b.Z - a.Z) < 0;
}
/// <summary>
/// Sets the diagonal flag for a vertex
/// </summary>
/// <param name="index">The vertex index</param>
private static void SetDiagonalFlag(ref int index)
{
index |= DiagonalFlag;
}
/// <summary>
/// Remove the diagonal flag for a vertex
/// </summary>
/// <param name="index">The vertex index</param>
/// <returns>The new index</returns>
private static int RemoveDiagonalFlag(int index)
{
return index & ~DiagonalFlag;
}
/// <summary>
/// Remove the diagonal flag for a vertex
/// </summary>
/// <param name="index">The vertex index</param>
private static void RemoveDiagonalFlag(ref int index)
{
index &= ~DiagonalFlag;
}
/// <summary>
/// Walk the edges of a contour to determine whether a triangle can be formed.
/// Form as many triangles as possible.
/// </summary>
/// <param name="verts">Vertices array</param>
/// <param name="indices">Indices array</param>
/// <param name="tris">Triangles array</param>
/// <returns>The number of triangles.</returns>
private static int Triangulate(PolyVertex[] verts, int[] indices, Triangle[] tris)
{
int ntris = 0;
int n = verts.Length;
//last bit of index determines whether vertex can be removed
for (int i = 0; i < n; i++)
{
int i1 = Next(i, n);
int i2 = Next(i1, n);
if (Diagonal(i, i2, verts, indices))
{
SetDiagonalFlag(ref indices[i1]);
}
}
//need 3 verts minimum for a polygon
while (n > 3)
{
//find the minimum distance betwee two vertices.
//also, save their index
int minLen = -1;
int minIndex = -1;
for (int i = 0; i < n; i++)
{
int i1 = Next(i, n);
if (HasDiagonalFlag(indices[i1]))
{
int p0 = RemoveDiagonalFlag(indices[i]);
int p2 = RemoveDiagonalFlag(indices[Next(i1, n)]);
int dx = verts[p2].X - verts[p0].X;
int dy = verts[p2].Z - verts[p0].Z;
int len = dx * dx + dy * dy;
if (minLen < 0 || len < minLen)
{
minLen = len;
minIndex = i;
}
}
}
if (minIndex == -1)
{
return -ntris;
}
int mi = minIndex;
int mi1 = Next(mi, n);
int mi2 = Next(mi1, n);
tris[ntris] = new Triangle();
tris[ntris].Index0 = RemoveDiagonalFlag(indices[mi]);
tris[ntris].Index1 = RemoveDiagonalFlag(indices[mi1]);
tris[ntris].Index2 = RemoveDiagonalFlag(indices[mi2]);
ntris++;
//remove P[i1]
n--;
for (int k = mi1; k < n; k++)
indices[k] = indices[k + 1];
if (mi1 >= n) mi1 = 0;
mi = Prev(mi1, n);
//update diagonal flags
if (Diagonal(Prev(mi, n), mi1, verts, indices))
{
SetDiagonalFlag(ref indices[mi]);
}
else
{
RemoveDiagonalFlag(ref indices[mi]);
}
if (Diagonal(mi, Next(mi1, n), verts, indices))
{
SetDiagonalFlag(ref indices[mi1]);
}
else
{
RemoveDiagonalFlag(ref indices[mi1]);
}
}
//append remaining triangle
tris[ntris] = new Triangle();
tris[ntris].Index0 = RemoveDiagonalFlag(indices[0]);
tris[ntris].Index1 = RemoveDiagonalFlag(indices[1]);
tris[ntris].Index2 = RemoveDiagonalFlag(indices[2]);
ntris++;
return ntris;
}
/// <summary>
/// Generate a new vertices with (x, y, z) coordiates and return the hash code index
/// </summary>
/// <param name="vertDict">Vertex dictionary that maps coordinates to index</param>
/// <param name="v">A vertex.</param>
/// <param name="verts">The list of vertices</param>
/// <returns>The vertex index</returns>
private static int AddVertex(Dictionary<PolyVertex, int> vertDict, PolyVertex v, List<PolyVertex> verts)
{
int index;
if (vertDict.TryGetValue(v, out index))
{
return index;
}
index = verts.Count;
verts.Add(v);
vertDict.Add(v, index);
return index;
}
/// <summary>
/// Try to merge two polygons. If possible, return the distance squared between two vertices.
/// </summary>
/// <param name="polys">Polygon list</param>
/// <param name="polyA">Polygon A</param>
/// <param name="polyB">Polygon B</param>
/// <param name="verts">Vertex list</param>
/// <param name="edgeA">Shared edge's endpoint A</param>
/// <param name="edgeB">Shared edge's endpoint B</param>
/// <returns>The distance between two vertices</returns>
private static int GetPolyMergeValue(List<Polygon> polys, int polyA, int polyB, List<PolyVertex> verts, out int edgeA, out int edgeB)
{
int numVertsA = polys[polyA].VertexCount;
int numVertsB = polys[polyB].VertexCount;
//check if polygons share an edge
edgeA = -1;
edgeB = -1;
//don't merge if result is too big
if (numVertsA + numVertsB - 2 > polys[polyA].Vertices.Length)
return -1;
//iterate through all the vertices of polygonA
for (int i = 0; i < numVertsA; i++)
{
//take two nearby vertices
int va0 = polys[polyA].Vertices[i];
int va1 = polys[polyA].Vertices[(i + 1) % numVertsA];
//make sure va0 < va1
if (va0 > va1)
{
int temp = va0;
va0 = va1;
va1 = temp;
}
//iterate through all the vertices of polygon B
for (int j = 0; j < numVertsB; j++)
{
//take two nearby vertices
int vb0 = polys[polyB].Vertices[j];
int vb1 = polys[polyB].Vertices[(j + 1) % numVertsB];
//make sure vb0 < vb1
if (vb0 > vb1)
{
int temp = vb0;
vb0 = vb1;
vb1 = temp;
}
//edge shared, since vertices are equal
if (va0 == vb0 && va1 == vb1)
{
edgeA = i;
edgeB = j;
break;
}
}
}
//no common edge
if (edgeA == -1 || edgeB == -1)
return -1;
//check if merged polygon would be convex
int vertA, vertB, vertC;
vertA = polys[polyA].Vertices[(edgeA + numVertsA - 1) % numVertsA];
vertB = polys[polyA].Vertices[edgeA];
vertC = polys[polyB].Vertices[(edgeB + 2) % numVertsB];
if (!ULeft(verts[vertA], verts[vertB], verts[vertC]))
return -1;
vertA = polys[polyB].Vertices[(edgeB + numVertsB - 1) % numVertsB];
vertB = polys[polyB].Vertices[edgeB];
vertC = polys[polyA].Vertices[(edgeA + 2) % numVertsA];
if (!ULeft(verts[vertA], verts[vertB], verts[vertC]))
return -1;
vertA = polys[polyA].Vertices[edgeA];
vertB = polys[polyA].Vertices[(edgeA + 1) % numVertsA];
int dx = (int)(verts[vertA].X - verts[vertB].X);
int dy = (int)(verts[vertA].Z - verts[vertB].Z);
return dx * dx + dy * dy;
}
/// <summary>
/// If vertex can't be removed, there is no need to spend time deleting it.
/// </summary>
/// <param name="polys">The polygon list</param>
/// <param name="remove">The vertex index</param>
/// <returns>True, if vertex can be removed. False, if otherwise.</returns>
private static bool CanRemoveVertex(List<Polygon> polys, int remove)
{
//count number of polygons to remove
int numRemovedVerts = 0;
int numTouchedVerts = 0;
int numRemainingEdges = 0;
for (int i = 0; i < polys.Count; i++)
{
Polygon p = polys[i];
int nv = p.VertexCount;
int numRemoved = 0;
int numVerts = 0;
for (int j = 0; j < nv; j++)
{
if (p.Vertices[j] == remove)
{
numTouchedVerts++;
numRemoved++;
}
numVerts++;
}
if (numRemoved > 0)
{
numRemovedVerts += numRemoved;
numRemainingEdges += numVerts - (numRemoved + 1);
}
}
//don't remove a vertex from a triangle since you need at least three vertices to make a polygon
if (numRemainingEdges <= 2)
return false;
//find edges which share removed vertex
int maxEdges = numTouchedVerts * 2;
int nedges = 0;
int[] edges = new int[maxEdges * 3];
for (int i = 0; i < polys.Count; i++)
{
Polygon p = polys[i];
int nv = p.VertexCount;
//collect edges which touch removed vertex
for (int j = 0, k = nv - 1; j < nv; k = j++)
{
if (p.Vertices[j] == remove || p.Vertices[k] == remove)
{
//arrange edge so that a has the removed value
int a = p.Vertices[j], b = p.Vertices[k];
if (b == remove)
{
int temp = a;
a = b;
b = temp;
}
//check if edge exists
bool exists = false;
for (int m = 0; m < nedges; m++)
{
int e = m * 3;
if (edges[e + 1] == b)
{
//increment vertex share count
edges[e + 2]++;
exists = true;
}
}
//add new edge
if (!exists)
{
int e = nedges * 3;
edges[e + 0] = a;
edges[e + 1] = b;
edges[e + 2] = 1;
nedges++;
}
}
}
}
//make sure there can't be more than two open edges
//since there could be two non-adjacent polygons which share the same vertex, which shouldn't be removed
int numOpenEdges = 0;
for (int i = 0; i < nedges; i++)
{
if (edges[i * 3 + 2] < 2)
numOpenEdges++;
}
if (numOpenEdges > 2)
return false;
return true;
}
/// <summary>
/// Connect two adjacent vertices with edges.
/// </summary>
/// <param name="vertices">The vertex list</param>
/// <param name="polys">The polygon list</param>
/// <param name="numVertsPerPoly">Number of vertices per polygon</param>
private static void BuildMeshAdjacency(List<PolyVertex> vertices, List<Polygon> polys, int numVertsPerPoly)
{
int maxEdgeCount = polys.Count * numVertsPerPoly;
int[] firstEdge = new int[vertices.Count + maxEdgeCount];
int nextEdge = vertices.Count;
List<AdjacencyEdge> edges = new List<AdjacencyEdge>(maxEdgeCount);
for (int i = 0; i < vertices.Count; i++)
firstEdge[i] = NullId;
//Iterate through all the polygons
for (int i = 0; i < polys.Count; i++)
{
Polygon p = polys[i];
//Iterate through all the vertices
for (int j = 0; j < numVertsPerPoly; j++)
{
if (p.Vertices[j] == NullId)
break;
//get closest two verts
int v0 = p.Vertices[j];
int v1 = (j + 1 >= numVertsPerPoly || p.Vertices[j + 1] == NullId) ? p.Vertices[0] : p.Vertices[j + 1];
if (v0 < v1)
{
AdjacencyEdge edge;
//store vertices
edge.Vert0 = v0;
edge.Vert1 = v1;
//poly array stores index of polygon
//polyEdge stores the vertex
edge.Poly0 = i;
edge.PolyEdge0 = j;
edge.Poly1 = i;
edge.PolyEdge1 = 0;
//insert edge
firstEdge[nextEdge + edges.Count] = firstEdge[v0];
firstEdge[v0] = edges.Count;
edges.Add(edge);
}
}
}
//Iterate through all the polygons again
for (int i = 0; i < polys.Count; i++)
{
Polygon p = polys[i];
for (int j = 0; j < numVertsPerPoly; j++)
{
if (p.Vertices[j] == NullId)
break;
//get adjacent vertices
int v0 = p.Vertices[j];
int v1 = (j + 1 >= numVertsPerPoly || p.Vertices[j + 1] == NullId) ? p.Vertices[0] : p.Vertices[j + 1];
if (v0 > v1)
{
//Iterate through all the edges
for (int e = firstEdge[v1]; e != NullId; e = firstEdge[nextEdge + e])
{
AdjacencyEdge edge = edges[e];
if (edge.Vert1 == v0 && edge.Poly0 == edge.Poly1)
{
edge.Poly1 = i;
edge.PolyEdge1 = j;
edges[e] = edge;
break;
}
}
}
}
}
//store adjacency
for (int i = 0; i < edges.Count; i++)
{
AdjacencyEdge e = edges[i];
//the endpoints belong to different polygons
if (e.Poly0 != e.Poly1)
{
//store other polygon number as part of extra info
polys[e.Poly0].NeighborEdges[e.PolyEdge0] = e.Poly1;
polys[e.Poly1].NeighborEdges[e.PolyEdge1] = e.Poly0;
}
}
}
/// <summary>
/// The two polygon arrrays are merged into a single array
/// </summary>
/// <param name="polys">The polygon list</param>
/// <param name="polyA">Polygon A</param>
/// <param name="polyB">Polygon B</param>
/// <param name="edgeA">Starting edge for polygon A</param>
/// <param name="edgeB">Starting edge for polygon B</param>
private void MergePolys(List<Polygon> polys, int polyA, int polyB, int edgeA, int edgeB)
{
//TODO replace with Polygon.Merge()
int numA = polys[polyA].VertexCount;
int numB = polys[polyB].VertexCount;
int[] temp = new int[numA + numB];
//merge
for (int i = 0; i < numVertsPerPoly; i++)
temp[i] = NullId;
int n = 0;
//add polygon A
for (int i = 0; i < numA - 1; i++)
temp[n++] = polys[polyA].Vertices[(edgeA + 1 + i) % numA];
//add polygon B
for (int i = 0; i < numB - 1; i++)
temp[n++] = polys[polyB].Vertices[(edgeB + 1 + i) % numB];
//save merged data to new polygon
for (int i = 0; i < numVertsPerPoly; i++)
polys[polyA].Vertices[i] = temp[i];
}
/// <summary>
/// Removing vertices will leave holes that have to be triangulated again.
/// </summary>
/// <param name="verts">A list of vertices</param>
/// <param name="polys">A list of polygons</param>
/// <param name="vertex">The vertex to remove</param>
private void RemoveVertex(List<PolyVertex> verts, List<Polygon> polys, int vertex)
{
int numVertsPerPoly = this.numVertsPerPoly;
//count number of polygons to remove
int numRemovedVerts = 0;
for (int i = 0; i < polys.Count; i++)
{
Polygon p = polys[i];
for (int j = 0; j < p.VertexCount; j++)
{
if (p.Vertices[j] == vertex)
numRemovedVerts++;
}
}
List<Edge> edges = new List<Edge>(numRemovedVerts * numVertsPerPoly);
List<int> hole = new List<int>(numRemovedVerts * numVertsPerPoly);
List<RegionId> regions = new List<RegionId>(numRemovedVerts * numVertsPerPoly);
List<Area> areas = new List<Area>(numRemovedVerts * numVertsPerPoly);
//Iterate through all the polygons
for (int i = 0; i < polys.Count; i++)
{
Polygon p = polys[i];
if (p.ContainsVertex(vertex))
{
int nv = p.VertexCount;
//collect edges which don't touch removed vertex
for (int j = 0, k = nv - 1; j < nv; k = j++)
if (p.Vertices[j] != vertex && p.Vertices[k] != vertex)
edges.Add(new Edge(p.Vertices[k], p.Vertices[j], p.RegionId, p.Area));
polys[i] = polys[polys.Count - 1];
polys.RemoveAt(polys.Count - 1);
i--;
}
}
//remove vertex
verts.RemoveAt(vertex);
//adjust indices
for (int i = 0; i < polys.Count; i++)
{
Polygon p = polys[i];
for (int j = 0; j < p.VertexCount; j++)
{
if (p.Vertices[j] > vertex)
p.Vertices[j]--;
}
}
for (int i = 0; i < edges.Count; i++)
{
Edge edge = edges[i];
if (edge.Vert0 > vertex)
edge.Vert0--;
if (edge.Vert1 > vertex)
edge.Vert1--;
edges[i] = edge;
}
if (edges.Count == 0)
return;
//Find edges surrounding the holes
hole.Add(edges[0].Vert0);
regions.Add(edges[0].Region);
areas.Add(edges[0].Area);
while (edges.Count > 0)
{
bool match = false;
for (int i = 0; i < edges.Count; i++)
{
Edge edge = edges[i];
bool add = false;
if (hole[0] == edge.Vert1)
{
//segment matches beginning of hole boundary
hole.Insert(0, edge.Vert0);
regions.Insert(0, edge.Region);
areas.Insert(0, edge.Area);
add = true;
}
else if (hole[hole.Count - 1] == edge.Vert0)
{
//segment matches end of hole boundary
hole.Add(edge.Vert1);
regions.Add(edge.Region);
areas.Add(edge.Area);
add = true;
}
if (add)
{
//edge segment was added so remove it
edges[i] = edges[edges.Count - 1];
edges.RemoveAt(edges.Count - 1);
match = true;
i--;
}
}
if (!match)
break;
}
var tris = new Triangle[hole.Count];
var tverts = new PolyVertex[hole.Count];
var thole = new int[hole.Count];
//generate temp vertex array for triangulation
for (int i = 0; i < hole.Count; i++)
{
int polyIndex = hole[i];
tverts[i] = verts[polyIndex];
thole[i] = i;
}
//triangulate the hole
int ntris = Triangulate(tverts, thole, tris);
if (ntris < 0)
ntris = -ntris;
//merge hole triangles back to polygons
List<Polygon> mergePolys = new List<Polygon>(ntris + 1);
for (int j = 0; j < ntris; j++)
{
Triangle t = tris[j];
if (t.Index0 != t.Index1 && t.Index0 != t.Index2 && t.Index1 != t.Index2)
{
Polygon p = new Polygon(numVertsPerPoly, areas[t.Index0], regions[t.Index0], 0);
p.Vertices[0] = hole[t.Index0];
p.Vertices[1] = hole[t.Index1];
p.Vertices[2] = hole[t.Index2];
mergePolys.Add(p);
}
}
if (mergePolys.Count == 0)
return;
//merge polygons
if (numVertsPerPoly > 3)
{
while (true)
{
//find best polygons
int bestMergeVal = 0;
int bestPolyA = 0, bestPolyB = 0, bestEa = 0, bestEb = 0;
for (int j = 0; j < mergePolys.Count - 1; j++)
{
int pj = j;
for (int k = j + 1; k < mergePolys.Count; k++)
{
int pk = k;
int edgeA, edgeB;
int v = GetPolyMergeValue(mergePolys, pj, pk, verts, out edgeA, out edgeB);
if (v > bestMergeVal)
{
bestMergeVal = v;
bestPolyA = j;
bestPolyB = k;
bestEa = edgeA;
bestEb = edgeB;
}
}
}
if (bestMergeVal > 0)
{
int polyA = bestPolyA;
int polyB = bestPolyB;
MergePolys(mergePolys, polyA, polyB, bestEa, bestEb);
mergePolys[polyB] = mergePolys[mergePolys.Count - 1];
mergePolys.RemoveAt(mergePolys.Count - 1);
}
else
{
//no more merging
break;
}
}
}
//add merged polys back to the list.
polys.AddRange(mergePolys);
}
/// <summary>
/// A triangle contains three indices.
/// </summary>
private struct Triangle
{
public int Index0;
public int Index1;
public int Index2;
}
/// <summary>
/// Two adjacent vertices form an edge.
/// </summary>
private struct AdjacencyEdge
{
public int Vert0;
public int Vert1;
public int PolyEdge0;
public int PolyEdge1;
public int Poly0;
public int Poly1;
}
/// <summary>
/// Another edge structure, but this one contains the RegionId and AreaId.
/// </summary>
private struct Edge
{
public int Vert0;
public int Vert1;
public RegionId Region;
public Area Area;
/// <summary>
/// Initializes a new instance of the <see cref="Edge"/> struct.
/// </summary>
/// <param name="vert0">Vertex A</param>
/// <param name="vert1">Vertex B</param>
/// <param name="region">Region id</param>
/// <param name="area">Area id</param>
public Edge(int vert0, int vert1, RegionId region, Area area)
{
Vert0 = vert0;
Vert1 = vert1;
Region = region;
Area = area;
}
}
/// <summary>
/// Each polygon is a collection of vertices. It is the basic unit of the PolyMesh
/// </summary>
public class Polygon
{
private int[] vertices; //"numVertsPerPoly" elements
private int[] neighborEdges; //"numVertsPerPoly" elements
private Area area;
private RegionId regionId;
private int flags;
/// <summary>
/// Initializes a new instance of the <see cref="Polygon" /> class.
/// </summary>
/// <param name="numVertsPerPoly">The number of vertices per polygon.</param>
/// <param name="area">The AreaId</param>
/// <param name="regionId">The RegionId</param>
/// <param name="flags">Polygon flags</param>
public Polygon(int numVertsPerPoly, Area area, RegionId regionId, int flags)
{
vertices = new int[numVertsPerPoly];
neighborEdges = new int[numVertsPerPoly];
this.area = area;
this.regionId = regionId;
this.flags = flags;
for (int i = 0; i < numVertsPerPoly; i++)
{
vertices[i] = NullId;
neighborEdges[i] = NullId;
}
}
/// <summary>
/// Gets the indices for the vertices.
/// </summary>
/// <value>The vertices.</value>
public int[] Vertices
{
get
{
return vertices;
}
}
/// <summary>
/// Gets the neighbor edges.
/// </summary>
/// <value>The neighbor edges.</value>
public int[] NeighborEdges
{
get
{
return neighborEdges;
}
}
/// <summary>
/// Gets or sets the area id
/// </summary>
public Area Area
{
get
{
return area;
}
set
{
area = value;
}
}
/// <summary>
/// Gets or sets the region identifier.
/// </summary>
/// <value>The region identifier.</value>
public RegionId RegionId
{
get
{
return regionId;
}
set
{
regionId = value;
}
}
/// <summary>
/// Gets or sets the flags.
/// </summary>
/// <value>The flags.</value>
public int Flags
{
get
{
return flags;
}
set
{
flags = value;
}
}
/// <summary>
/// Gets the the number of vertex.
/// </summary>
/// <value>The vertex count.</value>
public int VertexCount
{
get
{
for (int i = 0; i < vertices.Length; i++)
if (vertices[i] == NullId)
return i;
return vertices.Length;
}
}
/// <summary>
/// Determine if the vertex is in polygon.
/// </summary>
/// <returns><c>true</c>, if vertex was containsed, <c>false</c> otherwise.</returns>
/// <param name="vertex">The Vertex.</param>
public bool ContainsVertex(int vertex)
{
//iterate through all the vertices
for (int i = 0; i < vertices.Length; i++)
{
//find the vertex, return false if at end of defined polygon.
int v = vertices[i];
if (v == vertex)
return true;
else if (v == NullId)
return false;
}
return false;
}
}
}
}
| |
using Swagger.ObjectModel.Builders;
using System.Linq;
using Xunit;
namespace Swagger.ObjectModel.Tests.Builders
{
public class DataTypeBuilderTest
{
private readonly CustomDataTypeBuilder builder;
internal class CustomDataTypeBuilder : DataTypeBuilder<CustomDataTypeBuilder, DataType>
{
public CustomDataTypeBuilder() : base()
{
}
public override DataType Build()
{
return this.BuildBase();
}
}
public DataTypeBuilderTest()
{
this.builder = new CustomDataTypeBuilder();
}
[Fact]
public void Maximum_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Maximum);
}
[Fact]
public void Maximum_ShouldBeSettable()
{
var maxValue = int.MaxValue;
var result = builder.Maximum(maxValue).Build();
Assert.NotNull(result);
Assert.Equal(maxValue, result.Maximum);
}
[Fact]
public void Minimum_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Minimum);
}
[Fact]
public void Minimum_ShouldBeSettable()
{
var minValue = int.MinValue;
var result = builder.Minimum(minValue).Build();
Assert.NotNull(result);
Assert.Equal(minValue, result.Minimum);
}
[Fact]
public void Type_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Type);
}
[Fact]
public void Type_ShouldBeSettable()
{
var type = "int";
var result = builder.Type(type).Build();
Assert.NotNull(result);
Assert.Equal(type, result.Type);
}
[Fact]
public void CollectionFormat_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.CollectionFormat);
}
[Fact]
public void CollectionFormat_ShouldBeSettable()
{
var formats = new CollectionFormats();
var result = builder.CollectionFormat(formats).Build();
Assert.NotNull(result);
Assert.Equal(formats, result.CollectionFormat);
}
[Fact]
public void Default_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Default);
}
[Fact]
public void Default_ShouldBeSettable()
{
var obj = new object();
var result = builder.Default(obj).Build();
Assert.NotNull(result);
Assert.Equal(obj, result.Default);
}
[Fact]
public void Enum_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Enum);
}
[Fact]
public void Enum_ShouldBeSettable()
{
var enumValue = "enum";
var result = builder.Enum(enumValue).Build();
Assert.NotNull(result);
Assert.Equal(enumValue, result.Enum.First());
}
[Fact]
public void ExclusiveMax_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.ExclusiveMaximum);
}
[Fact]
public void ExclusiveMax_ShouldBeSettable()
{
var result = builder.IsExclusiveMaximum().Build();
Assert.NotNull(result);
Assert.True(result.ExclusiveMaximum);
}
[Fact]
public void ExclusiveMin_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.ExclusiveMinimum);
}
[Fact]
public void ExclusiveMin_ShouldBeSettable()
{
var result = builder.IsExclusiveMinimum().Build();
Assert.NotNull(result);
Assert.True(result.ExclusiveMinimum);
}
[Fact]
public void Format_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Format);
}
[Fact]
public void Format_ShouldBeSettable()
{
var format = "mm-dd-yyyy";
var result = builder.Format(format).Build();
Assert.NotNull(result);
Assert.Equal(format, result.Format);
}
[Fact]
public void Items_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Items);
}
[Fact]
public void Items_ShouldBeSettable()
{
var item = new Item();
var result = builder.Items(item).Build();
Assert.NotNull(result);
Assert.Equal(item, result.Items);
}
[Fact]
public void MaxItems_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.MaxItems);
}
[Fact]
public void MaxItems_ShouldBeSettable()
{
var maxItems = 2;
var result = builder.MaxItems(maxItems).Build();
Assert.NotNull(result);
Assert.Equal(maxItems, result.MaxItems);
}
[Fact]
public void MaxLength_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.MaxLength);
}
[Fact]
public void MaxLength_ShouldBeSettable()
{
var maxLength = 2;
var result = builder.MaxLength(maxLength).Build();
Assert.NotNull(result);
Assert.Equal(maxLength, result.MaxLength);
}
[Fact]
public void MinItems_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.MinItems);
}
[Fact]
public void MinItems_ShouldBeSettable()
{
var minItems = 2;
var result = builder.MinItems(minItems).Build();
Assert.NotNull(result);
Assert.Equal(minItems, result.MinItems);
}
[Fact]
public void MultipleOf_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.MultipleOf);
}
[Fact]
public void MultipleOf_ShouldBeSettable()
{
var multipleOf = 2;
var result = builder.MultipleOf(multipleOf).Build();
Assert.NotNull(result);
Assert.Equal(multipleOf, result.MultipleOf);
}
[Fact]
public void Pattern_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Pattern);
}
[Fact]
public void Pattern_ShouldBeSettable()
{
var pattern = "mm-dd-yyyy";
var result = builder.Pattern(pattern).Build();
Assert.NotNull(result);
Assert.Equal(pattern, result.Pattern);
}
[Fact]
public void Reference_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.Ref);
}
[Fact]
public void Reference_ShouldBeSettable()
{
var reference = "#ref";
var result = builder.Reference(reference).Build();
Assert.NotNull(result);
Assert.Equal(reference, result.Ref);
}
[Fact]
public void UniqueItems_ShouldDefaultToNull()
{
var result = builder.Build();
Assert.NotNull(result);
Assert.Null(result.UniqueItems);
}
[Fact]
public void UniqueItems_ShouldBeSettable()
{
var result = builder.IsUniqueItems().Build();
Assert.NotNull(result);
Assert.True(result.UniqueItems);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Diagnostics;
namespace System.IO
{
// This abstract base class represents a writer that can write
// primitives to an arbitrary stream. A subclass can override methods to
// give unique encodings.
[Serializable]
#if PROJECTN
[Internal.Runtime.CompilerServices.RelocatedTypeAttribute("System.Runtime.Extensions")]
#endif
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
protected Stream OutStream;
private byte[] _buffer; // temp space for writing primitives to.
private Encoding _encoding;
private Encoder _encoder;
private bool _leaveOpen;
// Perf optimization stuff
private byte[] _largeByteBuffer; // temp space for writing chars.
private int _maxChars; // max # of chars we can put in _largeByteBuffer
// Size should be around the max number of chars/string * Encoding's max bytes/char
private const int LargeByteBufferSize = 256;
// Protected default constructor that sets the output stream
// to a null stream (a bit bucket).
protected BinaryWriter()
{
OutStream = Stream.Null;
_buffer = new byte[16];
_encoding = EncodingCache.UTF8NoBOM;
_encoder = _encoding.GetEncoder();
}
public BinaryWriter(Stream output) : this(output, EncodingCache.UTF8NoBOM, false)
{
}
public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false)
{
}
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
{
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (!output.CanWrite)
{
throw new ArgumentException(SR.Argument_StreamNotWritable);
}
OutStream = output;
_buffer = new byte[16];
_encoding = encoding;
_encoder = _encoding.GetEncoder();
_leaveOpen = leaveOpen;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_leaveOpen)
{
OutStream.Flush();
}
else
{
OutStream.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
}
/// <remarks>
/// Override Dispose(bool) instead of Close(). This API exists for compatibility purposes.
/// </remarks>
public virtual void Close()
{
Dispose(true);
}
/// <summary>
/// Returns the stream associated with the writer. It flushes all pending
/// writes before returning. All subclasses should override Flush to
/// ensure that all buffered data is sent to the stream.
/// </summary>
public virtual Stream BaseStream
{
get
{
Flush();
return OutStream;
}
}
// Clears all buffers for this writer and causes any buffered data to be
// written to the underlying device.
public virtual void Flush()
{
OutStream.Flush();
}
public virtual long Seek(int offset, SeekOrigin origin)
{
return OutStream.Seek(offset, origin);
}
// Writes a boolean to this stream. A single byte is written to the stream
// with the value 0 representing false or the value 1 representing true.
//
public virtual void Write(bool value)
{
_buffer[0] = (byte)(value ? 1 : 0);
OutStream.Write(_buffer, 0, 1);
}
// Writes a byte to this stream. The current position of the stream is
// advanced by one.
//
public virtual void Write(byte value)
{
OutStream.WriteByte(value);
}
// Writes a signed byte to this stream. The current position of the stream
// is advanced by one.
//
[CLSCompliant(false)]
public virtual void Write(sbyte value)
{
OutStream.WriteByte((byte)value);
}
// Writes a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
public virtual void Write(byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
OutStream.Write(buffer, 0, buffer.Length);
}
// Writes a section of a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
public virtual void Write(byte[] buffer, int index, int count)
{
OutStream.Write(buffer, index, count);
}
// Writes a character to this stream. The current position of the stream is
// advanced by two.
// Note this method cannot handle surrogates properly in UTF-8.
//
public virtual void Write(char ch)
{
if (char.IsSurrogate(ch))
{
throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar);
}
Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
char[] chBuf = new char[] { ch };
numBytes = _encoder.GetBytes(chBuf, 0, 1, _buffer, 0, true);
OutStream.Write(_buffer, 0, numBytes);
}
// Writes a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
public virtual void Write(char[] chars)
{
if (chars == null)
{
throw new ArgumentNullException(nameof(chars));
}
byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
OutStream.Write(bytes, 0, bytes.Length);
}
// Writes a section of a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
public virtual void Write(char[] chars, int index, int count)
{
byte[] bytes = _encoding.GetBytes(chars, index, count);
OutStream.Write(bytes, 0, bytes.Length);
}
// Writes a double to this stream. The current position of the stream is
// advanced by eight.
//
public unsafe virtual void Write(double value)
{
ulong TmpValue = *(ulong*)&value;
_buffer[0] = (byte)TmpValue;
_buffer[1] = (byte)(TmpValue >> 8);
_buffer[2] = (byte)(TmpValue >> 16);
_buffer[3] = (byte)(TmpValue >> 24);
_buffer[4] = (byte)(TmpValue >> 32);
_buffer[5] = (byte)(TmpValue >> 40);
_buffer[6] = (byte)(TmpValue >> 48);
_buffer[7] = (byte)(TmpValue >> 56);
OutStream.Write(_buffer, 0, 8);
}
public virtual void Write(decimal value)
{
int[] bits = decimal.GetBits(value);
Debug.Assert(bits.Length == 4);
int lo = bits[0];
_buffer[0] = (byte)lo;
_buffer[1] = (byte)(lo >> 8);
_buffer[2] = (byte)(lo >> 16);
_buffer[3] = (byte)(lo >> 24);
int mid = bits[1];
_buffer[4] = (byte)mid;
_buffer[5] = (byte)(mid >> 8);
_buffer[6] = (byte)(mid >> 16);
_buffer[7] = (byte)(mid >> 24);
int hi = bits[2];
_buffer[8] = (byte)hi;
_buffer[9] = (byte)(hi >> 8);
_buffer[10] = (byte)(hi >> 16);
_buffer[11] = (byte)(hi >> 24);
int flags = bits[3];
_buffer[12] = (byte)flags;
_buffer[13] = (byte)(flags >> 8);
_buffer[14] = (byte)(flags >> 16);
_buffer[15] = (byte)(flags >> 24);
OutStream.Write(_buffer, 0, 16);
}
// Writes a two-byte signed integer to this stream. The current position of
// the stream is advanced by two.
//
public virtual void Write(short value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
OutStream.Write(_buffer, 0, 2);
}
// Writes a two-byte unsigned integer to this stream. The current position
// of the stream is advanced by two.
//
[CLSCompliant(false)]
public virtual void Write(ushort value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
OutStream.Write(_buffer, 0, 2);
}
// Writes a four-byte signed integer to this stream. The current position
// of the stream is advanced by four.
//
public virtual void Write(int value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes a four-byte unsigned integer to this stream. The current position
// of the stream is advanced by four.
//
[CLSCompliant(false)]
public virtual void Write(uint value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes an eight-byte signed integer to this stream. The current position
// of the stream is advanced by eight.
//
public virtual void Write(long value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
_buffer[4] = (byte)(value >> 32);
_buffer[5] = (byte)(value >> 40);
_buffer[6] = (byte)(value >> 48);
_buffer[7] = (byte)(value >> 56);
OutStream.Write(_buffer, 0, 8);
}
// Writes an eight-byte unsigned integer to this stream. The current
// position of the stream is advanced by eight.
//
[CLSCompliant(false)]
public virtual void Write(ulong value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
_buffer[4] = (byte)(value >> 32);
_buffer[5] = (byte)(value >> 40);
_buffer[6] = (byte)(value >> 48);
_buffer[7] = (byte)(value >> 56);
OutStream.Write(_buffer, 0, 8);
}
// Writes a float to this stream. The current position of the stream is
// advanced by four.
//
public unsafe virtual void Write(float value)
{
uint TmpValue = *(uint*)&value;
_buffer[0] = (byte)TmpValue;
_buffer[1] = (byte)(TmpValue >> 8);
_buffer[2] = (byte)(TmpValue >> 16);
_buffer[3] = (byte)(TmpValue >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes a length-prefixed string to this stream in the BinaryWriter's
// current Encoding. This method first writes the length of the string as
// a four-byte unsigned integer, and then writes that many characters
// to the stream.
//
public virtual void Write(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
int len = _encoding.GetByteCount(value);
Write7BitEncodedInt(len);
if (_largeByteBuffer == null)
{
_largeByteBuffer = new byte[LargeByteBufferSize];
_maxChars = LargeByteBufferSize / _encoding.GetMaxByteCount(1);
}
if (len <= LargeByteBufferSize)
{
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
else
{
// Aggressively try to not allocate memory in this loop for
// runtime performance reasons. Use an Encoder to write out
// the string correctly (handling surrogates crossing buffer
// boundaries properly).
int charStart = 0;
int numLeft = value.Length;
#if DEBUG
int totalBytes = 0;
#endif
while (numLeft > 0)
{
// Figure out how many chars to process this round.
int charCount = (numLeft > _maxChars) ? _maxChars : numLeft;
int byteLen;
byteLen = _encoder.GetBytes(value.ToCharArray(), charStart, charCount, _largeByteBuffer, 0, charCount == numLeft);
#if DEBUG
totalBytes += byteLen;
Debug.Assert(totalBytes <= len && byteLen <= LargeByteBufferSize, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
numLeft -= charCount;
}
#if DEBUG
Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
#endif
}
}
protected void Write7BitEncodedInt(int value)
{
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
uint v = (uint)value; // support negative numbers
while (v >= 0x80)
{
Write((byte)(v | 0x80));
v >>= 7;
}
Write((byte)v);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Support;
using UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
namespace Lucene.Net.Store
{
/// <summary>Abstract base class for output to a file in a Directory. A random-access
/// output stream. Used for all Lucene index output operations.
/// </summary>
/// <seealso cref="Directory">
/// </seealso>
/// <seealso cref="IndexInput">
/// </seealso>
public abstract class IndexOutput : IDisposable
{
/// <summary>Writes a single byte.</summary>
/// <seealso cref="IndexInput.ReadByte()">
/// </seealso>
public abstract void WriteByte(byte b);
/// <summary>Writes an array of bytes.</summary>
/// <param name="b">the bytes to write
/// </param>
/// <param name="length">the number of bytes to write
/// </param>
/// <seealso cref="IndexInput.ReadBytes(byte[],int,int)">
/// </seealso>
public virtual void WriteBytes(byte[] b, int length)
{
WriteBytes(b, 0, length);
}
/// <summary>Writes an array of bytes.</summary>
/// <param name="b">the bytes to write
/// </param>
/// <param name="offset">the offset in the byte array
/// </param>
/// <param name="length">the number of bytes to write
/// </param>
/// <seealso cref="IndexInput.ReadBytes(byte[],int,int)">
/// </seealso>
public abstract void WriteBytes(byte[] b, int offset, int length);
/// <summary>Writes an int as four bytes.</summary>
/// <seealso cref="IndexInput.ReadInt()">
/// </seealso>
public virtual void WriteInt(int i)
{
WriteByte((byte) (i >> 24));
WriteByte((byte) (i >> 16));
WriteByte((byte) (i >> 8));
WriteByte((byte) i);
}
/// <summary>Writes an int in a variable-length format. Writes between one and
/// five bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// </summary>
/// <seealso cref="IndexInput.ReadVInt()">
/// </seealso>
public virtual void WriteVInt(int i)
{
while ((i & ~ 0x7F) != 0)
{
WriteByte((byte) ((i & 0x7f) | 0x80));
i = Number.URShift(i, 7);
}
WriteByte((byte) i);
}
/// <summary>Writes a long as eight bytes.</summary>
/// <seealso cref="IndexInput.ReadLong()">
/// </seealso>
public virtual void WriteLong(long i)
{
WriteInt((int) (i >> 32));
WriteInt((int) i);
}
/// <summary>Writes an long in a variable-length format. Writes between one and five
/// bytes. Smaller values take fewer bytes. Negative numbers are not
/// supported.
/// </summary>
/// <seealso cref="IndexInput.ReadVLong()">
/// </seealso>
public virtual void WriteVLong(long i)
{
while ((i & ~ 0x7F) != 0)
{
WriteByte((byte) ((i & 0x7f) | 0x80));
i = Number.URShift(i, 7);
}
WriteByte((byte) i);
}
/// <summary>Writes a string.</summary>
/// <seealso cref="IndexInput.ReadString()">
/// </seealso>
public virtual void WriteString(System.String s)
{
UnicodeUtil.UTF8Result utf8Result = new UnicodeUtil.UTF8Result();
UnicodeUtil.UTF16toUTF8(s, 0, s.Length, utf8Result);
WriteVInt(utf8Result.length);
WriteBytes(utf8Result.result, 0, utf8Result.length);
}
/// <summary>Writes a sub sequence of characters from s as the old
/// format (modified UTF-8 encoded bytes).
/// </summary>
/// <param name="s">the source of the characters
/// </param>
/// <param name="start">the first character in the sequence
/// </param>
/// <param name="length">the number of characters in the sequence
/// </param>
/// <deprecated> -- please pre-convert to utf8 bytes
/// instead or use <see cref="WriteString" />
/// </deprecated>
[Obsolete("-- please pre-convert to utf8 bytes instead or use WriteString")]
public virtual void WriteChars(System.String s, int start, int length)
{
int end = start + length;
for (int i = start; i < end; i++)
{
int code = (int) s[i];
if (code >= 0x01 && code <= 0x7F)
WriteByte((byte) code);
else if (((code >= 0x80) && (code <= 0x7FF)) || code == 0)
{
WriteByte((byte) (0xC0 | (code >> 6)));
WriteByte((byte) (0x80 | (code & 0x3F)));
}
else
{
WriteByte((byte) (0xE0 | (Number.URShift(code, 12))));
WriteByte((byte) (0x80 | ((code >> 6) & 0x3F)));
WriteByte((byte) (0x80 | (code & 0x3F)));
}
}
}
/// <summary>Writes a sub sequence of characters from char[] as
/// the old format (modified UTF-8 encoded bytes).
/// </summary>
/// <param name="s">the source of the characters
/// </param>
/// <param name="start">the first character in the sequence
/// </param>
/// <param name="length">the number of characters in the sequence
/// </param>
/// <deprecated> -- please pre-convert to utf8 bytes instead or use <see cref="WriteString" />
/// </deprecated>
[Obsolete("-- please pre-convert to utf8 bytes instead or use WriteString")]
public virtual void WriteChars(char[] s, int start, int length)
{
int end = start + length;
for (int i = start; i < end; i++)
{
int code = (int) s[i];
if (code >= 0x01 && code <= 0x7F)
WriteByte((byte) code);
else if (((code >= 0x80) && (code <= 0x7FF)) || code == 0)
{
WriteByte((byte) (0xC0 | (code >> 6)));
WriteByte((byte) (0x80 | (code & 0x3F)));
}
else
{
WriteByte((byte) (0xE0 | (Number.URShift(code, 12))));
WriteByte((byte) (0x80 | ((code >> 6) & 0x3F)));
WriteByte((byte) (0x80 | (code & 0x3F)));
}
}
}
private static int COPY_BUFFER_SIZE = 16384;
private byte[] copyBuffer;
/// <summary>Copy numBytes bytes from input to ourself. </summary>
public virtual void CopyBytes(IndexInput input, long numBytes)
{
System.Diagnostics.Debug.Assert(numBytes >= 0, "numBytes=" + numBytes);
long left = numBytes;
if (copyBuffer == null)
copyBuffer = new byte[COPY_BUFFER_SIZE];
while (left > 0)
{
int toCopy;
if (left > COPY_BUFFER_SIZE)
toCopy = COPY_BUFFER_SIZE;
else
toCopy = (int) left;
input.ReadBytes(copyBuffer, 0, toCopy);
WriteBytes(copyBuffer, 0, toCopy);
left -= toCopy;
}
}
/// <summary>Forces any buffered output to be written. </summary>
public abstract void Flush();
/// <summary>Closes this stream to further operations. </summary>
[Obsolete("Use Dispose() instead.")]
public void Close()
{
Dispose();
}
/// <summary>Closes this stream to further operations. </summary>
public void Dispose()
{
Dispose(true);
}
protected abstract void Dispose(bool disposing);
/// <summary>Returns the current position in this file, where the next write will
/// occur.
/// </summary>
/// <seealso cref="Seek(long)">
/// </seealso>
public abstract long FilePointer { get; }
/// <summary>Sets current position in this file, where the next write will occur.</summary>
/// <seealso cref="FilePointer()">
/// </seealso>
public abstract void Seek(long pos);
/// <summary>The number of bytes in the file. </summary>
public abstract long Length { get; }
/// <summary>Set the file length. By default, this method does
/// nothing (it's optional for a Directory to implement
/// it). But, certain Directory implementations (for
/// </summary>
/// <seealso cref="FSDirectory"> can use this to inform the
/// underlying IO system to pre-allocate the file to the
/// specified size. If the length is longer than the
/// current file length, the bytes added to the file are
/// undefined. Otherwise the file is truncated.
/// </seealso>
/// <param name="length">file length
/// </param>
public virtual void SetLength(long length)
{
}
// map must be Map<String, String>
public virtual void WriteStringStringMap(System.Collections.Generic.IDictionary<string,string> map)
{
if (map == null)
{
WriteInt(0);
}
else
{
WriteInt(map.Count);
foreach (var entry in map)
{
WriteString(entry.Key);
WriteString(entry.Value);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Globalization
{
/// <summary>
/// This class defines behaviors specific to a writing system.
/// A writing system is the collection of scripts and orthographic rules
/// required to represent a language as text.
/// </summary>
public class StringInfo
{
private string _str = null!; // initialized in helper called by ctors
private int[]? _indexes;
public StringInfo() : this(string.Empty)
{
}
public StringInfo(string value)
{
this.String = value;
}
public override bool Equals(object? value)
{
return value is StringInfo otherStringInfo
&& _str.Equals(otherStringInfo._str);
}
public override int GetHashCode() => _str.GetHashCode();
/// <summary>
/// Our zero-based array of index values into the string. Initialize if
/// our private array is not yet, in fact, initialized.
/// </summary>
private int[]? Indexes
{
get
{
if (_indexes == null && String.Length > 0)
{
_indexes = StringInfo.ParseCombiningCharacters(String);
}
return _indexes;
}
}
public string String
{
get => _str;
set
{
_str = value ?? throw new ArgumentNullException(nameof(value));
_indexes = null;
}
}
public int LengthInTextElements => Indexes?.Length ?? 0;
public string SubstringByTextElements(int startingTextElement)
{
// If the string is empty, no sense going further.
if (Indexes == null)
{
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.ArgumentOutOfRange_NeedPosNum);
}
else
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.Arg_ArgumentOutOfRangeException);
}
}
return SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement);
}
public string SubstringByTextElements(int startingTextElement, int lengthInTextElements)
{
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.ArgumentOutOfRange_NeedPosNum);
}
if (String.Length == 0 || startingTextElement >= Indexes!.Length)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.Arg_ArgumentOutOfRangeException);
}
if (lengthInTextElements < 0)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), lengthInTextElements, SR.ArgumentOutOfRange_NeedPosNum);
}
if (startingTextElement > Indexes.Length - lengthInTextElements)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), lengthInTextElements, SR.Arg_ArgumentOutOfRangeException);
}
int start = Indexes[startingTextElement];
if (startingTextElement + lengthInTextElements == Indexes.Length)
{
// We are at the last text element in the string and because of that
// must handle the call differently.
return String.Substring(start);
}
else
{
return String.Substring(start, Indexes[lengthInTextElements + startingTextElement] - start);
}
}
public static string GetNextTextElement(string str) => GetNextTextElement(str, 0);
/// <summary>
/// Get the code point count of the current text element.
///
/// A combining class is defined as:
/// A character/surrogate that has the following Unicode category:
/// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
/// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
/// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
///
/// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
/// 1. If a character/surrogate is in the following category, it is a text element.
/// It can NOT further combine with characters in the combinging class to form a text element.
/// * one of the Unicode category in the combinging class
/// * UnicodeCategory.Format
/// * UnicodeCateogry.Control
/// * UnicodeCategory.OtherNotAssigned
/// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
/// </summary>
/// <returns>The length of the current text element</returns>
internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return currentCharCount;
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext))
{
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
}
else
{
// Remember the current index.
int startIndex = index;
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
{
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return index - startIndex;
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return ret;
}
/// <summary>
/// Returns the str containing the next text element in str starting at
/// index index. If index is not supplied, then it will start at the beginning
/// of str. It recognizes a base character plus one or more combining
/// characters or a properly formed surrogate pair as a text element.
/// See also the ParseCombiningCharacters() and the ParseSurrogates() methods.
/// </summary>
public static string GetNextTextElement(string str, int index)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
if (index < 0 || index >= len)
{
if (index == len)
{
return string.Empty;
}
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen));
}
public static TextElementEnumerator GetTextElementEnumerator(string str)
{
return GetTextElementEnumerator(str, 0);
}
public static TextElementEnumerator GetTextElementEnumerator(string str, int index)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
if (index < 0 || index > len)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
return new TextElementEnumerator(str, index, len);
}
/// <summary>
/// Returns the indices of each base character or properly formed surrogate
/// pair within the str. It recognizes a base character plus one or more
/// combining characters or a properly formed surrogate pair as a text
/// element and returns the index of the base character or high surrogate.
/// Each index is the beginning of a text element within a str. The length
/// of each element is easily computed as the difference between successive
/// indices. The length of the array will always be less than or equal to
/// the length of the str. For example, given the str
/// \u4f00\u302a\ud800\udc00\u4f01, this method would return the indices:
/// 0, 2, 4.
/// </summary>
public static int[] ParseCombiningCharacters(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len)
{
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, 0, returnArray, 0, resultCount);
return (returnArray);
}
return result;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class tk2dSpriteColliderIsland
{
public bool connected = true;
public Vector2[] points;
public bool IsValid()
{
if (connected)
{
return points.Length >= 3;
}
else
{
return points.Length >= 2;
}
}
public void CopyFrom(tk2dSpriteColliderIsland src)
{
connected = src.connected;
points = new Vector2[src.points.Length];
for (int i = 0; i < points.Length; ++i)
points[i] = src.points[i];
}
public bool CompareTo(tk2dSpriteColliderIsland src)
{
if (connected != src.connected) return false;
if (points.Length != src.points.Length) return false;
for (int i = 0; i < points.Length; ++i)
if (points[i] != src.points[i]) return false;
return true;
}
}
[System.Serializable]
public class tk2dSpriteCollectionDefinition
{
public enum Anchor
{
UpperLeft,
UpperCenter,
UpperRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
LowerLeft,
LowerCenter,
LowerRight,
Custom
}
public enum Pad
{
Default,
BlackZeroAlpha,
Extend,
TileXY,
}
public enum ColliderType
{
UserDefined, // don't try to create or destroy anything
ForceNone, // nothing will be created, if something exists, it will be destroyed
BoxTrimmed, // box, trimmed to cover visible region
BoxCustom, // box, with custom values provided by user
Polygon, // polygon, can be concave
}
public enum PolygonColliderCap
{
None,
FrontAndBack,
Front,
Back,
}
public enum ColliderColor
{
Default, // default unity color scheme
Red,
White,
Black
}
public enum Source
{
Sprite,
SpriteSheet,
Font
}
public enum DiceFilter
{
Complete,
SolidOnly,
TransparentOnly,
}
public string name = "";
public bool disableTrimming = false;
public bool additive = false;
public Vector3 scale = new Vector3(1,1,1);
public Texture2D texture = null;
[System.NonSerialized]
public Texture2D thumbnailTexture;
public int materialId = 0;
public Anchor anchor = Anchor.MiddleCenter;
public float anchorX, anchorY;
public Object overrideMesh;
public bool doubleSidedSprite = false;
public bool customSpriteGeometry = false;
public tk2dSpriteColliderIsland[] geometryIslands = new tk2dSpriteColliderIsland[0];
public bool dice = false;
public int diceUnitX = 64;
public int diceUnitY = 64;
public DiceFilter diceFilter = DiceFilter.Complete;
public Pad pad = Pad.Default;
public int extraPadding = 0; // default
public Source source = Source.Sprite;
public bool fromSpriteSheet = false;
public bool hasSpriteSheetId = false;
public int spriteSheetId = 0;
public int spriteSheetX = 0, spriteSheetY = 0;
public bool extractRegion = false;
public int regionX, regionY, regionW, regionH;
public int regionId;
public ColliderType colliderType = ColliderType.UserDefined;
public Vector2 boxColliderMin, boxColliderMax;
public tk2dSpriteColliderIsland[] polyColliderIslands;
public PolygonColliderCap polyColliderCap = PolygonColliderCap.FrontAndBack;
public bool colliderConvex = false;
public bool colliderSmoothSphereCollisions = false;
public ColliderColor colliderColor = ColliderColor.Default;
public List<tk2dSpriteDefinition.AttachPoint> attachPoints = new List<tk2dSpriteDefinition.AttachPoint>();
public void CopyFrom(tk2dSpriteCollectionDefinition src)
{
name = src.name;
disableTrimming = src.disableTrimming;
additive = src.additive;
scale = src.scale;
texture = src.texture;
materialId = src.materialId;
anchor = src.anchor;
anchorX = src.anchorX;
anchorY = src.anchorY;
overrideMesh = src.overrideMesh;
doubleSidedSprite = src.doubleSidedSprite;
customSpriteGeometry = src.customSpriteGeometry;
geometryIslands = src.geometryIslands;
dice = src.dice;
diceUnitX = src.diceUnitX;
diceUnitY = src.diceUnitY;
diceFilter = src.diceFilter;
pad = src.pad;
source = src.source;
fromSpriteSheet = src.fromSpriteSheet;
hasSpriteSheetId = src.hasSpriteSheetId;
spriteSheetX = src.spriteSheetX;
spriteSheetY = src.spriteSheetY;
spriteSheetId = src.spriteSheetId;
extractRegion = src.extractRegion;
regionX = src.regionX;
regionY = src.regionY;
regionW = src.regionW;
regionH = src.regionH;
regionId = src.regionId;
colliderType = src.colliderType;
boxColliderMin = src.boxColliderMin;
boxColliderMax = src.boxColliderMax;
polyColliderCap = src.polyColliderCap;
colliderColor = src.colliderColor;
colliderConvex = src.colliderConvex;
colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions;
extraPadding = src.extraPadding;
if (src.polyColliderIslands != null)
{
polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length];
for (int i = 0; i < polyColliderIslands.Length; ++i)
{
polyColliderIslands[i] = new tk2dSpriteColliderIsland();
polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]);
}
}
else
{
polyColliderIslands = new tk2dSpriteColliderIsland[0];
}
if (src.geometryIslands != null)
{
geometryIslands = new tk2dSpriteColliderIsland[src.geometryIslands.Length];
for (int i = 0; i < geometryIslands.Length; ++i)
{
geometryIslands[i] = new tk2dSpriteColliderIsland();
geometryIslands[i].CopyFrom(src.geometryIslands[i]);
}
}
else
{
geometryIslands = new tk2dSpriteColliderIsland[0];
}
attachPoints = new List<tk2dSpriteDefinition.AttachPoint>(src.attachPoints.Count);
foreach (tk2dSpriteDefinition.AttachPoint srcAp in src.attachPoints) {
tk2dSpriteDefinition.AttachPoint ap = new tk2dSpriteDefinition.AttachPoint();
ap.CopyFrom(srcAp);
attachPoints.Add(ap);
}
}
public void Clear()
{
// Reinitialize
var tmpVar = new tk2dSpriteCollectionDefinition();
CopyFrom(tmpVar);
}
public bool CompareTo(tk2dSpriteCollectionDefinition src)
{
if (name != src.name) return false;
if (additive != src.additive) return false;
if (scale != src.scale) return false;
if (texture != src.texture) return false;
if (materialId != src.materialId) return false;
if (anchor != src.anchor) return false;
if (anchorX != src.anchorX) return false;
if (anchorY != src.anchorY) return false;
if (overrideMesh != src.overrideMesh) return false;
if (dice != src.dice) return false;
if (diceUnitX != src.diceUnitX) return false;
if (diceUnitY != src.diceUnitY) return false;
if (diceFilter != src.diceFilter) return false;
if (pad != src.pad) return false;
if (extraPadding != src.extraPadding) return false;
if (doubleSidedSprite != src.doubleSidedSprite) return false;
if (customSpriteGeometry != src.customSpriteGeometry) return false;
if (geometryIslands != src.geometryIslands) return false;
if (geometryIslands != null && src.geometryIslands != null)
{
if (geometryIslands.Length != src.geometryIslands.Length) return false;
for (int i = 0; i < geometryIslands.Length; ++i)
if (!geometryIslands[i].CompareTo(src.geometryIslands[i])) return false;
}
if (source != src.source) return false;
if (fromSpriteSheet != src.fromSpriteSheet) return false;
if (hasSpriteSheetId != src.hasSpriteSheetId) return false;
if (spriteSheetId != src.spriteSheetId) return false;
if (spriteSheetX != src.spriteSheetX) return false;
if (spriteSheetY != src.spriteSheetY) return false;
if (extractRegion != src.extractRegion) return false;
if (regionX != src.regionX) return false;
if (regionY != src.regionY) return false;
if (regionW != src.regionW) return false;
if (regionH != src.regionH) return false;
if (regionId != src.regionId) return false;
if (colliderType != src.colliderType) return false;
if (boxColliderMin != src.boxColliderMin) return false;
if (boxColliderMax != src.boxColliderMax) return false;
if (polyColliderIslands != src.polyColliderIslands) return false;
if (polyColliderIslands != null && src.polyColliderIslands != null)
{
if (polyColliderIslands.Length != src.polyColliderIslands.Length) return false;
for (int i = 0; i < polyColliderIslands.Length; ++i)
if (!polyColliderIslands[i].CompareTo(src.polyColliderIslands[i])) return false;
}
if (polyColliderCap != src.polyColliderCap) return false;
if (colliderColor != src.colliderColor) return false;
if (colliderSmoothSphereCollisions != src.colliderSmoothSphereCollisions) return false;
if (colliderConvex != src.colliderConvex) return false;
if (attachPoints.Count != src.attachPoints.Count) return false;
for (int i = 0; i < attachPoints.Count; ++i) {
if (!attachPoints[i].CompareTo(src.attachPoints[i])) return false;
}
return true;
}
}
[System.Serializable]
public class tk2dSpriteCollectionDefault
{
public bool additive = false;
public Vector3 scale = new Vector3(1,1,1);
public tk2dSpriteCollectionDefinition.Anchor anchor = tk2dSpriteCollectionDefinition.Anchor.MiddleCenter;
public tk2dSpriteCollectionDefinition.Pad pad = tk2dSpriteCollectionDefinition.Pad.Default;
public tk2dSpriteCollectionDefinition.ColliderType colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined;
}
[System.Serializable]
public class tk2dSpriteSheetSource
{
public enum Anchor
{
UpperLeft,
UpperCenter,
UpperRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
LowerLeft,
LowerCenter,
LowerRight,
}
public enum SplitMethod
{
UniformDivision,
}
public Texture2D texture;
public int tilesX, tilesY;
public int numTiles = 0;
public Anchor anchor = Anchor.MiddleCenter;
public tk2dSpriteCollectionDefinition.Pad pad = tk2dSpriteCollectionDefinition.Pad.Default;
public Vector3 scale = new Vector3(1,1,1);
public bool additive = false;
// version 1
public bool active = false;
public int tileWidth, tileHeight;
public int tileMarginX, tileMarginY;
public int tileSpacingX, tileSpacingY;
public SplitMethod splitMethod = SplitMethod.UniformDivision;
public int version = 0;
public const int CURRENT_VERSION = 1;
public tk2dSpriteCollectionDefinition.ColliderType colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined;
public void CopyFrom(tk2dSpriteSheetSource src)
{
texture = src.texture;
tilesX = src.tilesX;
tilesY = src.tilesY;
numTiles = src.numTiles;
anchor = src.anchor;
pad = src.pad;
scale = src.scale;
colliderType = src.colliderType;
version = src.version;
active = src.active;
tileWidth = src.tileWidth;
tileHeight = src.tileHeight;
tileSpacingX = src.tileSpacingX;
tileSpacingY = src.tileSpacingY;
tileMarginX = src.tileMarginX;
tileMarginY = src.tileMarginY;
splitMethod = src.splitMethod;
}
public bool CompareTo(tk2dSpriteSheetSource src)
{
if (texture != src.texture) return false;
if (tilesX != src.tilesX) return false;
if (tilesY != src.tilesY) return false;
if (numTiles != src.numTiles) return false;
if (anchor != src.anchor) return false;
if (pad != src.pad) return false;
if (scale != src.scale) return false;
if (colliderType != src.colliderType) return false;
if (version != src.version) return false;
if (active != src.active) return false;
if (tileWidth != src.tileWidth) return false;
if (tileHeight != src.tileHeight) return false;
if (tileSpacingX != src.tileSpacingX) return false;
if (tileSpacingY != src.tileSpacingY) return false;
if (tileMarginX != src.tileMarginX) return false;
if (tileMarginY != src.tileMarginY) return false;
if (splitMethod != src.splitMethod) return false;
return true;
}
public string Name { get { return texture != null?texture.name:"New Sprite Sheet"; } }
}
[System.Serializable]
public class tk2dSpriteCollectionFont
{
public bool active = false;
public TextAsset bmFont;
public Texture2D texture;
public bool dupeCaps = false; // duplicate lowercase into uc, or vice-versa, depending on which exists
public bool flipTextureY = false;
public int charPadX = 0;
public tk2dFontData data;
public tk2dFont editorData;
public int materialId;
public bool useGradient = false;
public Texture2D gradientTexture = null;
public int gradientCount = 1;
public void CopyFrom(tk2dSpriteCollectionFont src)
{
active = src.active;
bmFont = src.bmFont;
texture = src.texture;
dupeCaps = src.dupeCaps;
flipTextureY = src.flipTextureY;
charPadX = src.charPadX;
data = src.data;
editorData = src.editorData;
materialId = src.materialId;
gradientCount = src.gradientCount;
gradientTexture = src.gradientTexture;
useGradient = src.useGradient;
}
public string Name
{
get
{
if (bmFont == null || texture == null)
return "Empty";
else
{
if (data == null)
return bmFont.name + " (Inactive)";
else
return bmFont.name;
}
}
}
public bool InUse
{
get { return active && bmFont != null && texture != null && data != null && editorData != null; }
}
}
[System.Serializable]
public class tk2dSpriteCollectionPlatform
{
public string name = "";
public tk2dSpriteCollection spriteCollection = null;
public bool Valid { get { return name.Length > 0 && spriteCollection != null; } }
public void CopyFrom(tk2dSpriteCollectionPlatform source)
{
name = source.name;
spriteCollection = source.spriteCollection;
}
}
[AddComponentMenu("2D Toolkit/Backend/tk2dSpriteCollection")]
public class tk2dSpriteCollection : MonoBehaviour
{
public const int CURRENT_VERSION = 4;
public enum NormalGenerationMode
{
None,
NormalsOnly,
NormalsAndTangents,
};
// Deprecated fields
[SerializeField] private tk2dSpriteCollectionDefinition[] textures;
[SerializeField] private Texture2D[] textureRefs;
public Texture2D[] DoNotUse__TextureRefs { get { return textureRefs; } set { textureRefs = value; } } // Don't use this for anything. Except maybe in tk2dSpriteCollectionBuilderDeprecated...
// new method
public tk2dSpriteSheetSource[] spriteSheets;
public tk2dSpriteCollectionFont[] fonts;
public tk2dSpriteCollectionDefault defaults;
// platforms
public List<tk2dSpriteCollectionPlatform> platforms = new List<tk2dSpriteCollectionPlatform>();
public bool managedSpriteCollection = false; // true when generated and managed by system, eg. platform specific data
public bool HasPlatformData { get { return platforms.Count > 1; } }
public bool loadable = false;
public AtlasFormat atlasFormat = AtlasFormat.UnityTexture;
public int maxTextureSize = 2048;
public bool forceTextureSize = false;
public int forcedTextureWidth = 2048;
public int forcedTextureHeight = 2048;
public enum TextureCompression
{
Uncompressed,
Reduced16Bit,
Compressed,
Dithered16Bit_Alpha,
Dithered16Bit_NoAlpha,
}
public enum AtlasFormat {
UnityTexture, // Normal Unity texture
Png,
}
public TextureCompression textureCompression = TextureCompression.Uncompressed;
public int atlasWidth, atlasHeight;
public bool forceSquareAtlas = false;
public float atlasWastage;
public bool allowMultipleAtlases = false;
public bool removeDuplicates = true;
public tk2dSpriteCollectionDefinition[] textureParams;
public tk2dSpriteCollectionData spriteCollection;
public bool premultipliedAlpha = false;
public Material[] altMaterials;
public Material[] atlasMaterials;
public Texture2D[] atlasTextures;
public TextAsset[] atlasTextureFiles = new TextAsset[0];
[SerializeField] private bool useTk2dCamera = false;
[SerializeField] private int targetHeight = 640;
[SerializeField] private float targetOrthoSize = 10.0f;
// New method of storing sprite size
public tk2dSpriteCollectionSize sizeDef = tk2dSpriteCollectionSize.Default();
public float globalScale = 1.0f;
public float globalTextureRescale = 1.0f;
// Remember test data for attach points
[System.Serializable]
public class AttachPointTestSprite {
public string attachPointName = "";
public tk2dSpriteCollectionData spriteCollection = null;
public int spriteId = -1;
public bool CompareTo(AttachPointTestSprite src) {
return src.attachPointName == attachPointName && src.spriteCollection == spriteCollection && src.spriteId == spriteId;
}
public void CopyFrom(AttachPointTestSprite src) {
attachPointName = src.attachPointName;
spriteCollection = src.spriteCollection;
spriteId = src.spriteId;
}
}
public List<AttachPointTestSprite> attachPointTestSprites = new List<AttachPointTestSprite>();
// Texture settings
[SerializeField]
private bool pixelPerfectPointSampled = false; // obsolete
public FilterMode filterMode = FilterMode.Bilinear;
public TextureWrapMode wrapMode = TextureWrapMode.Clamp;
public bool userDefinedTextureSettings = false;
public bool mipmapEnabled = false;
public int anisoLevel = 1;
// Starts off with Unity Physics 3D for current platforms
public tk2dSpriteDefinition.PhysicsEngine physicsEngine = tk2dSpriteDefinition.PhysicsEngine.Physics3D;
public float physicsDepth = 0.1f;
public bool disableTrimming = false;
public bool disableRotation = false;
public NormalGenerationMode normalGenerationMode = NormalGenerationMode.None;
public int padAmount = -1; // default
public bool autoUpdate = true;
public float editorDisplayScale = 1.0f;
public int version = 0;
public string assetName = "";
// Fix up upgraded data structures
public void Upgrade()
{
if (version == CURRENT_VERSION)
return;
Debug.Log("SpriteCollection '" + this.name + "' - Upgraded from version " + version.ToString());
if (version == 0)
{
if (pixelPerfectPointSampled)
filterMode = FilterMode.Point;
else
filterMode = FilterMode.Bilinear;
// don't bother messing about with user settings
// on old atlases
userDefinedTextureSettings = true;
}
if (version < 3)
{
if (textureRefs != null && textureParams != null && textureRefs.Length == textureParams.Length)
{
for (int i = 0; i < textureRefs.Length; ++i)
textureParams[i].texture = textureRefs[i];
textureRefs = null;
}
}
if (version < 4) {
sizeDef.CopyFromLegacy( useTk2dCamera, targetOrthoSize, targetHeight );
}
version = CURRENT_VERSION;
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Billing
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Billing client provides access to billing resources for Azure
/// Web-Direct subscriptions. Other subscription types which were not
/// purchased directly through the Azure web portal are not supported
/// through this preview API.
/// </summary>
public partial class BillingClient : ServiceClient<BillingClient>, IBillingClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Version of the API to be used with the client request. The current version
/// is 2017-02-27-preview.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Azure Subscription ID.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IInvoicesOperations.
/// </summary>
public virtual IInvoicesOperations Invoices { get; private set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Initializes a new instance of the BillingClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BillingClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the BillingClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected BillingClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the BillingClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected BillingClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BillingClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected BillingClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the BillingClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BillingClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BillingClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BillingClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BillingClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BillingClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the BillingClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BillingClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Invoices = new InvoicesOperations(this);
Operations = new Operations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2017-02-27-preview";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
using Odachi.CodeModel.Description;
using Odachi.CodeModel.Mapping;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Odachi.CodeModel.Builders.Abstraction;
namespace Odachi.CodeModel.Builders
{
public class PackageContext
{
public PackageContext()
{
GlobalDescriptor = new DefaultGlobalDescriptor();
ObjectDescriptors = new List<IObjectDescriptor>() { new DefaultObjectDescriptor() };
ServiceDescriptors = new List<IServiceDescriptor>() { new DefaultServiceDescriptor() };
ConstantDescriptors = new List<IConstantDescriptor>() { new DefaultConstantDescriptor() };
FieldDescriptors = new List<IFieldDescriptor>() { new DefaultFieldDescriptor() };
MethodDescriptors = new List<IMethodDescriptor>() { new DefaultMethodDescriptor() };
ParameterDescriptors = new List<IParameterDescriptor>() { new DefaultParameterDescriptor() };
EnumDescriptors = new List<IEnumDescriptor>() { new DefaultEnumDescriptor() };
EnumItemDescriptors = new List<IEnumItemDescriptor>() { new DefaultEnumItemDescriptor() };
TypeReferenceDescriptors = new List<ITypeReferenceDescriptor>() { new DefaultTypeReferenceDescriptor() };
TypeMapper = new TypeMapper();
ModulePath = ".";
}
public PackageContext(PackageContext parentContext, string newModulePath)
{
if (parentContext == null)
throw new ArgumentNullException(nameof(parentContext));
if (string.IsNullOrEmpty(newModulePath))
throw new ArgumentNullException(nameof(newModulePath));
GlobalDescriptor = parentContext.GlobalDescriptor;
ObjectDescriptors = parentContext.ObjectDescriptors;
ServiceDescriptors = parentContext.ServiceDescriptors;
ConstantDescriptors = parentContext.ConstantDescriptors;
FieldDescriptors = parentContext.FieldDescriptors;
MethodDescriptors = parentContext.MethodDescriptors;
ParameterDescriptors = parentContext.ParameterDescriptors;
EnumDescriptors = parentContext.EnumDescriptors;
EnumItemDescriptors = parentContext.EnumItemDescriptors;
TypeReferenceDescriptors = parentContext.TypeReferenceDescriptors;
TypeMapper = parentContext.TypeMapper;
ModulePath = newModulePath;
}
public IGlobalDescriptor GlobalDescriptor { get; }
public IList<IObjectDescriptor> ObjectDescriptors { get; }
public IList<IServiceDescriptor> ServiceDescriptors { get; }
public IList<IConstantDescriptor> ConstantDescriptors { get; }
public IList<IFieldDescriptor> FieldDescriptors { get; }
public IList<IMethodDescriptor> MethodDescriptors { get; }
public IList<IParameterDescriptor> ParameterDescriptors { get; }
public IList<IEnumDescriptor> EnumDescriptors { get; }
public IList<IEnumItemDescriptor> EnumItemDescriptors { get; }
public IList<ITypeReferenceDescriptor> TypeReferenceDescriptors { get; }
public TypeMapper TypeMapper { get; }
public string ModulePath { get; }
public string MapPath(string path)
{
return Path.Combine(ModulePath, path);
}
}
public class PackageBuilder : FragmentBuilderBase<PackageBuilder, Package>
{
private PackageBuilder(PackageBuilder parent, PackageContext context)
: base(context, parent.Name)
{
if (parent == null)
throw new ArgumentNullException(nameof(parent));
Enums = parent.Enums;
Objects = parent.Objects;
Services = parent.Services;
}
public PackageBuilder(string name)
: base(new PackageContext(), name)
{
Enums = new List<EnumBuilder>();
Objects = new List<ObjectBuilder>();
Services = new List<ServiceBuilder>();
}
public IList<EnumBuilder> Enums { get; set; }
public IList<ObjectBuilder> Objects { get; set; }
public IList<ServiceBuilder> Services { get; set; }
public PackageBuilder Folder(string name, Action<PackageBuilder> configure)
{
var innerBuilder = new PackageBuilder(this, new PackageContext(Context, Context.MapPath(name)));
configure(innerBuilder);
return this;
}
public PackageBuilder Enum(string name, Action<EnumBuilder> configure)
{
return Enum(name, null, configure);
}
public PackageBuilder Enum(string name, Type type, Action<EnumBuilder> configure)
{
var enumBuilder = new EnumBuilder(Context, name, source: type);
configure(enumBuilder);
Enums.Add(enumBuilder);
return this;
}
public PackageBuilder Object(string name, Action<ObjectBuilder> configure)
{
return Object(name, null, null, configure);
}
public PackageBuilder Object(string name, Type type, Action<ObjectBuilder> configure)
{
return Object(name, null, type, configure);
}
public PackageBuilder Object(string name, IReadOnlyList<string> genericArguments, Action<ObjectBuilder> configure)
{
return Object(name, genericArguments, null, configure);
}
public PackageBuilder Object(string name, IReadOnlyList<string> genericArguments, Type type, Action<ObjectBuilder> configure)
{
var objectBuilder = new ObjectBuilder(Context, name, genericArguments, source: type);
configure(objectBuilder);
Objects.Add(objectBuilder);
return this;
}
public PackageBuilder Service(string name, Action<ServiceBuilder> configure)
{
return Service(name, null, configure);
}
public PackageBuilder Service(string name, Type type, Action<ServiceBuilder> configure)
{
var serviceBuilder = new ServiceBuilder(Context, name, source: type);
configure(serviceBuilder);
Services.Add(serviceBuilder);
return this;
}
public PackageBuilder AutoRegister<TResult>(Func<PackageBuilder, Type, TResult> action)
{
return AutoRegister((p, t) =>
{
action(p, t);
});
}
public PackageBuilder AutoRegister(Action<PackageBuilder, Type> action)
{
Context.TypeMapper.OnUnresolvedType += (sender, args) =>
{
action(this, args.Type);
};
return this;
}
public PackageBuilder AutoRegister<TResult>(Func<Type, bool> condition, Func<PackageBuilder, Type, TResult> action)
{
return AutoRegister(condition, (p, t) =>
{
action(p, t);
});
}
public PackageBuilder AutoRegister(Func<Type, bool> condition, Action<PackageBuilder, Type> action)
{
Context.TypeMapper.OnUnresolvedType += (sender, args) =>
{
if (!condition(args.Type))
return;
action(this, args.Type);
};
return this;
}
public PackageBuilder Map<T>(TypeDefinition definition)
{
return Map(typeof(T), definition);
}
public PackageBuilder Map(Type type, TypeDefinition definition)
{
Context.TypeMapper.Register(type, definition);
return this;
}
public PackageBuilder MapFragment<T>(string moduleName, string fragmentName)
{
return MapFragment(typeof(T), moduleName, fragmentName);
}
public PackageBuilder MapFragment(Type type, string moduleName, string fragmentName)
{
var genericArgumentDefinition = type.GetGenericArguments().Select(a => new GenericArgumentDefinition(a.Name)).ToArray();
return Map(type, new FragmentTypeDefinition(Context.MapPath(moduleName), fragmentName, genericArgumentDefinition));
}
public override Package Build()
{
var result = new Package()
{
Name = Name,
};
int enumIndex = 0;
int objectIndex = 0;
int serviceIndex = 0;
while (enumIndex < Enums.Count || objectIndex < Objects.Count || serviceIndex < Services.Count)
{
for (; enumIndex < Enums.Count; enumIndex++)
{
var @enum = Enums[enumIndex];
result.Enums.Add(@enum.Build());
}
for (; objectIndex < Objects.Count; objectIndex++)
{
var @object = Objects[objectIndex];
result.Objects.Add(@object.Build());
}
for (; serviceIndex < Services.Count; serviceIndex++)
{
var service = Services[serviceIndex];
result.Services.Add(service.Build());
}
}
foreach (var hint in Hints)
{
result.Hints.Add(hint);
}
return result;
}
#region Static members
public static Package Build(string name, Action<PackageBuilder> configure)
{
var builder = new PackageBuilder(name);
configure(builder);
return builder.Build();
}
#endregion
}
public static class PackageBuilderExtensions
{
/// <summary>
/// Shortcut for creating a module with single enum fragment from specified .NET type.
/// </summary>
public static PackageBuilder Module_Enum<T>(this PackageBuilder builder, Action<EnumBuilder> configure)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (configure == null)
throw new ArgumentNullException(nameof(configure));
return Module_Enum(builder, typeof(T), configure);
}
/// <summary>
/// Shortcut for creating a module with single enum fragment from specified .NET type.
/// </summary>
public static PackageBuilder Module_Enum(this PackageBuilder builder, Type enumType, Action<EnumBuilder> configure)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.GetTypeInfo().IsEnum)
throw new ArgumentException($"Parameter `enumType` must be enum type");
if (configure == null)
throw new ArgumentNullException(nameof(configure));
var fragmentName = builder.Context.GlobalDescriptor.GetFragmentName(builder.Context, enumType);
var moduleName = builder.Context.GlobalDescriptor.GetModuleName(builder.Context, fragmentName);
return builder
.MapFragment(enumType, moduleName, fragmentName)
.Enum(fragmentName, enumType, configure);
}
/// <summary>
/// Shortcut for creating a module with single enum fragment and all its enum items from specified .NET type.
/// </summary>
public static PackageBuilder Module_Enum_Default<T>(this PackageBuilder builder, Action<EnumBuilder> configure = null)
where T : struct
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
return Module_Enum_Default(builder, typeof(T), configure: configure);
}
/// <summary>
/// Shortcut for creating a module with single enum fragment and all its enum items from specified .NET type.
/// </summary>
public static PackageBuilder Module_Enum_Default(this PackageBuilder builder, Type enumType, Action<EnumBuilder> configure = null)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.GetTypeInfo().IsEnum)
throw new ArgumentException($"Parameter `enumType` must be enum type");
return builder.Module_Enum(enumType, enumBuilder =>
{
foreach (var item in Enum.GetValues(enumType))
{
enumBuilder.Item(item.ToString(), Convert.ToInt32(item));
}
configure?.Invoke(enumBuilder);
});
}
/// <summary>
/// Shortcut for creating a module with single object fragment from specified .NET type.
/// </summary>
public static PackageBuilder Module_Object<T>(this PackageBuilder builder, Action<ObjectBuilder> configure)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (configure == null)
throw new ArgumentNullException(nameof(configure));
return Module_Object(builder, typeof(T), configure);
}
/// <summary>
/// Shortcut for creating a module with single object fragment from specified .NET type.
/// </summary>
public static PackageBuilder Module_Object(this PackageBuilder builder, Type objectType, Action<ObjectBuilder> configure)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (objectType == null)
throw new ArgumentNullException(nameof(objectType));
if (configure == null)
throw new ArgumentNullException(nameof(configure));
var objectTypeInfo = objectType.GetTypeInfo();
var fragmentName = builder.Context.GlobalDescriptor.GetFragmentName(builder.Context, objectType);
var moduleName = builder.Context.GlobalDescriptor.GetModuleName(builder.Context, fragmentName);
var genericArguments = objectTypeInfo.ContainsGenericParameters ? objectTypeInfo.GenericTypeParameters.Select(p => p.Name).ToArray() : null;
return builder
.MapFragment(objectType, moduleName, fragmentName)
.Object(fragmentName, genericArguments, objectType, configure);
}
/// <summary>
/// Shortcut for creating a module with single object fragment and all its fields and properties from specified .NET type.
/// </summary>
public static PackageBuilder Module_Object_Default<T>(this PackageBuilder builder, Action<ObjectBuilder> configure = null)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
return Module_Object_Default(builder, typeof(T), configure: configure);
}
/// <summary>
/// Shortcut for creating a module with single object fragment and all its fields and properties from specified .NET type.
/// </summary>
public static PackageBuilder Module_Object_Default(this PackageBuilder builder, Type objectType, Action<ObjectBuilder> configure = null)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (objectType == null)
throw new ArgumentNullException(nameof(objectType));
return builder.Module_Object(objectType, objectBuilder =>
{
var members = objectType.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var member in members)
{
if (member is FieldInfo field)
{
if (field.IsLiteral && !field.IsInitOnly)
{
var value = field.GetRawConstantValue();
objectBuilder.Constant(field.Name, field.FieldType, value, (objectType, field), constantBuilder =>
{
constantBuilder.Type.IsNullable = value == null;
});
}
else if (!field.IsStatic)
{
objectBuilder.Field(field.Name, field.FieldType, (objectType, field));
}
}
else if (member is PropertyInfo property)
{
if (!(property.GetMethod?.IsStatic ?? false) && !(property.SetMethod?.IsStatic ?? false))
{
objectBuilder.Field(property.Name, property.PropertyType, (objectType, property));
}
}
}
configure?.Invoke(objectBuilder);
});
}
/// <summary>
/// Shortcut for creating a module with single service fragment from specified .NET type.
/// </summary>
public static PackageBuilder Module_Service<T>(this PackageBuilder builder, Action<ServiceBuilder> configure)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (configure == null)
throw new ArgumentNullException(nameof(configure));
return Module_Service(builder, typeof(T), configure);
}
/// <summary>
/// Shortcut for creating a module with single service fragment from specified .NET type.
/// </summary>
public static PackageBuilder Module_Service(this PackageBuilder builder, Type objectType, Action<ServiceBuilder> configure)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (objectType == null)
throw new ArgumentNullException(nameof(objectType));
if (configure == null)
throw new ArgumentNullException(nameof(configure));
var fragmentName = builder.Context.GlobalDescriptor.GetFragmentName(builder.Context, objectType);
var moduleName = builder.Context.GlobalDescriptor.GetModuleName(builder.Context, fragmentName);
return builder
.MapFragment(objectType, moduleName, fragmentName)
.Service(fragmentName, objectType, configure);
}
/// <summary>
/// Shortcut for creating a module with single service fragment and all its fields and properties from specified .NET type.
/// </summary>
public static PackageBuilder Module_Service_Default<T>(this PackageBuilder builder, Action<ServiceBuilder> configure = null)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
return Module_Service_Default(builder, typeof(T), configure: configure);
}
/// <summary>
/// Shortcut for creating a module with single service fragment and all its fields and properties from specified .NET type.
/// </summary>
public static PackageBuilder Module_Service_Default(this PackageBuilder builder, Type objectType, Action<ServiceBuilder> configure = null)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
if (objectType == null)
throw new ArgumentNullException(nameof(objectType));
return builder.Module_Service(objectType, serviceBuilder =>
{
var members = objectType.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var member in members)
{
// ignore GetType, GetHashCode, Equals, ToString
if (member.DeclaringType == typeof(object))
continue;
if (member is FieldInfo field)
{
if (field.IsLiteral && !field.IsInitOnly)
{
var value = field.GetRawConstantValue();
serviceBuilder.Constant(field.Name, field.FieldType, value, (objectType, field), constantBuilder =>
{
constantBuilder.Type.IsNullable = value == null;
});
}
}
else if (member is MethodInfo method)
{
if (!method.IsStatic)
{
serviceBuilder.Method(method.Name, method.ReturnType, (objectType, method), methodBuilder =>
{
foreach (var parameter in method.GetParameters())
{
methodBuilder.Parameter(parameter.Name, parameter.ParameterType, parameter);
}
});
}
}
}
configure?.Invoke(serviceBuilder);
});
}
}
}
| |
// 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 AndNotDouble()
{
var test = new SimpleBinaryOpTest__AndNotDouble();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndNotDouble
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static SimpleBinaryOpTest__AndNotDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.AndNot(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.AndNot(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.AndNot(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.AndNot), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.AndNot), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.AndNot), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotDouble();
var result = Avx.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (((~BitConverter.DoubleToInt64Bits(left[0])) & BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (((~BitConverter.DoubleToInt64Bits(left[i])) & BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.AndNot)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System
{
/// <summary>Methods for parsing numbers and strings.</summary>
internal static class ParseNumbers
{
internal const int LeftAlign = 0x0001;
internal const int RightAlign = 0x0004;
internal const int PrefixSpace = 0x0008;
internal const int PrintSign = 0x0010;
internal const int PrintBase = 0x0020;
internal const int PrintAsI1 = 0x0040;
internal const int PrintAsI2 = 0x0080;
internal const int PrintAsI4 = 0x0100;
internal const int TreatAsUnsigned = 0x0200;
internal const int TreatAsI1 = 0x0400;
internal const int TreatAsI2 = 0x0800;
internal const int IsTight = 0x1000;
internal const int NoSpace = 0x2000;
internal const int PrintRadixBase = 0x4000;
private const int MinRadix = 2;
private const int MaxRadix = 36;
public static unsafe long StringToLong(ReadOnlySpan<char> s, int radix, int flags)
{
int pos = 0;
return StringToLong(s, radix, flags, ref pos);
}
public static long StringToLong(ReadOnlySpan<char> s, int radix, int flags, ref int currPos)
{
int i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
int r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
int length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
int sign = 1;
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
int grabNumbersStart = i;
long result = GrabLongs(r, s, ref i, (flags & TreatAsUnsigned) != 0);
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
//If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((ulong)result == 0x8000000000000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
throw new OverflowException(SR.Overflow_Int64);
if (r == 10)
{
result *= sign;
}
return result;
}
public static int StringToInt(ReadOnlySpan<char> s, int radix, int flags)
{
int pos = 0;
return StringToInt(s, radix, flags, ref pos);
}
public static int StringToInt(ReadOnlySpan<char> s, int radix, int flags, ref int currPos)
{
// They're requied to tell me where to start parsing.
int i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
int r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
int length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
int sign = 1;
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
// Consume the 0x if we're in an unknown base or in base-16.
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
int grabNumbersStart = i;
int result = GrabInts(r, s, ref i, ((flags & TreatAsUnsigned) != 0));
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
// If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((flags & TreatAsI1) != 0)
{
if ((uint)result > 0xFF)
throw new OverflowException(SR.Overflow_SByte);
}
else if ((flags & TreatAsI2) != 0)
{
if ((uint)result > 0xFFFF)
throw new OverflowException(SR.Overflow_Int16);
}
else if ((uint)result == 0x80000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
{
throw new OverflowException(SR.Overflow_Int32);
}
if (r == 10)
{
result *= sign;
}
return result;
}
public static string IntToString(int n, int radix, int width, char paddingChar, int flags)
{
Span<char> buffer;
unsafe
{
char* tmpBuffer = stackalloc char[66]; // Longest possible string length for an integer in binary notation with prefix
buffer = new Span<char>(tmpBuffer, 66);
}
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
// If the number is negative, make it positive and remember the sign.
// If the number is MIN_VALUE, this will still be negative, so we'll have to
// special case this later.
bool isNegative = false;
uint l;
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
l = (10 == radix) ? (uint)-n : (uint)n;
}
else
{
l = (uint)n;
}
// The conversion to a uint will sign extend the number. In order to ensure
// that we only get as many bits as we expect, we chop the number.
if ((flags & PrintAsI1) != 0)
{
l &= 0xFF;
}
else if ((flags & PrintAsI2) != 0)
{
l &= 0xFFFF;
}
// Special case the 0.
int index;
if (0 == l)
{
buffer[0] = '0';
index = 1;
}
else
{
index = 0;
for (int i = 0; i < buffer.Length; i++) // for(...;i<buffer.Length;...) loop instead of do{...}while(l!=0) to help JIT eliminate span bounds checks
{
uint div = l / (uint)radix; // TODO https://github.com/dotnet/coreclr/issues/3439
uint charVal = l - (div * (uint)radix);
l = div;
buffer[i] = (charVal < 10) ?
(char)(charVal + '0') :
(char)(charVal + 'a' - 10);
if (l == 0)
{
index = i + 1;
break;
}
}
Debug.Assert(l == 0, $"Expected {l} == 0");
}
// If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
}
if (10 == radix)
{
// If it was negative, append the sign, else if they requested, add the '+'.
// If they requested a leading space, put it on.
if (isNegative)
{
buffer[index++] = '-';
}
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
}
}
// Figure out the size of and allocate the resulting string
string result = string.FastAllocateString(Math.Max(width, index));
unsafe
{
// Put the characters into the string in reverse order.
// Fill the remaining space, if there is any, with the correct padding character.
fixed (char* resultPtr = result)
{
char* p = resultPtr;
int padding = result.Length - index;
if ((flags & LeftAlign) != 0)
{
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
}
else
{
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
}
Debug.Assert((p - resultPtr) == result.Length, $"Expected {p - resultPtr} == {result.Length}");
}
}
return result;
}
public static string LongToString(long n, int radix, int width, char paddingChar, int flags)
{
Span<char> buffer;
unsafe
{
char* tmpBuffer = stackalloc char[67]; // Longest possible string length for an integer in binary notation with prefix
buffer = new Span<char>(tmpBuffer, 67);
}
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
//If the number is negative, make it positive and remember the sign.
ulong ul;
bool isNegative = false;
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
ul = (10 == radix) ? (ulong)(-n) : (ulong)n;
}
else
{
ul = (ulong)n;
}
if ((flags & PrintAsI1) != 0)
{
ul = ul & 0xFF;
}
else if ((flags & PrintAsI2) != 0)
{
ul = ul & 0xFFFF;
}
else if ((flags & PrintAsI4) != 0)
{
ul = ul & 0xFFFFFFFF;
}
//Special case the 0.
int index;
if (0 == ul)
{
buffer[0] = '0';
index = 1;
}
else
{
index = 0;
for (int i = 0; i < buffer.Length; i++) // for loop instead of do{...}while(l!=0) to help JIT eliminate span bounds checks
{
ulong div = ul / (ulong)radix; // TODO https://github.com/dotnet/coreclr/issues/3439
int charVal = (int)(ul - (div * (ulong)radix));
ul = div;
buffer[i] = (charVal < 10) ?
(char)(charVal + '0') :
(char)(charVal + 'a' - 10);
if (ul == 0)
{
index = i + 1;
break;
}
}
Debug.Assert(ul == 0, $"Expected {ul} == 0");
}
//If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
else if ((flags & PrintRadixBase) != 0)
{
buffer[index++] = '#';
buffer[index++] = (char)((radix % 10) + '0');
buffer[index++] = (char)((radix / 10) + '0');
}
}
if (10 == radix)
{
//If it was negative, append the sign.
if (isNegative)
{
buffer[index++] = '-';
}
//else if they requested, add the '+';
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
//If they requested a leading space, put it on.
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
}
}
// Figure out the size of and allocate the resulting string
string result = string.FastAllocateString(Math.Max(width, index));
unsafe
{
// Put the characters into the string in reverse order.
// Fill the remaining space, if there is any, with the correct padding character.
fixed (char* resultPtr = result)
{
char* p = resultPtr;
int padding = result.Length - index;
if ((flags & LeftAlign) != 0)
{
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
}
else
{
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
}
Debug.Assert((p - resultPtr) == result.Length, $"Expected {p - resultPtr} == {result.Length}");
}
}
return result;
}
private static void EatWhiteSpace(ReadOnlySpan<char> s, ref int i)
{
int localIndex = i;
for (; localIndex < s.Length && char.IsWhiteSpace(s[localIndex]); localIndex++);
i = localIndex;
}
private static long GrabLongs(int radix, ReadOnlySpan<char> s, ref int i, bool isUnsigned)
{
ulong result = 0;
ulong maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = 0x7FFFFFFFFFFFFFFF / 10;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || ((long)result) < 0)
{
ThrowOverflowInt64Exception();
}
result = result * (ulong)radix + (ulong)value;
i++;
}
if ((long)result < 0 && result != 0x8000000000000000)
{
ThrowOverflowInt64Exception();
}
}
else
{
Debug.Assert(radix == 2 || radix == 8 || radix == 10 || radix == 16);
maxVal =
radix == 10 ? 0xffffffffffffffff / 10 :
radix == 16 ? 0xffffffffffffffff / 16 :
radix == 8 ? 0xffffffffffffffff / 8 :
0xffffffffffffffff / 2;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
{
ThrowOverflowUInt64Exception();
}
ulong temp = result * (ulong)radix + (ulong)value;
if (temp < result) // this means overflow as well
{
ThrowOverflowUInt64Exception();
}
result = temp;
i++;
}
}
return (long)result;
}
private static int GrabInts(int radix, ReadOnlySpan<char> s, ref int i, bool isUnsigned)
{
uint result = 0;
uint maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = (0x7FFFFFFF / 10);
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || (int)result < 0)
{
ThrowOverflowInt32Exception();
}
result = result * (uint)radix + (uint)value;
i++;
}
if ((int)result < 0 && result != 0x80000000)
{
ThrowOverflowInt32Exception();
}
}
else
{
Debug.Assert(radix == 2 || radix == 8 || radix == 10 || radix == 16);
maxVal =
radix == 10 ? 0xffffffff / 10 :
radix == 16 ? 0xffffffff / 16 :
radix == 8 ? 0xffffffff / 8 :
0xffffffff / 2;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
{
throw new OverflowException(SR.Overflow_UInt32);
}
uint temp = result * (uint)radix + (uint)value;
if (temp < result) // this means overflow as well
{
ThrowOverflowUInt32Exception();
}
result = temp;
i++;
}
}
return (int)result;
}
private static void ThrowOverflowInt32Exception() => throw new OverflowException(SR.Overflow_Int32);
private static void ThrowOverflowInt64Exception() => throw new OverflowException(SR.Overflow_Int64);
private static void ThrowOverflowUInt32Exception() => throw new OverflowException(SR.Overflow_UInt32);
private static void ThrowOverflowUInt64Exception() => throw new OverflowException(SR.Overflow_UInt64);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsDigit(char c, int radix, out int result)
{
int tmp;
if ((uint)(c - '0') <= 9)
{
result = tmp = c - '0';
}
else if ((uint)(c - 'A') <= 'Z' - 'A')
{
result = tmp = c - 'A' + 10;
}
else if ((uint)(c - 'a') <= 'z' - 'a')
{
result = tmp = c - 'a' + 10;
}
else
{
result = -1;
return false;
}
return tmp < radix;
}
}
}
| |
using System;
using System.Linq;
using Xunit;
using BitPaySDK;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using BitPaySDK.Exceptions;
using BitPaySDK.Models;
using BitPaySDK.Models.Bill;
using BitPaySDK.Models.Invoice;
using BitPaySDK.Models.Payout;
using BitPaySDK.Models.Wallet;
using Microsoft.Extensions.Configuration;
using Buyer = BitPaySDK.Models.Invoice.Buyer;
using InvoiceStatus = BitPaySDK.Models.Invoice.Status;
using BillStatus = BitPaySDK.Models.Bill.Status;
using PayoutStatus = BitPaySDK.Models.Payout.Status;
namespace BitPayXUnitTest
{
public class Tests
{
// This is the BitPay object we're going to use through all the tests
private BitPay _bitpay;
// The pairing code generated in your BitPay account -
// https://test.bitpay.com/dashboard/merchant/api-tokens
// This is the POS Pairing Code
private static readonly string PairingCode = "hyxq4Ew";
// Your favourite client name
private static readonly string ClientName = "BitPay .Net Client v2.2.1907 Tester on " + Environment.MachineName;
// Define the date range for fetching results during the test
private static DateTime today = DateTime.Now;
private static DateTime tomorrow = today.AddDays(1);
private static DateTime yesterday = today.AddDays(-1);
// Will store one of the generated invoices during the test
// so it can be paid manually in order to pass the ledger tests
public Tests()
{
// JSON minified with the BitPay configuration as in the required configuration file
// and parsed into a IConfiguration object
var json = "{\"BitPayConfiguration\":{\"Environment\":\"Test\",\"EnvConfig\":{\"Test\":{\"PrivateKeyPath\":\"sec/bitpay_test_private.key\",\"ApiTokens\":{\"merchant\":\"A4qqz5JXoK5TMi3hD8EfKNHJB2ybLgdYRkbZwZ5M9ZgT\",\"payout\":\"G4pfTiUU7967YJs7Z7n8e2SuQPa2abDTgFrjFB5ZFZsT\"}},\"Prod\":{\"PrivateKeyPath\":\"\",\"ApiTokens\":{\"merchant\":\"\"}}}}}";
var memoryJsonFile = new MemoryFileInfo("config.json", Encoding.UTF8.GetBytes(json), DateTimeOffset.Now);
var memoryFileProvider = new MockFileProvider(memoryJsonFile);
var configuration = new ConfigurationBuilder()
.AddJsonFile(memoryFileProvider, "config.json", false, false)
.Build();
// Initialize the BitPay object to be used in the following tests
// Initialize with IConfiguration object
// _bitpay = new BitPay(configuration);
// Initialize with separate variables
_bitpay = new BitPay(
Env.Test,
"/Users/antonio.buedo/Bitpay/Repos/csharp-bitpay-client/BitPayXUnitTest/bin/Debug/bitpay_private_test.key",
new Env.Tokens(){
Merchant = "EUxbieiBNDb6GCKq6WDoovWwWpkpE2PpP4tNo7mzCAk9",
Payout = "EUxbieiBNDb6GCKq6WDoovWwWpkpE2PpP4tNo7mzCAk9"
}
);
// ledgers require the Merchant Facade
if (!_bitpay.tokenExist(Facade.Merchant))
{
// get a pairing code for the merchant facade for this client
var pcode = _bitpay.RequestClientAuthorization(Facade.Merchant).Result;
/* We can't continue. Please make sure you write down this pairing code, then goto
your BitPay account in the API Tokens section
https://test.bitpay.com/dashboard/merchant/api-tokens
and paste it into the search field.
It should get you to a page to approve it. After you approve it, run the tests
again and they should pass.
*/
throw new BitPayException("Please approve the pairing code " + pcode + " in your account.");
}
// payouts require the Payout Facade
if (!_bitpay.tokenExist(Facade.Payout))
{
// get a pairing code for the payout facade for this client
var pcode = _bitpay.RequestClientAuthorization(Facade.Payout).Result;
/* We can't continue. Please make sure you write down this pairing code, then goto
your BitPay account in the API Tokens section
https://test.bitpay.com/dashboard/merchant/api-tokens
and paste it into the search field.
It should get you to a page to approve it. After you approve it, run the tests
again and they should pass.
*/
throw new BitPayException("Please approve the pairing code " + pcode + " in your account.");
}
}
[Fact]
public async Task TestShouldGetInvoiceId()
{
// create an invoice and make sure we receive an id - which means it has been successfully submitted
var invoice = new Invoice(30.0, Currency.USD);
var basicInvoice = await _bitpay.CreateInvoice(invoice);
Assert.NotNull(basicInvoice.Id);
}
[Fact]
public async Task testShouldCreateInvoiceBTC()
{
// create an invoice and make sure we receive an id - which means it has been successfully submitted
var invoice = new Invoice(30.0, Currency.USD);
invoice.PaymentCurrencies = new List<string>();
invoice.PaymentCurrencies.Add(Currency.BTC);
var basicInvoice = await _bitpay.CreateInvoice(invoice);
Assert.NotNull(basicInvoice.Id);
}
[Fact]
public async Task testShouldCreateInvoiceBCH()
{
// create an invoice and make sure we receive an id - which means it has been successfully submitted
var invoice = new Invoice(30.0, Currency.USD);
invoice.PaymentCurrencies = new List<string>();
invoice.PaymentCurrencies.Add(Currency.BCH);
var basicInvoice = await _bitpay.CreateInvoice(invoice);
Assert.NotNull(basicInvoice.Id);
}
[Fact]
public async Task testShouldCreateInvoiceETH()
{
// create an invoice and make sure we receive an id - which means it has been successfully submitted
var invoice = new Invoice(30.0, Currency.USD);
invoice.PaymentCurrencies = new List<string>();
invoice.PaymentCurrencies.Add(Currency.ETH);
var basicInvoice = await _bitpay.CreateInvoice(invoice);
Assert.NotNull(basicInvoice.Id);
}
[Fact]
public async Task TestShouldGetInvoiceUrl()
{
// create an invoice and make sure we receive an invoice url - which means we can check it online
var basicInvoice = await _bitpay.CreateInvoice(new Invoice(10.0, Currency.USD));
Assert.NotNull(basicInvoice.Url);
}
[Fact]
public async Task TestShouldGetInvoiceStatus()
{
// create an invoice and make sure we receive a correct invoice status (new)
var basicInvoice = await _bitpay.CreateInvoice(new Invoice(10.0, Currency.USD));
Assert.Equal(InvoiceStatus.New, basicInvoice.Status);
}
[Fact]
public async Task TestShouldCreateInvoiceOneTenthBtc()
{
// create an invoice and make sure we receive the correct price value back (under 1 BTC)
var invoice = await _bitpay.CreateInvoice(new Invoice(0.1, Currency.BTC));
Assert.Equal(0.1, invoice.Price);
}
[Fact]
public async Task TestShouldCreateInvoice100Usd()
{
// create an invoice and make sure we receive the correct price value back (USD)
var invoice = await _bitpay.CreateInvoice(new Invoice(100.0, Currency.USD));
Assert.Equal(100.0, invoice.Price);
}
[Fact]
public async Task TestShouldCreateInvoice100Eur()
{
// create an invoice and make sure we receive the correct price value back (EUR)
var invoice = await _bitpay.CreateInvoice(new Invoice(100.0, Currency.EUR));
Assert.Equal(100.0, invoice.Price);
}
[Fact]
public async Task TestShouldGetInvoice()
{
// create an invoice then retrieve it through the get method - they should match
var invoice = await _bitpay.CreateInvoice(new Invoice(100.0, Currency.EUR));
var retrievedInvoice = await _bitpay.GetInvoice(invoice.Id);
Assert.Equal(invoice.Id, retrievedInvoice.Id);
}
[Fact]
public async Task TestShouldCreateInvoiceWithAdditionalParams()
{
// create an invoice and make sure we receive the correct fields values back
var buyerData = new Buyer();
buyerData.Name = "Satoshi";
buyerData.Address1 = "street";
buyerData.Address2 = "911";
buyerData.Locality = "Washington";
buyerData.Region = "District of Columbia";
buyerData.PostalCode = "20000";
buyerData.Country = "USA";
// buyerData.Email = "";
// buyerData.Phone = "";
buyerData.Notify = true;
var invoice = new Invoice(100.0, Currency.USD)
{
Buyer = buyerData,
PosData = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
PaymentCurrencies = new List<string> {
Currency.BTC,
Currency.BCH
},
AcceptanceWindow = 480000,
FullNotifications = true,
// NotificationEmail = "",
NotificationUrl = "https://hookb.in/03EBRQJrzasGmGkNPNw9",
OrderId = "1234",
Physical = true,
// RedirectUrl = "",
TransactionSpeed = "high",
ItemCode = "bitcoindonation",
ItemDesc = "dhdhdfgh"
};
invoice = await _bitpay.CreateInvoice(invoice, Facade.Merchant);
Assert.Equal(InvoiceStatus.New, invoice.Status);
Assert.Equal("Satoshi", invoice.Buyer.Name);
Assert.Equal("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", invoice.PosData);
}
[Fact]
public async Task TestShouldGetExchangeRates()
{
// get the exchange rates
var rates = await _bitpay.GetRates();
Assert.NotNull(rates.GetRates());
}
[Fact]
public async Task TestShouldGetUsdExchangeRate()
{
// get the exchange rates and check the USD value
var rates = await _bitpay.GetRates();
Assert.True(rates.GetRate(Currency.USD) != 0, "Exchange rate not retrieved: USD");
}
[Fact]
public async Task TestShouldGetEurExchangeRate()
{
// get the exchange rates and check the EUR value
var rates = await _bitpay.GetRates();
Assert.True(rates.GetRate(Currency.EUR) != 0, "Exchange rate not retrieved: EUR");
}
[Fact]
public async Task TestShouldGetCnyExchangeRate()
{
// get the exchange rates and check the CNY value
var rates = await _bitpay.GetRates();
Assert.True(rates.GetRate(Currency.CNY) != 0, "Exchange rate not retrieved: CNY");
}
[Fact]
public async Task TestShouldUpdateExchangeRates()
{
// check the exchange rates after update
var rates = await _bitpay.GetRates();
await rates.Update();
Assert.NotNull(rates.GetRates());
}
[Fact]
public async Task TestShouldGetInvoiceIdOne()
{
// create an invoice and get it by its id
var invoice = await _bitpay.CreateInvoice(new Invoice(1.0, Currency.USD), Facade.Merchant);
invoice = await _bitpay.GetInvoice(invoice.Id);
Assert.NotNull(invoice.Id);
}
[Fact]
public async Task TestShouldCreateAndDeleteInvoice() {
// update and delete invoice by id
var basicInvoice = await _bitpay.CreateInvoice(new Invoice(1.0, Currency.USD), Facade.Merchant);
var retreivedInvoice = await _bitpay.GetInvoice(basicInvoice.Id);
var cancelledInvoice = await _bitpay.CancelInvoice(retreivedInvoice.Id);
var retreivedCancelledInvoice = await _bitpay.GetInvoice(cancelledInvoice.Id);
Assert.NotNull(basicInvoice);
Assert.NotNull(retreivedInvoice);
Assert.NotNull(cancelledInvoice);
Assert.NotNull(retreivedCancelledInvoice);
}
[Fact]
public async Task TestShouldGetInvoices() {
// get invoices between two dates
var invoices = await _bitpay.GetInvoices(yesterday, tomorrow);
Assert.True(invoices.Count > 0, "No invoices retrieved");
}
[Fact]
public async Task TestShouldCreateUpdateAndDeleteInvoice()
{
// update and delete invoice by id
var basicInvoice = await _bitpay.CreateInvoice(new Invoice(1.0, Currency.USD), Facade.Merchant);
var retreivedInvoice = await _bitpay.GetInvoice(basicInvoice.Id);
var updatedInvoice = await _bitpay.UpdateInvoice(retreivedInvoice.Id, "sandbox@bitpay.com");
var cancelledInvoice = await _bitpay.CancelInvoice(updatedInvoice.Id);
var retreivedCancelledInvoice = await _bitpay.GetInvoice(cancelledInvoice.Id);
Assert.NotNull(basicInvoice);
Assert.NotNull(retreivedInvoice);
Assert.NotNull(updatedInvoice);
Assert.NotNull(cancelledInvoice);
Assert.NotNull(retreivedCancelledInvoice);
}
/*
To use this test:
You must have a paid/completed invoice in your account (list of invoices). The test looks for the first invoice in the "complete"
state and authorises a refund. The actual refund will not be executed until the email receiver enters his bitcoin refund address.
*/
[Fact]
public async Task testShouldCreateGetCancelRefundRequest()
{
//check within the last few days
var date = DateTime.Now;
var today = date;
var sevenDaysAgo = date.AddDays(-95);
var invoices = await _bitpay.GetInvoices(sevenDaysAgo, today, InvoiceStatus.Complete);
Invoice firstInvoice = invoices[0];
Assert.NotNull(firstInvoice);
Refund createdRefund = await _bitpay.CreateRefund(firstInvoice.Id, firstInvoice.Price, firstInvoice.Currency, true, false, false);
List<Refund> retrievedRefunds = await _bitpay.GetRefunds(firstInvoice.Id);
Refund firstRefund = retrievedRefunds.Last();
Refund updatedRefund = await _bitpay.UpdateRefund(firstRefund.Id, "created");
Refund retrievedRefund = await _bitpay.GetRefund(firstRefund.Id);
Boolean sentStatus = await _bitpay.SendRefundNotification(firstRefund.Id);
Refund cancelRefund = await _bitpay.CancelRefund(firstRefund.Id);
List<Wallet> supportedWallets = await _bitpay.GetSupportedWallets();
Assert.NotNull(invoices);
Assert.NotNull(retrievedRefunds);
Assert.Equal("created", updatedRefund.Status);
Assert.Equal(firstRefund.Id, retrievedRefund.Id);
Assert.True(sentStatus);
Assert.Equal("canceled", cancelRefund.Status);
Assert.NotNull(supportedWallets);
}
[Fact]
public async Task testShouldCreateGetCancelRefundRequestNew() {
var date = DateTime.Now;
var today = date;
var sevenDaysAgo = date.AddDays(-95);
var invoices = await _bitpay.GetInvoices(sevenDaysAgo, today, InvoiceStatus.Complete);
Invoice firstInvoice = invoices[0];
Assert.NotNull(firstInvoice);
Refund createdRefund = await _bitpay.CreateRefund(firstInvoice.Id, firstInvoice.Price, firstInvoice.Currency, true, false, false);
List<Refund> retrievedRefunds = await _bitpay.GetRefunds(firstInvoice.Id);
Refund firstRefund = retrievedRefunds.Last();
Refund updatedRefund = await _bitpay.UpdateRefund(firstRefund.Id, "created");
Refund retrievedRefund = await _bitpay.GetRefund(firstRefund.Id);
Boolean sentStatus = await _bitpay.SendRefundNotification(firstRefund.Id);
Refund cancelRefund = await _bitpay.CancelRefund(firstRefund.Id);
List<Wallet> supportedWallets = await _bitpay.GetSupportedWallets();
Assert.NotNull(invoices);
Assert.NotNull(retrievedRefunds);
Assert.Equal("created", updatedRefund.Status);
Assert.Equal(firstRefund.Id, retrievedRefund.Id);
Assert.True(sentStatus);
Assert.Equal("canceled", cancelRefund.Status);
Assert.NotNull(supportedWallets);
}
[Fact]
public async Task TestShouldGetLedgerBtc()
{
// make sure we get a ledger with a not null Entries property
var ledger = await _bitpay.GetLedger(Currency.BTC, yesterday.AddMonths(-1).AddDays(3), tomorrow);
Assert.NotNull(ledger);
Assert.NotNull(ledger.Entries);
}
[Fact]
public async Task TestShouldGetLedgerUsd()
{
// Please see the comments from the GetBtcLedger concerning the Merchant facade
// make sure we get a ledger with a not null Entries property
var ledger = await _bitpay.GetLedger(Currency.USD, yesterday.AddMonths(-1).AddDays(3), tomorrow);
Assert.NotNull(ledger);
Assert.NotNull(ledger.Entries);
}
[Fact]
public async Task TestShouldGetLedgers()
{
var ledgers = await _bitpay.GetLedgers();
Assert.NotNull(ledgers);
Assert.True(ledgers.Count > 0, "No ledgers retrieved");
}
[Fact]
public async Task testShouldSubmitPayoutRecipients()
{
List<PayoutRecipient> recipientsList = new List<PayoutRecipient>();
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient1@bitpay.com",
"recipient1",
"https://hookb.in/wNDlQMV7WMFz88VDyGnJ"));
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient2@bitpay.com",
"recipient2",
"https://hookb.in/QJOPBdMgRkukpp2WO60o"));
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient3@bitpay.com",
"recipient3",
"https://hookb.in/QJOPBdMgRkukpp2WO60o"));
var recipientsObj = new PayoutRecipients(recipientsList);
List<PayoutRecipient> recipients = await _bitpay.SubmitPayoutRecipients(recipientsObj);
Assert.NotNull(recipients);
Assert.Equal(recipients[0].Email, "sandbox+recipient1@bitpay.com");
}
[Fact]
public async Task testShouldGetPayoutRecipientId()
{
List<PayoutRecipient> recipientsList = new List<PayoutRecipient>();
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient1@bitpay.com",
"recipient1",
"https://hookb.in/wNDlQMV7WMFz88VDyGnJ"));
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient2@bitpay.com",
"recipient2",
"https://hookb.in/QJOPBdMgRkukpp2WO60o"));
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient3@bitpay.com",
"recipient3",
"https://hookb.in/QJOPBdMgRkukpp2WO60o"));
PayoutRecipients recipientsObj = new PayoutRecipients(recipientsList);
var recipients = await _bitpay.SubmitPayoutRecipients(recipientsObj);
var firstRecipient = recipients.First();
var retrieved = await _bitpay.GetPayoutRecipient(firstRecipient.Id);
Assert.NotNull(firstRecipient);
Assert.NotNull(retrieved.Id);
Assert.Equal(firstRecipient.Id, retrieved.Id);
Assert.Equal(firstRecipient.Email, "sandbox+recipient1@bitpay.com");
}
[Fact]
public async Task testShouldSubmitGetAndDeletePayoutRecipient()
{
List<PayoutRecipient> recipientsList = new List<PayoutRecipient>();
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient17@bitpay.com",
"recipient1",
"https://hookb.in/wNDlQMV7WMFz88VDyGnJ"));
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient28@bitpay.com",
"recipient2",
"https://hookb.in/QJOPBdMgRkukpp2WO60o"));
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient30@bitpay.com",
"recipient3",
"https://hookb.in/QJOPBdMgRkukpp2WO60o"));
var recipientsObj = new PayoutRecipients(recipientsList);
var basicRecipients = await _bitpay.SubmitPayoutRecipients(recipientsObj);
var basicRecipient = basicRecipients[0];
var retrieveRecipient = await _bitpay.GetPayoutRecipient(basicRecipient.Id);
var retrieveRecipients = await _bitpay.GetPayoutRecipients();
retrieveRecipient.Label = "Updated Label";
var updateRecipient = await _bitpay.UpdatePayoutRecipient(retrieveRecipient.Id, retrieveRecipient);
var deleteRecipient = await _bitpay.DeletePayoutRecipient(retrieveRecipient.Id);
Assert.NotNull(basicRecipient);
Assert.NotNull(retrieveRecipient.Id);
Assert.NotNull(retrieveRecipients);
Assert.Equal(basicRecipient.Id, retrieveRecipient.Id);
Assert.Equal(retrieveRecipient.Status, RecipientStatus.INVITED);
Assert.Equal(updateRecipient.Label,"Updated Label");
Assert.True(deleteRecipient);
}
[Fact]
public async Task testShouldRequestPayoutRecipientNotification()
{
List<PayoutRecipient> recipientsList = new List<PayoutRecipient>();
recipientsList.Add(new PayoutRecipient(
"sandbox+recipient1@bitpay.com",
"recipient1",
"https://hookb.in/wNDlQMV7WMFz88VDyGnJ"));
PayoutRecipients recipientsObj = new PayoutRecipients(recipientsList);
var recipients = await _bitpay.SubmitPayoutRecipients(recipientsObj);
var basicRecipient = recipients[0];
var result = await _bitpay.RequestPayoutRecipientNotification(basicRecipient.Id);
Assert.True(result);
}
[Fact]
public async Task testShouldSubmitPayout()
{
var ledgerCurrency = Currency.USD;
var currency = Currency.USD;
var payout = new Payout(5.0, currency, ledgerCurrency);
var recipients = await _bitpay.GetPayoutRecipients("active", 1);
payout.RecipientId = recipients.First().Id;
payout.NotificationUrl = "https://hookbin.com/yDEDeWJKyasG9yjj9X9P";
var createPayout = await _bitpay.SubmitPayout(payout);
var cancelledPayout = await _bitpay.CancelPayout(createPayout.Id);
Assert.NotNull(createPayout.Id);
Assert.True(cancelledPayout);
}
[Fact]
public async Task testShouldGetPayouts()
{
var endDate = DateTime.Now;
var startDate = endDate.AddDays(-50);
var batches = await _bitpay.GetPayouts(startDate, endDate);
Assert.True(batches.Count > 0);
}
[Fact]
public async Task testShouldGetPayoutsByStatus()
{
var endDate = DateTime.Now;
var startDate = endDate.AddDays(-50);
var batches = await _bitpay.GetPayouts(startDate, endDate, PayoutStatus.Cancelled, "");
Assert.True(batches.Count > 0);
}
[Fact]
public async Task testShouldSubmitGetAndDeletePayout()
{
var ledgerCurrency = Currency.USD;
var currency = Currency.USD;
var batch = new Payout(5.0, currency, ledgerCurrency);
var recipients = await _bitpay.GetPayoutRecipients("active", 1);
batch.RecipientId = recipients.First().Id;
batch.NotificationUrl = "https://hookb.in/QJOPBdMgRkukpp2WO60o";
var batch0 = await _bitpay.SubmitPayout(batch);
var batchRetrieved = await _bitpay.GetPayout(batch0.Id);
var batchCancelled = await _bitpay.CancelPayout(batchRetrieved.Id);
Assert.NotNull(batch0.Id);
Assert.NotNull(batchRetrieved.Id);
Assert.Equal(batch0.Id, batchRetrieved.Id);
Assert.Equal(batchRetrieved.Status, PayoutStatus.New);
Assert.True(batchCancelled);
}
[Fact]
public async Task testShouldRequestPayoutNotification()
{
var ledgerCurrency = Currency.USD;
var currency = Currency.USD;
var batch = new Payout(5.0, currency, ledgerCurrency);
var recipients = await _bitpay.GetPayoutRecipients("active", 1);
batch.RecipientId = recipients.First().Id;
batch.NotificationUrl = "https://hookb.in/QJOPBdMgRkukpp2WO60o";
var createPayout = await _bitpay.SubmitPayout(batch);
var result = await _bitpay.RequestPayoutNotification(createPayout.Id);
var cancelledPayout = await _bitpay.CancelPayout(createPayout.Id);
Assert.True(result);
Assert.True(cancelledPayout);
}
[Fact]
public async Task testShouldGetPayoutRecipients()
{
var recipients = await _bitpay.GetPayoutRecipients("active", 1);
Assert.Equal(1, recipients.Count);
}
[Fact]
public async Task TestShouldSubmitPayoutBatch()
{
var date = DateTime.Now;
var threeDaysFromNow = date.AddDays(3);
var effectiveDate = threeDaysFromNow;
var currency = Currency.USD;
var ledgerCurrency = Currency.USD;
var instructions = new List<PayoutInstruction>() {
new PayoutInstruction(10.0, RecipientReferenceMethod.EMAIL, "sandbox+recipient1@bitpay.com"),
};
var batch = new PayoutBatch(currency, effectiveDate, instructions, ledgerCurrency);
batch.NotificationUrl = "https://hookbin.com/yDEDeWJKyasG9yjj9X9P";
batch = await _bitpay.SubmitPayoutBatch(batch);
Assert.NotNull(batch.Id);
Assert.True(batch.Instructions.Count == 1);
await _bitpay.CancelPayoutBatch(batch.Id);
}
[Fact]
public async Task TestShouldSubmitGetAndDeletePayoutBatch()
{
var date = DateTime.Now;
var threeDaysFromNow = date.AddDays(3);
var effectiveDate = threeDaysFromNow;
var currency = Currency.USD;
var ledgerCurrency = Currency.USD;
var instructions = new List<PayoutInstruction>() {
new PayoutInstruction(10.0, RecipientReferenceMethod.EMAIL, "sandbox+recipient1@bitpay.com"),
new PayoutInstruction(10.0, RecipientReferenceMethod.EMAIL, "sandbox+recipient2@bitpay.com")
};
var batch0 = new PayoutBatch(currency, effectiveDate, instructions, ledgerCurrency);
batch0.NotificationUrl = "https://hookbin.com/yDEDeWJKyasG9yjj9X9P";
batch0 = await _bitpay.SubmitPayoutBatch(batch0);
Assert.NotNull(batch0.Id);
Assert.True(batch0.Instructions.Count == 2);
var batch1 = await _bitpay.GetPayoutBatch(batch0.Id);
Assert.NotNull(batch1.Id);
Assert.True(batch1.Instructions.Count == 2);
await _bitpay.CancelPayoutBatch(batch0.Id);
}
[Fact]
public async Task testShouldRequestPayoutBatchNotification()
{
var date = DateTime.Now;
var ledgerCurrency = Currency.USD;
var threeDaysFromNow = date.AddDays(3);
var currency = Currency.USD;
var effectiveDate = threeDaysFromNow;
var instructions = new List<PayoutInstruction>() {
new PayoutInstruction(10.0, RecipientReferenceMethod.EMAIL, "sandbox+recipient1@bitpay.com"),
new PayoutInstruction(10.0, RecipientReferenceMethod.EMAIL, "sandbox+recipient2@bitpay.com") };
var batch = new PayoutBatch(currency, effectiveDate, instructions, ledgerCurrency);
batch.NotificationUrl = "https://hookbin.com/yDEDeWJKyasG9yjj9X9P";
batch = await _bitpay.SubmitPayoutBatch(batch);
var result = await _bitpay.RequestPayoutBatchNotification(batch.Id);
var cancelledPayoutBatch = await _bitpay.CancelPayoutBatch(batch.Id);
Assert.True(result);
Assert.True(cancelledPayoutBatch);
}
[Fact]
public async Task TestShouldGetPayoutBatches()
{
var endDate = DateTime.Now;
var startDate = endDate.AddDays(-50);
var batches = await _bitpay.GetPayoutBatches(startDate, endDate);
Assert.True(batches.Count > 0, "No batches retrieved");
}
[Fact]
public async Task TestShouldGetPayoutBatchesByStatus()
{
var endDate = DateTime.Now;
var startDate = endDate.AddDays(-50);
var batches = await _bitpay.GetPayoutBatches(startDate, endDate, PayoutStatus.Cancelled);
Assert.True(batches.Count > 0, "No batches retrieved");
}
[Fact]
public async Task TestGetSettlements()
{
// make sure we get a ledger with a not null Entries property
var settlements = await _bitpay.GetSettlements(Currency.EUR, yesterday.AddMonths(-1).AddDays(3), tomorrow);
Assert.NotNull(settlements);
}
[Fact]
public async Task TestGetSettlement()
{
// make sure we get a ledger with a not null Entries property
var settlements = await _bitpay.GetSettlements(Currency.EUR, yesterday.AddMonths(-1).AddDays(3), tomorrow);
var firstSettlement = settlements[0];
var settlement = await _bitpay.GetSettlement(firstSettlement.Id);
Assert.NotNull(settlement.Id);
Assert.Equal(firstSettlement.Id, settlement.Id);
}
[Fact]
public async Task TestShouldCreateBillUSD()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Price = 30.0, Quantity = 9, Description = "product-a" });
items.Add(new Item() { Price = 14.0, Quantity = 16, Description = "product-b" });
items.Add(new Item() { Price = 3.90, Quantity = 42, Description = "product-c" });
items.Add(new Item() { Price = 6.99, Quantity = 12, Description = "product-d" });
// create a bill and make sure we receive an id - which means it has been successfully submitted
var bill = new Bill()
{
Number = "1",
Currency = Currency.USD,
Email = "", //email address mandatory
Items = items
};
var basicBill = await _bitpay.CreateBill(bill);
Assert.NotNull(basicBill.Id);
}
[Fact]
public async Task TestShouldCreateBillEur()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Price = 30.0, Quantity = 9, Description = "product-a" });
items.Add(new Item() { Price = 14.0, Quantity = 16, Description = "product-b" });
items.Add(new Item() { Price = 3.90, Quantity = 42, Description = "product-c" });
items.Add(new Item() { Price = 6.99, Quantity = 12, Description = "product-d" });
// create a bill and make sure we receive an id - which means it has been successfully submitted
var bill = new Bill()
{
Number = "2",
Currency = Currency.EUR,
Email = "", //email address mandatory
Items = items
};
var basicBill = await _bitpay.CreateBill(bill);
Assert.NotNull(basicBill.Id);
}
[Fact]
public async Task TestShouldGetBillUrl()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Price = 30.0, Quantity = 9, Description = "product-a" });
items.Add(new Item() { Price = 14.0, Quantity = 16, Description = "product-b" });
items.Add(new Item() { Price = 3.90, Quantity = 42, Description = "product-c" });
items.Add(new Item() { Price = 6.99, Quantity = 12, Description = "product-d" });
// create a bill and make sure we receive a bill url - which means we can check it online
var bill = new Bill()
{
Number = "3",
Currency = Currency.USD,
Email = "", //email address mandatory
Items = items
};
var basicBill = await _bitpay.CreateBill(bill);
Assert.NotNull(basicBill.Url);
}
[Fact]
public async Task TestShouldGetBillStatus()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Price = 30.0, Quantity = 9, Description = "product-a" });
items.Add(new Item() { Price = 14.0, Quantity = 16, Description = "product-b" });
items.Add(new Item() { Price = 3.90, Quantity = 42, Description = "product-c" });
items.Add(new Item() { Price = 6.99, Quantity = 12, Description = "product-d" });
// create a bill and make sure we receive a correct bill status (draft)
var bill = new Bill()
{
Number = "4",
Currency = Currency.USD,
Email = "", //email address mandatory
Items = items
};
var basicBill = await _bitpay.CreateBill(bill);
Assert.Equal(BillStatus.Draft, basicBill.Status);
}
[Fact]
public async Task TestShouldGetBillTotals()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Price = 30.0, Quantity = 9, Description = "product-a" });
items.Add(new Item() { Price = 14.0, Quantity = 16, Description = "product-b" });
items.Add(new Item() { Price = 3.90, Quantity = 42, Description = "product-c" });
items.Add(new Item() { Price = 6.99, Quantity = 12, Description = "product-d" });
// create a bill and make sure we receive the same items sum as it was sent
var bill = new Bill()
{
Number = "5",
Currency = Currency.USD,
Email = "", //email address mandatory
Items = items
};
var basicBill = await _bitpay.CreateBill(bill);
Assert.Equal(basicBill.Items.Select(i => i.Price).Sum(), items.Select(i => i.Price).Sum());
}
[Fact]
public async Task TestShouldGetBill()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Price = 30.0, Quantity = 9, Description = "product-a" });
items.Add(new Item() { Price = 14.0, Quantity = 16, Description = "product-b" });
items.Add(new Item() { Price = 3.90, Quantity = 42, Description = "product-c" });
items.Add(new Item() { Price = 6.99, Quantity = 12, Description = "product-d" });
// create a bill then retrieve it through the get method - they should match
var bill = new Bill()
{
Number = "6",
Currency = Currency.USD,
Email = "", //email address mandatory
Items = items
};
var basicBill = await _bitpay.CreateBill(bill);
var retrievedBill = await _bitpay.GetBill(basicBill.Id);
Assert.Equal(basicBill.Id, retrievedBill.Id);
}
[Fact]
public async Task TestShouldGetAndUpdateBill()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Price = 30.0, Quantity = 9, Description = "product-a" });
items.Add(new Item() { Price = 14.0, Quantity = 16, Description = "product-b" });
items.Add(new Item() { Price = 3.90, Quantity = 42, Description = "product-c" });
items.Add(new Item() { Price = 6.99, Quantity = 12, Description = "product-d" });
var bill = new Bill()
{
Number = "6",
Currency = Currency.USD,
Email = "", //email address mandatory
Items = items,
Name = "basicBill"
};
var basicBill = await _bitpay.CreateBill(bill);
var retrievedBill = await _bitpay.GetBill(basicBill.Id);
retrievedBill.Currency = Currency.EUR;
retrievedBill.Name = "updatedBill";
retrievedBill.Items.Add(new Item() { Price = 60.0, Quantity = 7, Description = "product-added" });
var updatedBill = await _bitpay.UpdateBill(retrievedBill, retrievedBill.Id);
Assert.Equal(basicBill.Id, retrievedBill.Id);
Assert.Equal(retrievedBill.Id, updatedBill.Id);
Assert.Equal(updatedBill.Currency, Currency.EUR);
Assert.Equal(updatedBill.Name, "updatedBill");
}
[Fact]
public async Task TestShouldDeliverBill()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Price = 30.0, Quantity = 9, Description = "product-a" });
items.Add(new Item() { Price = 14.0, Quantity = 16, Description = "product-b" });
items.Add(new Item() { Price = 3.90, Quantity = 42, Description = "product-c" });
items.Add(new Item() { Price = 6.99, Quantity = 12, Description = "product-d" });
// create a bill then retrieve it through the get method - they should match
var bill = new Bill()
{
Number = "7",
Currency = Currency.USD,
Email = "", //email address mandatory
Items = items
};
var basicBill = await _bitpay.CreateBill(bill);
var result = await _bitpay.DeliverBill(basicBill.Id, basicBill.Token);
// Retrieve the updated bill for status confirmation
var retrievedBill = await _bitpay.GetBill(basicBill.Id);
// Check the correct response
Assert.Equal("Success", result);
// Confirm that the bill is sent
Assert.Equal(BillStatus.Sent, retrievedBill.Status);
}
[Fact]
public async Task TestShouldGetBills()
{
var bills = await _bitpay.GetBills();
Assert.True(bills.Count > 0, "No bills retrieved");
}
[Fact]
public async Task TestShouldGetBillsByStatus()
{
var bills = await _bitpay.GetBills(BillStatus.Sent);
Assert.True(bills.Count > 0, "No bills retrieved");
}
}
}
| |
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using umbraco.DataLayer;
using umbraco.BusinessLogic;
using System.Linq;
namespace umbraco.cms.businesslogic.macro
{
/// <summary>
/// The Macro component are one of the umbraco essentials, used for drawing dynamic content in the public website of umbraco.
///
/// A Macro is a placeholder for either a xsl transformation, a custom .net control or a .net usercontrol.
///
/// The Macro is representated in templates and content as a special html element, which are being parsed out and replaced with the
/// output of either the .net control or the xsl transformation when a page is being displayed to the visitor.
///
/// A macro can have a variety of properties which are used to transfer userinput to either the usercontrol/custom control or the xsl
///
/// </summary>
[Obsolete("This is no longer used, use the IMacroService and related models instead")]
public class Macro
{
//initialize empty model
internal IMacro MacroEntity = new Umbraco.Core.Models.Macro();
/// <summary>
/// Unused, please do not use
/// </summary>
[Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
/// <summary>
/// id
/// </summary>
public int Id
{
get { return MacroEntity.Id; }
}
/// <summary>
/// If set to true, the macro can be inserted on documents using the richtexteditor.
/// </summary>
public bool UseInEditor
{
get { return MacroEntity.UseInEditor; }
set { MacroEntity.UseInEditor = value; }
}
/// <summary>
/// The cache refreshrate - the maximum amount of time the macro should remain cached in the umbraco
/// runtime layer.
///
/// The macro caches are refreshed whenever a document is changed
/// </summary>
public int RefreshRate
{
get { return MacroEntity.CacheDuration; }
set { MacroEntity.CacheDuration = value; }
}
/// <summary>
/// The alias of the macro - are used for retrieving the macro when parsing the {?UMBRACO_MACRO}{/?UMBRACO_MACRO} element,
/// by using the alias instead of the Id, it's possible to distribute macroes from one installation to another - since the id
/// is given by an autoincrementation in the database table, and might be used by another macro in the foreing umbraco
/// </summary>
public string Alias
{
get { return MacroEntity.Alias; }
set { MacroEntity.Alias = value; }
}
/// <summary>
/// The userfriendly name
/// </summary>
public string Name
{
get { return MacroEntity.Name; }
set { MacroEntity.Name = value; }
}
/// <summary>
/// If the macro is a wrapper for a custom control, this is the assemly name from which to load the macro
///
/// specified like: /bin/mydll (without the .dll extension)
/// </summary>
public string Assembly
{
get { return MacroEntity.ControlAssembly; }
set { MacroEntity.ControlAssembly = value; }
}
/// <summary>
/// The relative path to the usercontrol or the assembly type of the macro when using .Net custom controls
/// </summary>
/// <remarks>
/// When using a user control the value is specified like: /usercontrols/myusercontrol.ascx (with the .ascx postfix)
/// </remarks>
public string Type
{
get { return MacroEntity.ControlType; }
set { MacroEntity.ControlType = value; }
}
/// <summary>
/// The xsl file used to transform content
///
/// Umbraco assumes that the xslfile is present in the "/xslt" folder
/// </summary>
public string Xslt
{
get { return MacroEntity.XsltPath; }
set { MacroEntity.XsltPath = value; }
}
/// <summary>
/// This field is used to store the file value for any scripting macro such as python, ruby, razor macros or Partial View Macros
/// </summary>
/// <remarks>
/// Depending on how the file is stored depends on what type of macro it is. For example if the file path is a full virtual path
/// starting with the ~/Views/MacroPartials then it is deemed to be a Partial View Macro, otherwise the file extension of the file
/// saved will determine which macro engine will be used to execute the file.
/// </remarks>
public string ScriptingFile
{
get { return MacroEntity.ScriptPath; }
set { MacroEntity.ScriptPath = value; }
}
/// <summary>
/// The python file used to be executed
///
/// Umbraco assumes that the python file is present in the "/python" folder
/// </summary>
public bool RenderContent
{
get { return MacroEntity.DontRender == false; }
set { MacroEntity.DontRender = value == false; }
}
/// <summary>
/// Gets or sets a value indicating whether [cache personalized].
/// </summary>
/// <value><c>true</c> if [cache personalized]; otherwise, <c>false</c>.</value>
public bool CachePersonalized
{
get { return MacroEntity.CacheByMember; }
set { MacroEntity.CacheByMember = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the macro is cached for each individual page.
/// </summary>
/// <value><c>true</c> if [cache by page]; otherwise, <c>false</c>.</value>
public bool CacheByPage
{
get { return MacroEntity.CacheByPage; }
set { MacroEntity.CacheByPage = value; }
}
/// <summary>
/// Properties which are used to send parameters to the xsl/usercontrol/customcontrol of the macro
/// </summary>
public MacroProperty[] Properties
{
get
{
return MacroEntity.Properties.Select(x => new MacroProperty
{
Alias = x.Alias,
Name = x.Name,
SortOrder = x.SortOrder,
Macro = this,
ParameterEditorAlias = x.EditorAlias
}).ToArray();
}
}
/// <summary>
/// Macro initializer
/// </summary>
[Obsolete("This should no longer be used, use the IMacroService and related models instead")]
public Macro()
{
}
/// <summary>
/// Macro initializer
/// </summary>
/// <param name="Id">The id of the macro</param>
[Obsolete("This should no longer be used, use the IMacroService and related models instead")]
public Macro(int Id)
{
Setup(Id);
}
[Obsolete("This should no longer be used, use the IMacroService and related models instead")]
internal Macro(IMacro macro)
{
MacroEntity = macro;
}
/// <summary>
/// Initializes a new instance of the <see cref="Macro"/> class.
/// </summary>
/// <param name="alias">The alias.</param>
[Obsolete("This should no longer be used, use the IMacroService and related models instead")]
public Macro(string alias)
{
Setup(alias);
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
[Obsolete("This should no longer be used, use the IMacroService and related models instead")]
public virtual void Save()
{
//event
var e = new SaveEventArgs();
FireBeforeSave(e);
if (e.Cancel == false)
{
ApplicationContext.Current.Services.MacroService.Save(MacroEntity);
FireAfterSave(e);
}
}
/// <summary>
/// Deletes the current macro
/// </summary>
public void Delete()
{
//event
var e = new DeleteEventArgs();
FireBeforeDelete(e);
if (e.Cancel == false)
{
ApplicationContext.Current.Services.MacroService.Delete(MacroEntity);
FireAfterDelete(e);
}
}
[Obsolete("This is no longer used, use the IMacroService and related models instead")]
public static Macro Import(XmlNode n)
{
var alias = XmlHelper.GetNodeValue(n.SelectSingleNode("alias"));
//check to see if the macro alreay exists in the system
//it's better if it does and we keep using it, alias *should* be unique remember
var m = Macro.GetByAlias(alias);
if (m == null)
{
m = MakeNew(XmlHelper.GetNodeValue(n.SelectSingleNode("name")));
}
try
{
m.Alias = alias;
m.Assembly = XmlHelper.GetNodeValue(n.SelectSingleNode("scriptAssembly"));
m.Type = XmlHelper.GetNodeValue(n.SelectSingleNode("scriptType"));
m.Xslt = XmlHelper.GetNodeValue(n.SelectSingleNode("xslt"));
m.RefreshRate = int.Parse(XmlHelper.GetNodeValue(n.SelectSingleNode("refreshRate")));
// we need to validate if the usercontrol is missing the tilde prefix requirement introduced in v6
if (string.IsNullOrEmpty(m.Assembly) && string.IsNullOrEmpty(m.Type) == false && m.Type.StartsWith("~") == false)
{
m.Type = "~/" + m.Type;
}
if (n.SelectSingleNode("scriptingFile") != null)
{
m.ScriptingFile = XmlHelper.GetNodeValue(n.SelectSingleNode("scriptingFile"));
}
try
{
m.UseInEditor = bool.Parse(XmlHelper.GetNodeValue(n.SelectSingleNode("useInEditor")));
}
catch (Exception macroExp)
{
LogHelper.Error<Macro>("Error creating macro property", macroExp);
}
// macro properties
foreach (XmlNode mp in n.SelectNodes("properties/property"))
{
try
{
var propertyAlias = mp.Attributes.GetNamedItem("alias").Value;
var property = m.Properties.SingleOrDefault(p => p.Alias == propertyAlias);
if (property != null)
{
property.Name = mp.Attributes.GetNamedItem("name").Value;
property.ParameterEditorAlias = mp.Attributes.GetNamedItem("propertyType").Value;
property.Save();
}
else
{
MacroProperty.MakeNew(
m,
propertyAlias,
mp.Attributes.GetNamedItem("name").Value,
mp.Attributes.GetNamedItem("propertyType").Value
);
}
}
catch (Exception macroPropertyExp)
{
LogHelper.Error<Macro>("Error creating macro property", macroPropertyExp);
}
}
m.Save();
}
catch (Exception ex)
{
LogHelper.Error<Macro>("An error occurred importing a macro", ex);
return null;
}
return m;
}
private void Setup(int id)
{
var macro = ApplicationContext.Current.Services.MacroService.GetById(id);
if (macro == null)
throw new ArgumentException(string.Format("No Macro exists with id '{0}'", id));
MacroEntity = macro;
}
private void Setup(string alias)
{
var macro = ApplicationContext.Current.Services.MacroService.GetByAlias(alias);
if (macro == null)
throw new ArgumentException(string.Format("No Macro exists with alias '{0}'", alias));
MacroEntity = macro;
}
/// <summary>
/// Get an xmlrepresentation of the macro, used for exporting the macro to a package for distribution
/// </summary>
/// <param name="xd">Current xmldocument context</param>
/// <returns>An xmlrepresentation of the macro</returns>
public XmlNode ToXml(XmlDocument xd)
{
var serializer = new EntityXmlSerializer();
var xml = serializer.Serialize(MacroEntity);
return xml.GetXmlNode(xd);
}
[Obsolete("This does nothing")]
public void RefreshProperties()
{
}
#region STATICS
/// <summary>
/// Creates a new macro given the name
/// </summary>
/// <param name="Name">Userfriendly name</param>
/// <returns>The newly macro</returns>
public static Macro MakeNew(string Name)
{
var macro = new Umbraco.Core.Models.Macro
{
Name = Name,
Alias = Name.Replace(" ", String.Empty)
};
ApplicationContext.Current.Services.MacroService.Save(macro);
var newMacro = new Macro(macro);
//fire new event
var e = new NewEventArgs();
newMacro.OnNew(e);
return newMacro;
}
/// <summary>
/// Retrieve all macroes
/// </summary>
/// <returns>A list of all macroes</returns>
public static Macro[] GetAll()
{
return ApplicationContext.Current.Services.MacroService.GetAll()
.Select(x => new Macro(x))
.ToArray();
}
/// <summary>
/// Static contructor for retrieving a macro given an alias
/// </summary>
/// <param name="alias">The alias of the macro</param>
/// <returns>If the macro with the given alias exists, it returns the macro, else null</returns>
public static Macro GetByAlias(string alias)
{
return ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<Macro>(
GetCacheKey(alias),
timeout: TimeSpan.FromMinutes(30),
getCacheItem: () =>
{
var macro = ApplicationContext.Current.Services.MacroService.GetByAlias(alias);
if (macro == null) return null;
return new Macro(macro);
});
}
public static Macro GetById(int id)
{
return ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem<Macro>(
GetCacheKey(string.Format("macro_via_id_{0}", id)),
timeout: TimeSpan.FromMinutes(30),
getCacheItem: () =>
{
var macro = ApplicationContext.Current.Services.MacroService.GetById(id);
if (macro == null) return null;
return new Macro(macro);
});
}
public static MacroTypes FindMacroType(string xslt, string scriptFile, string scriptType, string scriptAssembly)
{
if (string.IsNullOrEmpty(xslt) == false)
return MacroTypes.XSLT;
if (string.IsNullOrEmpty(scriptFile) == false)
{
//we need to check if the file path saved is a virtual path starting with ~/Views/MacroPartials, if so then this is
//a partial view macro, not a script macro
//we also check if the file exists in ~/App_Plugins/[Packagename]/Views/MacroPartials, if so then it is also a partial view.
return (scriptFile.InvariantStartsWith(SystemDirectories.MvcViews + "/MacroPartials/")
|| (Regex.IsMatch(scriptFile, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled | RegexOptions.IgnoreCase)))
? MacroTypes.PartialView
: MacroTypes.Script;
}
if (string.IsNullOrEmpty(scriptType) == false && scriptType.InvariantContains(".ascx"))
return MacroTypes.UserControl;
if (string.IsNullOrEmpty(scriptType) == false && !string.IsNullOrEmpty(scriptAssembly))
return MacroTypes.CustomControl;
return MacroTypes.Unknown;
}
public static string GenerateCacheKeyFromCode(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentNullException("input", "An MD5 hash cannot be generated when 'input' parameter is null!");
// step 1, calculate MD5 hash from input
var md5 = MD5.Create();
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
var sb = new StringBuilder();
for (var i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
#region Macro Refactor
private static string GetCacheKey(string alias)
{
return CacheKeys.MacroCacheKey + alias;
}
#endregion
//Macro events
//Delegates
public delegate void SaveEventHandler(Macro sender, SaveEventArgs e);
public delegate void NewEventHandler(Macro sender, NewEventArgs e);
public delegate void DeleteEventHandler(Macro sender, DeleteEventArgs e);
/// <summary>
/// Occurs when a macro is saved.
/// </summary>
public static event SaveEventHandler BeforeSave;
protected virtual void FireBeforeSave(SaveEventArgs e) {
if (BeforeSave != null)
BeforeSave(this, e);
}
public static event SaveEventHandler AfterSave;
protected virtual void FireAfterSave(SaveEventArgs e) {
if (AfterSave != null)
AfterSave(this, e);
}
public static event NewEventHandler New;
protected virtual void OnNew(NewEventArgs e) {
if (New != null)
New(this, e);
}
public static event DeleteEventHandler BeforeDelete;
protected virtual void FireBeforeDelete(DeleteEventArgs e) {
if (BeforeDelete != null)
BeforeDelete(this, e);
}
public static event DeleteEventHandler AfterDelete;
protected virtual void FireAfterDelete(DeleteEventArgs e) {
if (AfterDelete != null)
AfterDelete(this, e);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Runtime.Serialization;
namespace DDay.iCal
{
/// <summary>
/// A class that represents an RFC 2445 VALARM component.
/// FIXME: move GetOccurrences() logic into an AlarmEvaluator.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public class Alarm :
CalendarComponent,
IAlarm
{
#region Private Fields
private List<AlarmOccurrence> m_Occurrences;
#endregion
#region Public Properties
virtual public AlarmAction Action
{
get { return Properties.Get<AlarmAction>("ACTION"); }
set { Properties.Set("ACTION", value); }
}
virtual public IAttachment Attachment
{
get { return Properties.Get<IAttachment>("ATTACH"); }
set { Properties.Set("ATTACH", value); }
}
virtual public IList<IAttendee> Attendees
{
get { return Properties.GetList<IAttendee>("ATTENDEE"); }
set { Properties.SetList("ATTENDEE", value); }
}
virtual public string Description
{
get { return Properties.Get<string>("DESCRIPTION"); }
set { Properties.Set("DESCRIPTION", value); }
}
virtual public TimeSpan Duration
{
get { return Properties.Get<TimeSpan>("DURATION"); }
set { Properties.Set("DURATION", value); }
}
virtual public int Repeat
{
get { return Properties.Get<int>("REPEAT"); }
set { Properties.Set("REPEAT", value); }
}
virtual public string Summary
{
get { return Properties.Get<string>("SUMMARY"); }
set { Properties.Set("SUMMARY", value); }
}
virtual public ITrigger Trigger
{
get { return Properties.Get<ITrigger>("TRIGGER"); }
set { Properties.Set("TRIGGER", value); }
}
#endregion
#region Protected Properties
virtual protected List<AlarmOccurrence> Occurrences
{
get { return m_Occurrences; }
set { m_Occurrences = value; }
}
#endregion
#region Constructors
public Alarm()
{
Initialize();
}
void Initialize()
{
Name = Components.ALARM;
Occurrences = new List<AlarmOccurrence>();
}
#endregion
#region Public Methods
/// <summary>
/// Gets a list of alarm occurrences for the given recurring component, <paramref name="rc"/>
/// that occur between <paramref name="FromDate"/> and <paramref name="ToDate"/>.
/// </summary>
virtual public IList<AlarmOccurrence> GetOccurrences(IRecurringComponent rc, IDateTime FromDate, IDateTime ToDate)
{
Occurrences.Clear();
if (Trigger != null)
{
// If the trigger is relative, it can recur right along with
// the recurring items, otherwise, it happens once and
// only once (at a precise time).
if (Trigger.IsRelative)
{
// Ensure that "FromDate" has already been set
if (FromDate == null)
FromDate = rc.Start.Copy<IDateTime>();
TimeSpan d = default(TimeSpan);
foreach (Occurrence o in rc.GetOccurrences(FromDate, ToDate))
{
IDateTime dt = o.Period.StartTime;
if (Trigger.Related == TriggerRelation.End)
{
if (o.Period.EndTime != null)
{
dt = o.Period.EndTime;
if (d == default(TimeSpan))
d = o.Period.Duration;
}
// Use the "last-found" duration as a reference point
else if (d != default(TimeSpan))
dt = o.Period.StartTime.Add(d);
else throw new ArgumentException("Alarm trigger is relative to the END of the occurrence; however, the occurence has no discernible end.");
}
Occurrences.Add(new AlarmOccurrence(this, dt.Add(Trigger.Duration.Value), rc));
}
}
else
{
IDateTime dt = Trigger.DateTime.Copy<IDateTime>();
dt.AssociatedObject = this;
Occurrences.Add(new AlarmOccurrence(this, dt, rc));
}
// If a REPEAT and DURATION value were specified,
// then handle those repetitions here.
AddRepeatedItems();
}
return Occurrences;
}
/// <summary>
/// Polls the <see cref="Alarm"/> component for alarms that have been triggered
/// since the provided <paramref name="Start"/> date/time. If <paramref name="Start"/>
/// is null, all triggered alarms will be returned.
/// </summary>
/// <param name="Start">The earliest date/time to poll trigerred alarms for.</param>
/// <returns>A list of <see cref="AlarmOccurrence"/> objects, each containing a triggered alarm.</returns>
virtual public IList<AlarmOccurrence> Poll(IDateTime Start, IDateTime End)
{
List<AlarmOccurrence> Results = new List<AlarmOccurrence>();
// Evaluate the alarms to determine the recurrences
RecurringComponent rc = Parent as RecurringComponent;
if (rc != null)
{
Results.AddRange(GetOccurrences(rc, Start, End));
Results.Sort();
}
return Results;
}
#endregion
#region Protected Methods
/// <summary>
/// Handles the repetitions that occur from the <c>REPEAT</c> and
/// <c>DURATION</c> properties. Each recurrence of the alarm will
/// have its own set of generated repetitions.
/// </summary>
virtual protected void AddRepeatedItems()
{
if (Repeat != null)
{
int len = Occurrences.Count;
for (int i = 0; i < len; i++)
{
AlarmOccurrence ao = Occurrences[i];
IDateTime alarmTime = ao.DateTime.Copy<IDateTime>();
for (int j = 0; j < Repeat; j++)
{
alarmTime = alarmTime.Add(Duration);
Occurrences.Add(new AlarmOccurrence(this, alarmTime.Copy<IDateTime>(), ao.Component));
}
}
}
}
#endregion
#region Overrides
protected override void OnDeserializing(StreamingContext context)
{
base.OnDeserializing(context);
Initialize();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Umbraco.Core.Logging;
namespace Umbraco.Core.ObjectResolution
{
/// <summary>
/// The base class for all lazy many-objects resolvers.
/// </summary>
/// <typeparam name="TResolver">The type of the concrete resolver class.</typeparam>
/// <typeparam name="TResolved">The type of the resolved objects.</typeparam>
/// <remarks>
/// <para>This is a special case resolver for when types get lazily resolved in order to resolve the actual types. This is useful
/// for when there is some processing overhead (i.e. Type finding in assemblies) to return the Types used to instantiate the instances.
/// In some these cases we don't want to have to type-find during application startup, only when we need to resolve the instances.</para>
/// <para>Important notes about this resolver: it does not support Insert or Remove and therefore does not support any ordering unless
/// the types are marked with the WeightAttribute.</para>
/// </remarks>
public abstract class LazyManyObjectsResolverBase<TResolver, TResolved> : ManyObjectsResolverBase<TResolver, TResolved>
where TResolved : class
where TResolver : ResolverBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// and an optional lifetime scope.
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="logger"></param>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: base(serviceProvider, logger, scope)
{
Initialize();
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: base(scope)
{
Initialize();
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(HttpContextBase httpContext)
: base(httpContext)
{
Initialize();
}
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, IEnumerable<Lazy<Type>> lazyTypeList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(serviceProvider, logger, scope)
{
AddTypes(lazyTypeList);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(IEnumerable<Lazy<Type>> lazyTypeList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, lazyTypeList, scope)
{
}
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, Func<IEnumerable<Type>> typeListProducerList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(serviceProvider, logger, scope)
{
_typeListProducerList.Add(typeListProducerList);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(Func<IEnumerable<Type>> typeListProducerList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, typeListProducerList, scope)
{
}
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, HttpContextBase httpContext, IEnumerable<Lazy<Type>> lazyTypeList)
: this(serviceProvider, logger, httpContext)
{
AddTypes(lazyTypeList);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable<Lazy<Type>> lazyTypeList)
: this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, httpContext, lazyTypeList)
{
}
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, HttpContextBase httpContext, Func<IEnumerable<Type>> typeListProducerList)
: this(serviceProvider, logger, httpContext)
{
_typeListProducerList.Add(typeListProducerList);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use ctor specifying IServiceProvider instead")]
protected LazyManyObjectsResolverBase(HttpContextBase httpContext, Func<IEnumerable<Type>> typeListProducerList)
: this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, httpContext, typeListProducerList)
{
}
#endregion
private readonly List<Lazy<Type>> _lazyTypeList = new List<Lazy<Type>>();
private readonly List<Func<IEnumerable<Type>>> _typeListProducerList = new List<Func<IEnumerable<Type>>>();
private readonly List<Type> _excludedTypesList = new List<Type>();
private Lazy<List<Type>> _resolvedTypes;
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="logger"></param>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, HttpContextBase httpContext)
: base(serviceProvider, logger, httpContext)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of object types,
/// and an optional lifetime scope.
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="logger"></param>
/// <param name="value">The list of object types.</param>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, IEnumerable<Type> value, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: base(serviceProvider, logger, value, scope)
{
}
private void Initialize()
{
_resolvedTypes = new Lazy<List<Type>>(() =>
{
var resolvedTypes = new List<Type>();
// get the types by evaluating the lazy & producers
var types = new List<Type>();
types.AddRange(_lazyTypeList.Select(x => x.Value));
types.AddRange(_typeListProducerList.SelectMany(x => x()));
// we need to validate each resolved type now since we could
// not do it before evaluating the lazy & producers
foreach (var type in types.Where(x => _excludedTypesList.Contains(x) == false))
{
AddValidAndNoDuplicate(resolvedTypes, type);
}
return resolvedTypes;
});
}
/// <summary>
/// Gets a value indicating whether the resolver has resolved types to create instances from.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
public bool HasResolvedTypes
{
get { return _resolvedTypes.IsValueCreated; }
}
/// <summary>
/// Gets the list of types to create instances from.
/// </summary>
/// <remarks>When called, will get the types from the lazy list.</remarks>
protected override IEnumerable<Type> InstanceTypes
{
get { return _resolvedTypes.Value; }
}
/// <summary>
/// Ensures that type is valid and not a duplicate
/// then appends the type to the end of the list
/// </summary>
/// <param name="list"></param>
/// <param name="type"></param>
private void AddValidAndNoDuplicate(List<Type> list, Type type)
{
EnsureCorrectType(type);
if (list.Contains(type))
{
throw new InvalidOperationException(string.Format(
"Type {0} is already in the collection of types.", type.FullName));
}
list.Add(type);
}
#region Types collection manipulation
/// <summary>
/// Removes types from the list of types, once it has been lazily evaluated, and before actual objects are instanciated.
/// </summary>
/// <param name="value">The type to remove.</param>
public override void RemoveType(Type value)
{
EnsureSupportsRemove();
_excludedTypesList.Add(value);
}
/// <summary>
/// Lazily adds types from lazy types.
/// </summary>
/// <param name="types">The lazy types, to add.</param>
protected void AddTypes(IEnumerable<Lazy<Type>> types)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
foreach (var t in types)
{
_lazyTypeList.Add(t);
}
}
}
/// <summary>
/// Lazily adds types from a function producing types.
/// </summary>
/// <param name="typeListProducer">The functions producing types, to add.</param>
public void AddTypeListDelegate(Func<IEnumerable<Type>> typeListProducer)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
_typeListProducerList.Add(typeListProducer);
}
}
/// <summary>
/// Lazily adds a type from a lazy type.
/// </summary>
/// <param name="value">The lazy type, to add.</param>
public void AddType(Lazy<Type> value)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
_lazyTypeList.Add(value);
}
}
/// <summary>
/// Lazily adds a type from an actual type.
/// </summary>
/// <param name="value">The actual type, to add.</param>
/// <remarks>The type is converted to a lazy type.</remarks>
public override void AddType(Type value)
{
AddType(new Lazy<Type>(() => value));
}
/// <summary>
/// Clears all lazy types
/// </summary>
public override void Clear()
{
EnsureSupportsClear();
using (Resolution.Configuration)
using (GetWriteLock())
{
_lazyTypeList.Clear();
}
}
#endregion
#region Types collection manipulation support
/// <summary>
/// Gets a <c>false</c> value indicating that the resolver does NOT support inserting types.
/// </summary>
protected override bool SupportsInsert
{
get { return false; }
}
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web.Configuration;
using System.Xml.Linq;
using System.Xml.XPath;
using ASC.Common;
using ASC.Common.Data;
using ASC.Common.Logging;
namespace ASC.Data.Backup
{
public class DbBackupProvider : IBackupProvider
{
private readonly List<string> processedTables = new List<string>();
public string Name
{
get { return "databases"; }
}
public IEnumerable<XElement> GetElements(int tenant, string[] configs, IDataWriteOperator writer)
{
processedTables.Clear();
var xml = new List<XElement>();
var connectionKeys = new Dictionary<string, string>();
foreach (var connectionString in GetConnectionStrings(configs))
{
//do not save the base, having the same provider and connection string is not to duplicate
//data, but also expose the ref attribute of repetitive bases for the correct recovery
var node = new XElement(connectionString.Name);
xml.Add(node);
var connectionKey = connectionString.ProviderName + connectionString.ConnectionString;
if (connectionKeys.ContainsKey(connectionKey))
{
node.Add(new XAttribute("ref", connectionKeys[connectionKey]));
}
else
{
connectionKeys.Add(connectionKey, connectionString.Name);
node.Add(BackupDatabase(tenant, connectionString, writer));
}
}
return xml;
}
public void LoadFrom(IEnumerable<XElement> elements, int tenant, string[] configs, IDataReadOperator reader)
{
processedTables.Clear();
foreach (var connectionString in GetConnectionStrings(configs))
{
RestoreDatabase(connectionString, elements, reader);
}
}
public event EventHandler<ProgressChangedEventArgs> ProgressChanged;
private void OnProgressChanged(string status, int progress)
{
if (ProgressChanged != null) ProgressChanged(this, new ProgressChangedEventArgs(status, progress));
}
private Configuration GetConfiguration(string config)
{
if (config.Contains(Path.DirectorySeparatorChar) && !Uri.IsWellFormedUriString(config, UriKind.Relative))
{
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = string.Compare(Path.GetExtension(config), ".config", true) == 0 ?
config :
Path.Combine(config, "Web.config");
return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
}
return WebConfigurationManager.OpenWebConfiguration(config);
}
private IEnumerable<ConnectionStringSettings> GetConnectionStrings(string[] configs)
{
if (configs.Length == 0)
{
configs = new string[] { AppDomain.CurrentDomain.SetupInformation.ConfigurationFile };
}
var connectionStrings = new List<ConnectionStringSettings>();
foreach (var config in configs)
{
connectionStrings.AddRange(GetConnectionStrings(GetConfiguration(config)));
}
return connectionStrings.GroupBy(cs => cs.Name).Select(g => g.First());
}
private IEnumerable<ConnectionStringSettings> GetConnectionStrings(Configuration cfg)
{
var connectionStrings = new List<ConnectionStringSettings>();
foreach (ConnectionStringSettings connectionString in cfg.ConnectionStrings.ConnectionStrings)
{
if (connectionString.Name == "LocalSqlServer" || connectionString.Name == "readonly") continue;
connectionStrings.Add(connectionString);
if (connectionString.ConnectionString.Contains("|DataDirectory|"))
{
connectionString.ConnectionString = connectionString.ConnectionString.Replace("|DataDirectory|", Path.GetDirectoryName(cfg.FilePath) + '\\');
}
}
return connectionStrings;
}
private List<XElement> BackupDatabase(int tenant, ConnectionStringSettings connectionString, IDataWriteOperator writer)
{
var xml = new List<XElement>();
var errors = 0;
var timeout = TimeSpan.FromSeconds(1);
using (var dbHelper = new DbHelper(connectionString))
{
var tables = dbHelper.GetTables();
for (int i = 0; i < tables.Count; i++)
{
var table = tables[i];
OnProgressChanged(table, (int)(i / (double)tables.Count * 100));
if (processedTables.Contains(table, StringComparer.InvariantCultureIgnoreCase))
{
continue;
}
xml.Add(new XElement(table));
DataTable dataTable = null;
while (true)
{
try
{
dataTable = dbHelper.GetTable(table, tenant);
break;
}
catch
{
errors++;
if (20 < errors) throw;
Thread.Sleep(timeout);
}
}
foreach (DataColumn c in dataTable.Columns)
{
if (c.DataType == typeof(DateTime)) c.DateTimeMode = DataSetDateTime.Unspecified;
}
using (var file = TempStream.Create())
{
dataTable.WriteXml(file, XmlWriteMode.WriteSchema);
writer.WriteEntry(string.Format("{0}\\{1}\\{2}", Name, connectionString.Name, table).ToLower(), file);
}
processedTables.Add(table);
}
}
return xml;
}
private void RestoreDatabase(ConnectionStringSettings connectionString, IEnumerable<XElement> elements, IDataReadOperator reader)
{
var dbName = connectionString.Name;
var dbElement = elements.SingleOrDefault(e => string.Compare(e.Name.LocalName, connectionString.Name, true) == 0);
if (dbElement != null && dbElement.Attribute("ref") != null)
{
dbName = dbElement.Attribute("ref").Value;
dbElement = elements.Single(e => string.Compare(e.Name.LocalName, dbElement.Attribute("ref").Value, true) == 0);
}
if (dbElement == null) return;
using (var dbHelper = new DbHelper(connectionString))
{
var tables = dbHelper.GetTables();
for (int i = 0; i < tables.Count; i++)
{
var table = tables[i];
OnProgressChanged(table, (int)(i / (double)tables.Count * 100));
if (processedTables.Contains(table, StringComparer.InvariantCultureIgnoreCase))
{
continue;
}
if (dbElement.Element(table) != null)
{
using (var stream = reader.GetEntry(string.Format("{0}\\{1}\\{2}", Name, dbName, table).ToLower()))
{
var data = new DataTable();
data.ReadXml(stream);
dbHelper.SetTable(data);
}
processedTables.Add(table);
}
}
}
}
private class DbHelper : IDisposable
{
private readonly DbProviderFactory factory;
private readonly DbConnection connect;
private readonly DbCommandBuilder builder;
private readonly DataTable columns;
private readonly bool mysql;
private readonly IDictionary<string, string> whereExceptions = new Dictionary<string, string>();
private readonly static ILog log = LogManager.GetLogger("ASC.Data");
public DbHelper(ConnectionStringSettings connectionString)
{
var file = connectionString.ElementInformation.Source;
if ("web.connections.config".Equals(Path.GetFileName(file), StringComparison.InvariantCultureIgnoreCase))
{
file = Path.Combine(Path.GetDirectoryName(file), "Web.config");
}
var xconfig = XDocument.Load(file);
var provider = xconfig.XPathSelectElement("/configuration/system.data/DbProviderFactories/add[@invariant='" + connectionString.ProviderName + "']");
factory = (DbProviderFactory)Activator.CreateInstance(Type.GetType(provider.Attribute("type").Value, true));
builder = factory.CreateCommandBuilder();
connect = factory.CreateConnection();
connect.ConnectionString = connectionString.ConnectionString;
connect.Open();
mysql = connectionString.ProviderName.ToLower().Contains("mysql");
if (mysql)
{
CreateCommand("set @@session.sql_mode = concat(@@session.sql_mode, ',NO_AUTO_VALUE_ON_ZERO')").ExecuteNonQuery();
}
columns = connect.GetSchema("Columns");
whereExceptions["calendar_calendar_item"] = " where calendar_id in (select id from calendar_calendars where tenant = {0}) ";
whereExceptions["calendar_calendar_user"] = " where calendar_id in (select id from calendar_calendars where tenant = {0}) ";
whereExceptions["calendar_event_item"] = " inner join calendar_events on calendar_event_item.event_id = calendar_events.id where calendar_events.tenant = {0} ";
whereExceptions["calendar_event_user"] = " inner join calendar_events on calendar_event_user.event_id = calendar_events.id where calendar_events.tenant = {0} ";
whereExceptions["crm_entity_contact"] = " inner join crm_contact on crm_entity_contact.contact_id = crm_contact.id where crm_contact.tenant_id = {0} ";
whereExceptions["crm_entity_tag"] = " inner join crm_tag on crm_entity_tag.tag_id = crm_tag.id where crm_tag.tenant_id = {0} ";
whereExceptions["files_folder_tree"] = " inner join files_folder on folder_id = id where tenant_id = {0} ";
whereExceptions["forum_answer_variant"] = " where answer_id in (select id from forum_answer where tenantid = {0})";
whereExceptions["forum_topic_tag"] = " where topic_id in (select id from forum_topic where tenantid = {0})";
whereExceptions["forum_variant"] = " where question_id in (select id from forum_question where tenantid = {0})";
whereExceptions["projects_project_participant"] = " inner join projects_projects on projects_project_participant.project_id = projects_projects.id where projects_projects.tenant_id = {0} ";
whereExceptions["projects_following_project_participant"] = " inner join projects_projects on projects_following_project_participant.project_id = projects_projects.id where projects_projects.tenant_id = {0} ";
whereExceptions["projects_project_tag"] = " inner join projects_projects on projects_project_tag.project_id = projects_projects.id where projects_projects.tenant_id = {0} ";
whereExceptions["tenants_tenants"] = " where id = {0}";
whereExceptions["core_acl"] = " where tenant = {0} or tenant = -1";
whereExceptions["core_subscription"] = " where tenant = {0} or tenant = -1";
whereExceptions["core_subscriptionmethod"] = " where tenant = {0} or tenant = -1";
}
public List<string> GetTables()
{
var allowTables = new List<string>
{
"blogs_",
"bookmarking_",
"calendar_",
"core_",
"crm_",
"events_",
"files_",
"forum_",
"photo_",
"projects_",
"tenants_",
"webstudio_",
"wiki_",
};
var disallowTables = new List<string>
{
"core_settings",
"webstudio_uservisit",
"webstudio_useractivity",
"tenants_forbiden"
};
IEnumerable<string> tables;
if (mysql)
{
tables = CreateCommand("show tables")
.ExecuteList()
.ConvertAll(r => (string)r[0]);
}
else
{
tables = connect
.GetSchema("Tables")
.Select(@"TABLE_TYPE <> 'SYSTEM_TABLE'")
.Select(row => ((string)row["TABLE_NAME"]));
}
return tables
.Where(t => allowTables.Any(a => t.StartsWith(a)) && !disallowTables.Any(d => t.StartsWith(d)))
.ToList();
}
public DataTable GetTable(string table, int tenant)
{
try
{
var dataTable = new DataTable(table);
var adapter = factory.CreateDataAdapter();
adapter.SelectCommand = CreateCommand("select " + Quote(table) + ".* from " + Quote(table) + GetWhere(table, tenant));
log.Debug(adapter.SelectCommand.CommandText);
adapter.Fill(dataTable);
return dataTable;
}
catch (Exception error)
{
log.ErrorFormat("Table {0}: {1}", table, error);
throw;
}
}
public void SetTable(DataTable table)
{
using (var tx = connect.BeginTransaction())
{
try
{
if ("tenants_tenants".Equals(table.TableName, StringComparison.InvariantCultureIgnoreCase))
{
// remove last tenant
var tenantid = CreateCommand("select id from tenants_tenants order by id desc limit 1").ExecuteScalar<int>();
CreateCommand("delete from tenants_tenants where id = " + tenantid).ExecuteNonQuery();
if (table.Columns.Contains("mappeddomain"))
{
foreach (var r in table.Rows.Cast<DataRow>())
{
r[table.Columns["mappeddomain"]] = null;
if (table.Columns.Contains("id"))
{
CreateCommand("update tenants_tariff set tenant = " + r[table.Columns["id"]] + " where tenant = " + tenantid).ExecuteNonQuery();
}
}
}
}
var sql = new StringBuilder("replace into " + Quote(table.TableName) + "(");
var tableColumns = GetColumnsFrom(table.TableName)
.Intersect(table.Columns.Cast<DataColumn>().Select(c => c.ColumnName), StringComparer.InvariantCultureIgnoreCase)
.ToList();
tableColumns.ForEach(column => sql.AppendFormat("{0}, ", Quote(column)));
sql.Replace(", ", ") values (", sql.Length - 2, 2);
var insert = connect.CreateCommand();
tableColumns.ForEach(column =>
{
sql.AppendFormat("@{0}, ", column);
var p = insert.CreateParameter();
p.ParameterName = "@" + column;
insert.Parameters.Add(p);
});
sql.Replace(", ", ")", sql.Length - 2, 2);
insert.CommandText = sql.ToString();
foreach (var r in table.Rows.Cast<DataRow>())
{
foreach (var c in tableColumns)
{
((IDbDataParameter)insert.Parameters["@" + c]).Value = r[c];
}
insert.ExecuteNonQuery();
}
tx.Commit();
}
catch (Exception e)
{
log.ErrorFormat("Table {0}: {1}", table, e);
}
}
}
public void Dispose()
{
builder.Dispose();
connect.Dispose();
}
private DbCommand CreateCommand(string sql)
{
var command = connect.CreateCommand();
command.CommandText = sql;
return command;
}
private string Quote(string identifier)
{
return identifier;
}
private IEnumerable<string> GetColumnsFrom(string table)
{
if (mysql)
{
return CreateCommand("show columns from " + Quote(table))
.ExecuteList()
.ConvertAll(r => (string)r[0]);
}
else
{
return columns.Select(string.Format("TABLE_NAME = '{0}'", table))
.Select(r => r["COLUMN_NAME"].ToString());
}
}
private string GetWhere(string tableName, int tenant)
{
if (tenant == -1) return string.Empty;
if (whereExceptions.ContainsKey(tableName.ToLower()))
{
return string.Format(whereExceptions[tableName.ToLower()], tenant);
}
var tenantColumn = GetColumnsFrom(tableName).FirstOrDefault(c => c.ToLower().StartsWith("tenant"));
return tenantColumn != null ?
" where " + Quote(tenantColumn) + " = " + tenant :
" where 1 = 0";
}
}
}
}
| |
using NUnit.Framework;
using System.Linq;
using StreetPacMan.Server.Facade;
using StreetPacMan.Server.Rules;
using StreetPacMan.Server.Tests.Infra;
namespace StreetPacMan.Server.Tests.Integ
{
[TestFixture]
public class ApplesEating : BaseCleaner
{
private static readonly InitialApple AppleGeo = new TestAppleLocationsProvider().GetInitialApples().First();
[Test]
public void DoServerPoll_AsPacMan_PollsInSameGeoOfApple_NotifyThatAppleRemoved()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var retVal = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, AppleGeo.Lat, AppleGeo.Lon, true));
CollectionAssert.IsNotEmpty(retVal.RemovedAppleIds);
}
[Test]
public void DoServerPoll_AsPacMan_PollsNotInSameGeoOfApple_NoAppleRemoved()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var retVal = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, 0, 0, true));
CollectionAssert.IsEmpty(retVal.RemovedAppleIds);
}
[Test]
public void DoServerPoll_AsPacMan_PollsInSameGeoOfApple_NotifyThatApplesRemoveOnEnsuingCalls()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var retVal1 = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, AppleGeo.Lat, AppleGeo.Lon, true));
var retVal2 = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, AppleGeo.Lat + 1, AppleGeo.Lon + 1, true));
CollectionAssert.IsNotEmpty(retVal2.RemovedAppleIds);
}
[Test]
public void DoServerPoll_AsPacMan_PollsInDifferentGeoAsApple_NoNotifyOnRemovalOnEnsuingCalls()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var retVal1 = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, 0, 0, true));
var retVal2 = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, 1,1, true));
CollectionAssert.IsEmpty(retVal2.RemovedAppleIds);
}
[Test]
public void DoServerPoll_AsPacMan_PollsInSameGeoOfApple_MakeSureTheAppleDoesNotReturnOfCallsToGetAllApples()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var initialAppleCount = instance.GetGameStateForX(pacman.PlayerId).Apples.Count();
instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, AppleGeo.Lat, AppleGeo.Lon, true));
var postPollAppleCount = instance.GetGameStateForX(pacman.PlayerId).Apples.Count();
Assert.AreNotEqual(initialAppleCount, postPollAppleCount);
}
[Test]
public void DoServerPoll_AsPacMan_PollsInNonSameGeoOfApple_MakeSureAllTheAppleReturnInCallsToGetAllApples()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var initialAppleCount = instance.GetGameStateForX(pacman.PlayerId).Apples.Count();
instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, 0,0, true));
var postPollAppleCount = instance.GetGameStateForX(pacman.PlayerId).Apples.Count();
Assert.AreEqual(initialAppleCount , postPollAppleCount);
}
[Test]
public void DoServerPoll_AsPacMan_PollsInNonSameGeoOfApple_ScoreStaysSame()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var earlyScore = instance.GetGameStateForX(pacman.PlayerId).Score;
instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, 0,0, true));
var currentScore = instance.GetGameStateAsObvserverX("GameName").Score;
Assert.AreEqual(earlyScore, currentScore);
}
[Test]
public void DoServerPoll_AsPacMan_PollsInSameGeoOfApple_Add10PointsToScore()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var earlyScore = instance.GetGameStateForX(pacman.PlayerId).Score;
instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, AppleGeo.Lat, AppleGeo.Lon, true));
var currentScore = instance.GetGameStateAsObvserverX("GameName").Score;
Assert.AreEqual(earlyScore + AddScoreForEatenApplesRule.PointsForEatingApple, currentScore);
}
[Test]
public void DoServerPoll_AsPacMan_PollsInSameGeoOfApple_EventForEatingAppleShouldBeAdded()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, AppleGeo.Lat, AppleGeo.Lon, true));
var gameEvents = instance.GetAllEventsX("GameName");
CollectionAssert.IsNotEmpty(gameEvents.Events.Where(x=>x.Type==EventType.PacManAteApple).ToArray());
}
[Test]
public void DoServerPoll_AsPacMan_PollsInSameGeoOfApple_Twice_AddScoreAsIfAppleWasEatenOnlyOnce()
{
var instance = ServerFacadeFactory.GetServerFacade();
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var earlyScore = instance.GetGameStateForX(pacman.PlayerId).Score;
instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, AppleGeo.Lat, AppleGeo.Lon, true));
instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, AppleGeo.Lat, AppleGeo.Lon, true));
var currentScore = instance.GetGameStateAsObvserverX("GameName").Score;
Assert.AreEqual(earlyScore + AddScoreForEatenApplesRule.PointsForEatingApple, currentScore);
}
[TestCase(AppleKind.Normal, AddScoreForEatenApplesRule.PointsForEatingApple)]
[TestCase(AppleKind.Super, AddScoreForEatenApplesRule.PointsForEatingSuperApple)]
[TestCase(AppleKind.Cherry, AddScoreForEatenApplesRule.PointsForEatingCherry)]
public void DoServerPoll_AsPacMan_EatApple_AddTheCorrectScorePerAppleType(AppleKind kind, int points)
{
var singleAppleLocation = new InitialApple { Lat = 2, Lon = 2, Type = kind };
var instance = ServerFacadeFactory.CreateGameWithApplesOnlyAt(singleAppleLocation, new InitialApple{Lat=3, Lon=3} );
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var earlyScore = instance.GetGameStateForX(pacman.PlayerId).Score;
instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, singleAppleLocation.Lat, singleAppleLocation.Lon, true));
var currentScore = instance.GetGameStateAsObvserverX("GameName").Score;
Assert.AreEqual(earlyScore + points, currentScore);
}
[Test]
public void DoServerPoll_AsPacMan_EatTheLastAppleLeftOnBoard_ShouldSendMessageOfGameOverPacManWins()
{
var singleAppleLocation = new InitialApple { Lat = 2, Lon = 2,Type=AppleKind.Normal };
var instance = ServerFacadeFactory.CreateGameWithApplesOnlyAt(singleAppleLocation);
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var retVal = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, singleAppleLocation.Lat, singleAppleLocation.Lon, true));
Assert.AreEqual(
string.Format("Game Over! PacMen win with {0} points!", AddScoreForEatenApplesRule.PointsForEatingApple),
retVal.RecentMessages.Last().Body);
}
[Test]
public void DoServerPoll_AsPacMan_EatTheLastSuperAppleLeftOnBoard_ShouldSendMessageOfGameOverPacManWins()
{
var singleAppleLocation = new InitialApple { Lat = 2, Lon = 2, Type = AppleKind.Super };
var instance = ServerFacadeFactory.CreateGameWithApplesOnlyAt(singleAppleLocation);
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var retVal = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, singleAppleLocation.Lat, singleAppleLocation.Lon, true));
Assert.AreEqual(
string.Format("Game Over! PacMen win with {0} points!", AddScoreForEatenApplesRule.PointsForEatingSuperApple),
retVal.RecentMessages.Last().Body);
}
[Test]
public void DoServerPoll_AsPacMan_EatSuperApple_ShouldSendMessageThatPacManIsNowSuper()
{
var singleAppleLocation = new InitialApple { Lat = 2, Lon = 2, Type = AppleKind.Super };
var instance = ServerFacadeFactory.CreateGameWithExtraApplesAt(singleAppleLocation);
instance.CreateGameX("GameName");
var pacman = instance.JoinGameX("GameName", "PacManName", PlayerRole.PacMan);
var retVal = instance.UpdateMyWhereabouts(new ServerPollParameters(pacman.PlayerId, singleAppleLocation.Lat, singleAppleLocation.Lon, true));
Assert.AreEqual("PacManName has eaten a power pellet!", retVal.RecentMessages.Last().Body);
Assert.AreEqual(GameState.SuperPacMan, retVal.GameState);
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using global::WOSI.CallButler.Data;
namespace WOSI.CallButler.ManagementInterface
{
[Serializable]
public class AudioCodecInformation
{
public string Name = "";
public bool Enabled = false;
public override string ToString()
{
return Name;
}
}
public interface ICallButlerManagementInterface
{
bool IsConnected { get;}
bool ReportErrors{get;set;}
#region Settings Functions
bool GetMultilingual(CallButlerAuthInfo authInfo);
void SetMultilingual(CallButlerAuthInfo authInfo, bool isMultilingual);
string GetDefaultLanguage(CallButlerAuthInfo authInfo);
void SetDefaultLanguage(CallButlerAuthInfo authInfo, string defLanguage);
string GetLanguages(CallButlerAuthInfo authInfo);
void SetLanguages(CallButlerAuthInfo authInfo, string languages);
string GetApplicationPermissions(CallButlerAuthInfo authInfo);
int LineCount { get;set;}
string SMTPServer { get;set;}
int SMTPPort { get;set;}
bool SMTPUseSSL { get;set;}
string SMTPUsername { get;set;}
string SMTPPassword { get;set;}
string SMTPFromEmail { get;set;}
string[] GetTTSVoices();
byte[] PrivateLabelData { get;}
string ProductID { get;}
string SplashInfo { get;}
System.Collections.Specialized.NameValueCollection AvailableEditions { get;}
void SetProductID(CallButlerAuthInfo authInfo, string productID);
string ProductDescription { get;}
string TelephoneNumberDescription { get;}
string AdditionalCopyrightNotice { get;}
string HoldMusicLocation { get; set;}
int SIPPort { get;set;}
bool EnableSTUN { get;set;}
bool UseInternalAddressForSIP { get;set;}
string STUNServer { get;set;}
string LicenseName { get;set;}
string LicenseKey { get; set;}
DateTime LicenseExpiration { get;}
bool IsLicensed { get;}
bool IsFreeVersion { get;}
DateTime TrialExpiration { get;}
bool IsDownloadRegistered { get;set;}
Version ServerVersion { get;}
bool ExpertModeEnabled { get; set; }
LogLevel LogLevel { get; set;}
LogStorage LogStorage { get;set;}
bool AllowRemoteManagement { get;set;}
AudioCodecInformation[] GetAudioCodecs(CallButlerAuthInfo authInfo);
void SetAudioCodecs(CallButlerAuthInfo authInfo, AudioCodecInformation[] codecs);
void SetManagementPassword(CallButlerAuthInfo authInfo, string password);
string GetManagementPassword(CallButlerAuthInfo authInfo);
void SetAnswerTimeout(CallButlerAuthInfo authInfo, int answerTimeout);
int GetAnswerTimeout(CallButlerAuthInfo authInfo);
void SetWelcomeGreetingDelay(CallButlerAuthInfo authInfo, int delay);
int GetWelcomeGreetingDelay(CallButlerAuthInfo authInfo);
string GetLogErrorEmail(CallButlerAuthInfo authInfo);
void SetLogErrorEmail(CallButlerAuthInfo authInfo, string emailAddress);
bool GetSendLogErrorEmail(CallButlerAuthInfo authInfo);
void SetSendLogErrorEmail(CallButlerAuthInfo authInfo, bool sendEmail);
bool GetReceptionistEnabled(CallButlerAuthInfo authInfo);
void SetReceptionistEnabled(CallButlerAuthInfo authInfo, bool enabled);
Guid GetReceptionistExtension(CallButlerAuthInfo authInfo);
void SetReceptionistExtension(CallButlerAuthInfo authInfo, Guid extensionID);
string GetBusyRedirectServer(CallButlerAuthInfo authInfo);
void SetBusyRedirectServer(CallButlerAuthInfo authInfo, string server);
#region PBX Settings Functions
int GetPBXRegistrationTimeout(CallButlerAuthInfo authInfo);
void SetPBXRegistrationTimeout(CallButlerAuthInfo authInfo, int timeout);
string GetPBXDialPrefix(CallButlerAuthInfo authInfo);
void SetPBXDialPrefix(CallButlerAuthInfo authInfo, string dialPrefix);
string GetPBXRegistrarDomain(CallButlerAuthInfo authInfo);
void SetPBXRegistrarDomain(CallButlerAuthInfo authInfo, string domain);
#endregion
#endregion
#region Outbound Call Functions
void PlaceGreetingRecordCall(CallButlerAuthInfo authInfo, string numberToCall, Guid greetingID, string languageID);
#endregion
#region Service Functions
void RestartService(CallButlerAuthInfo authInfo);
#endregion
#region Status Functions
global::WOSI.CallButler.Data.CallButlerPhoneStatusDataset.PhoneStatusDataTable GetPhoneExtensionStatus(CallButlerAuthInfo authInfo);
#endregion
#region Plugin Functions
Guid[] GetInstalledServicePlugins();
Guid[] GetInstalledAddonModules();
object ExchangePluginData(CallButlerAuthInfo authInfo, Guid pluginID, string method, object data);
#endregion
#region Scheduling Functions
void PlaceScheduleReminderCall(CallButlerAuthInfo authInfo, Guid extensionID, OutlookReminder [] reminders);
//void PlaceScheduleReminderCall(CallButlerAuthInfo authInfo, Guid [] extensionID, DateTime [] scheduleTime, string [] subject, string [] location);
#endregion
#region Call History Functions
void ClearCallHistory(CallButlerAuthInfo authInfo);
CallButlerDataset.CallHistoryDataTable GetCallHistory(CallButlerAuthInfo authInfo);
CallButlerDataset.CallHistoryDataTable GetRecentCalls(CallButlerAuthInfo authInfo, int count);
#endregion
#region Extension Functions
CallButlerDataset.ExtensionsDataTable GetExtensions(CallButlerAuthInfo authInfo);
CallButlerDataset.ExtensionsDataTable GetExtensionNumber(CallButlerAuthInfo authInfo, int extensionNumber);
CallButlerDataset.LocalizedGreetingsDataTable GetExtensionVoicemailGreeting(CallButlerAuthInfo authInfo, Guid extensionID);
void PersistExtension(CallButlerAuthInfo authInfo, global::WOSI.CallButler.Data.CallButlerDataset.ExtensionsDataTable extension);
void DeleteExtension(CallButlerAuthInfo authInfo, Guid extensionID);
CallButlerDataset.ExtensionContactNumbersDataTable GetExtensionContactNumbers(CallButlerAuthInfo authInfo, Guid extensionID);
void PersistExtensionContactNumbers(CallButlerAuthInfo authInfo, global::WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersDataTable changes);
void DeleteExtensionContactNumber(CallButlerAuthInfo authInfo, Guid extensionId, Guid extensionContactNumberID);
#endregion
#region Voicemail Functions
byte[] GetVoicemailSound(CallButlerAuthInfo authInfo,Guid extensionID, Guid voicemailId);
CallButlerDataset.VoicemailsDataTable GetVoicemails(CallButlerAuthInfo authInfo, Guid extensionID);
CallButlerDataset.VoicemailsDataTable GetVoicemails(CallButlerAuthInfo authInfo);
void PersistVoicemail(CallButlerAuthInfo authInfo, CallButlerDataset.VoicemailsDataTable voicemail);
void DeleteVoicemail(CallButlerAuthInfo authInfo, Guid extensionId, Guid voicemailID);
#endregion
#region Department Functions
CallButlerDataset.DepartmentsDataTable GetDepartments(CallButlerAuthInfo authInfo);
void PersistDepartment(CallButlerAuthInfo authInfo, CallButlerDataset.DepartmentsDataTable department);
void DeleteDepartment(CallButlerAuthInfo authInfo, Guid departmentID);
#endregion
#region GreetingsFunctions
void DeleteGreeting(CallButlerAuthInfo authInfo, Guid greetingID);
CallButlerDataset.LocalizedGreetingsDataTable GetLocalizedGreeting(CallButlerAuthInfo authInfo, Guid greetingID, string languageID);
CallButlerDataset.LocalizedGreetingsDataTable GetLocalizedGreeting(CallButlerAuthInfo authInfo, Guid greetingID, Guid localizedGreetingID);
CallButlerDataset.LocalizedGreetingsDataTable GetLocalizedGreetingInDefaultLanguage(CallButlerAuthInfo authInfo, Guid greetingID);
void PersistLocalizedGreeting(CallButlerAuthInfo authInfo, global::WOSI.CallButler.Data.CallButlerDataset.LocalizedGreetingsDataTable localizedGreeting);
byte[] GetLocalizedGreetingSound(CallButlerAuthInfo authInfo, Guid greetingID, Guid localizedGreetingID);
void PersistLocalizedGreetingSound(CallButlerAuthInfo authInfo, Guid greetingID, Guid localizedGreetingID, byte[] soundBytes);
#endregion
#region Client Functions
CallButlerDataset.ExtensionsDataTable GetEmployeeExtension(CallButlerAuthInfo authInfo, int extension, string password);
CallButlerDataset.VoicemailsDataTable GetNewEmployeeVoicemails(CallButlerAuthInfo authInfo, Guid extensionId);
bool DoesEmployeeHaveNewVoicemails(CallButlerAuthInfo authInfo, Guid extensionId);
#endregion
#region Personalized Greeting Functions
CallButlerDataset.PersonalizedGreetingsDataTable GetPersonalizedGreetings(CallButlerAuthInfo authInfo);
void PersistPersonalizedGreeting(CallButlerAuthInfo authInfo, CallButlerDataset.PersonalizedGreetingsDataTable personalizedGreeting);
void DeletePersonalizedGreeting(CallButlerAuthInfo authInfo, Guid personalizedGreetingID);
#endregion
#region Provider Functions
CallButlerDataset.ProvidersDataTable GetProviders(CallButlerAuthInfo authInfo);
void PersistProviders(CallButlerAuthInfo authInfo, CallButlerDataset.ProvidersDataTable providers);
void DeleteProvider(CallButlerAuthInfo authInfo, Guid providerID);
#endregion
#region Script Schedule Functions
CallButlerDataset.ScriptSchedulesDataTable GetScriptSchedules(CallButlerAuthInfo authInfo);
void PersistScriptSchedule(CallButlerAuthInfo authInfo, CallButlerDataset.ScriptSchedulesDataTable scriptSchedules);
void DeleteScriptSchedule(CallButlerAuthInfo authInfo, Guid scriptScheduleID);
#endregion
void PersistVoicemailSound(CallButlerAuthInfo authInfo, Guid extensionID, CallButlerDataset.ExtensionsDataTable extensions, byte[] soundBytes);
int GetCustomerLogin(string login, string managementPassword);
string GetHostedTestAddress(CallButlerAuthInfo authInfo);
bool GetFirstTimeRun(CallButlerAuthInfo authInfo);
void SetFirstTimeRun(CallButlerAuthInfo authInfo, bool val);
byte GetRecordVolume(CallButlerAuthInfo authInfo);
void SetRecordVolume(CallButlerAuthInfo authInfo, byte recordVolume);
byte GetSoundVolume(CallButlerAuthInfo authInfo);
void SetSoundVolume(CallButlerAuthInfo authInfo, byte soundVolume);
byte GetSpeechVolume(CallButlerAuthInfo authInfo);
void SetSpeechVolume(CallButlerAuthInfo authInfo, byte speechVolume);
string GetDefaultVoice(CallButlerAuthInfo authInfo);
void SetDefaultVoice(CallButlerAuthInfo authInfo, string defaultVoice);
void SendEmail( CallButlerAuthInfo authInfo, string sendTo, string subject, string message);
void SendTestEmail(CallButlerAuthInfo authInfo, string sendTo, string subject, string message, string smtpServer, int smtpPort, bool useSSL, string smtpUsername, string smtpPassword);
string [] GetHoldMusic(CallButlerAuthInfo authInfo);
void DeleteHoldMusic(CallButlerAuthInfo authInfo, string fileName);
void PersistHoldMusic(CallButlerAuthInfo authInfo, string fileName, byte[] soundBytes);
}
}
| |
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 DurandalAuth.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .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 XorSingle()
{
var test = new SimpleBinaryOpTest__XorSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// 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();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorSingle
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single> _dataTable;
static SimpleBinaryOpTest__XorSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__XorSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Xor(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Xor(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Xor(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorSingle();
var result = Avx.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Single> left, Vector256<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if ((BitConverter.SingleToInt32Bits(left[0]) ^ BitConverter.SingleToInt32Bits(right[0])) != BitConverter.SingleToInt32Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((BitConverter.SingleToInt32Bits(left[i]) ^ BitConverter.SingleToInt32Bits(right[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Xor)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using BTDB.Buffer;
namespace BTDB.KVDBLayer.BTreeMem
{
class BTreeLeafComp : IBTreeLeafNode, IBTreeNode
{
internal readonly long TransactionId;
byte[] _keyBytes;
struct Member
{
internal ushort KeyOffset;
internal ushort KeyLength;
internal byte[] Value;
}
Member[] _keyvalues;
internal const long MaxTotalLen = ushort.MaxValue;
internal const int MaxMembers = 30;
BTreeLeafComp(long transactionId, int length)
{
TransactionId = transactionId;
_keyvalues = new Member[length];
}
internal BTreeLeafComp(long transactionId, BTreeLeafMember[] newKeyValues)
{
Debug.Assert(newKeyValues.Length > 0 && newKeyValues.Length <= MaxMembers);
TransactionId = transactionId;
_keyBytes = new byte[newKeyValues.Sum(m => m.Key.Length)];
_keyvalues = new Member[newKeyValues.Length];
ushort ofs = 0;
for (var i = 0; i < newKeyValues.Length; i++)
{
_keyvalues[i] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort)newKeyValues[i].Key.Length,
Value = newKeyValues[i].Value
};
Array.Copy(newKeyValues[i].Key, 0, _keyBytes, ofs, _keyvalues[i].KeyLength);
ofs += _keyvalues[i].KeyLength;
}
}
BTreeLeafComp(long transactionId, byte[] newKeyBytes, Member[] newKeyValues)
{
TransactionId = transactionId;
_keyBytes = newKeyBytes;
_keyvalues = newKeyValues;
}
internal static IBTreeNode CreateFirst(CreateOrUpdateCtx ctx)
{
Debug.Assert(ctx.WholeKeyLen <= MaxTotalLen);
var result = new BTreeLeafComp(ctx.TransactionId, 1);
result._keyBytes = ctx.WholeKey();
result._keyvalues[0] = new Member
{
KeyOffset = 0,
KeyLength = (ushort)result._keyBytes.Length,
Value = ctx.Value.ToByteArray()
};
return result;
}
int Find(byte[] prefix, ByteBuffer key)
{
var left = 0;
var right = _keyvalues.Length;
var keyBytes = _keyBytes;
while (left < right)
{
var middle = (left + right) / 2;
int currentKeyOfs = _keyvalues[middle].KeyOffset;
int currentKeyLen = _keyvalues[middle].KeyLength;
var result = BitArrayManipulation.CompareByteArray(prefix, 0, prefix.Length,
keyBytes, currentKeyOfs, Math.Min(currentKeyLen, prefix.Length));
if (result == 0)
{
result = BitArrayManipulation.CompareByteArray(key.Buffer, key.Offset, key.Length,
keyBytes, currentKeyOfs + prefix.Length, currentKeyLen - prefix.Length);
if (result == 0)
{
return middle * 2 + 1;
}
}
if (result < 0)
{
right = middle;
}
else
{
left = middle + 1;
}
}
return left * 2;
}
public void CreateOrUpdate(CreateOrUpdateCtx ctx)
{
var index = Find(ctx.KeyPrefix, ctx.Key);
if ((index & 1) == 1)
{
index = index / 2;
ctx.Created = false;
ctx.KeyIndex = index;
var m = _keyvalues[index];
m.Value = ctx.Value.ToByteArray();
var leaf = this;
if (ctx.TransactionId != TransactionId)
{
leaf = new BTreeLeafComp(ctx.TransactionId, _keyvalues.Length);
Array.Copy(_keyvalues, leaf._keyvalues, _keyvalues.Length);
leaf._keyBytes = _keyBytes;
ctx.Node1 = leaf;
ctx.Update = true;
}
leaf._keyvalues[index] = m;
ctx.Stack.Add(new NodeIdxPair { Node = leaf, Idx = index });
return;
}
if ((long)_keyBytes.Length + ctx.WholeKeyLen > MaxTotalLen)
{
var currentKeyValues = new BTreeLeafMember[_keyvalues.Length];
for (int i = 0; i < currentKeyValues.Length; i++)
{
var member = _keyvalues[i];
currentKeyValues[i] = new BTreeLeafMember
{
Key = ByteBuffer.NewAsync(_keyBytes, member.KeyOffset, member.KeyLength).ToByteArray(),
Value = member.Value
};
}
new BTreeLeaf(ctx.TransactionId - 1, currentKeyValues).CreateOrUpdate(ctx);
return;
}
index = index / 2;
ctx.Created = true;
ctx.KeyIndex = index;
var newKey = ctx.WholeKey();
if (_keyvalues.Length < MaxMembers)
{
var newKeyValues = new Member[_keyvalues.Length + 1];
var newKeyBytes = new byte[_keyBytes.Length + newKey.Length];
Array.Copy(_keyvalues, 0, newKeyValues, 0, index);
var ofs = (ushort)(index == 0 ? 0 : newKeyValues[index - 1].KeyOffset + newKeyValues[index - 1].KeyLength);
newKeyValues[index] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort)newKey.Length,
Value = ctx.Value.ToByteArray()
};
Array.Copy(_keyBytes, 0, newKeyBytes, 0, ofs);
Array.Copy(newKey, 0, newKeyBytes, ofs, newKey.Length);
Array.Copy(_keyBytes, ofs, newKeyBytes, ofs + newKey.Length, _keyBytes.Length - ofs);
Array.Copy(_keyvalues, index, newKeyValues, index + 1, _keyvalues.Length - index);
RecalculateOffsets(newKeyValues);
var leaf = this;
if (ctx.TransactionId != TransactionId)
{
leaf = new BTreeLeafComp(ctx.TransactionId, newKeyBytes, newKeyValues);
ctx.Node1 = leaf;
ctx.Update = true;
}
else
{
_keyvalues = newKeyValues;
_keyBytes = newKeyBytes;
}
ctx.Stack.Add(new NodeIdxPair { Node = leaf, Idx = index });
return;
}
ctx.Split = true;
var keyCountLeft = (_keyvalues.Length + 1) / 2;
var keyCountRight = _keyvalues.Length + 1 - keyCountLeft;
var leftNode = new BTreeLeafComp(ctx.TransactionId, keyCountLeft);
var rightNode = new BTreeLeafComp(ctx.TransactionId, keyCountRight);
ctx.Node1 = leftNode;
ctx.Node2 = rightNode;
if (index < keyCountLeft)
{
Array.Copy(_keyvalues, 0, leftNode._keyvalues, 0, index);
var ofs = (ushort)(index == 0 ? 0 : _keyvalues[index - 1].KeyOffset + _keyvalues[index - 1].KeyLength);
leftNode._keyvalues[index] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort)newKey.Length,
Value = ctx.Value.ToByteArray()
};
Array.Copy(_keyvalues, index, leftNode._keyvalues, index + 1, keyCountLeft - index - 1);
Array.Copy(_keyvalues, keyCountLeft - 1, rightNode._keyvalues, 0, keyCountRight);
var leftKeyBytesLen = _keyvalues[keyCountLeft - 1].KeyOffset + newKey.Length;
var newKeyBytes = new byte[leftKeyBytesLen];
Array.Copy(_keyBytes, 0, newKeyBytes, 0, ofs);
Array.Copy(newKey, 0, newKeyBytes, ofs, newKey.Length);
Array.Copy(_keyBytes, ofs, newKeyBytes, ofs + newKey.Length, leftKeyBytesLen - (ofs + newKey.Length));
leftNode._keyBytes = newKeyBytes;
newKeyBytes = new byte[_keyBytes.Length + newKey.Length - leftKeyBytesLen];
Array.Copy(_keyBytes, leftKeyBytesLen - newKey.Length, newKeyBytes, 0, newKeyBytes.Length);
rightNode._keyBytes = newKeyBytes;
ctx.Stack.Add(new NodeIdxPair { Node = leftNode, Idx = index });
ctx.SplitInRight = false;
RecalculateOffsets(leftNode._keyvalues);
}
else
{
Array.Copy(_keyvalues, 0, leftNode._keyvalues, 0, keyCountLeft);
var leftKeyBytesLen = _keyvalues[keyCountLeft].KeyOffset;
var newKeyBytes = new byte[leftKeyBytesLen];
Array.Copy(_keyBytes, 0, newKeyBytes, 0, leftKeyBytesLen);
leftNode._keyBytes = newKeyBytes;
newKeyBytes = new byte[_keyBytes.Length + newKey.Length - leftKeyBytesLen];
var ofs = (index == _keyvalues.Length ? _keyBytes.Length : _keyvalues[index].KeyOffset) - leftKeyBytesLen;
Array.Copy(_keyBytes, leftKeyBytesLen, newKeyBytes, 0, ofs);
Array.Copy(newKey, 0, newKeyBytes, ofs, newKey.Length);
Array.Copy(_keyBytes, ofs + leftKeyBytesLen, newKeyBytes, ofs + newKey.Length, _keyBytes.Length - ofs - leftKeyBytesLen);
rightNode._keyBytes = newKeyBytes;
Array.Copy(_keyvalues, keyCountLeft, rightNode._keyvalues, 0, index - keyCountLeft);
rightNode._keyvalues[index - keyCountLeft] = new Member
{
KeyOffset = 0,
KeyLength = (ushort)newKey.Length,
Value = ctx.Value.ToByteArray(),
};
Array.Copy(_keyvalues, index, rightNode._keyvalues, index - keyCountLeft + 1, keyCountLeft + keyCountRight - 1 - index);
ctx.Stack.Add(new NodeIdxPair { Node = rightNode, Idx = index - keyCountLeft });
ctx.SplitInRight = true;
}
RecalculateOffsets(rightNode._keyvalues);
}
public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, byte[] prefix, ByteBuffer key)
{
var idx = Find(prefix, key);
FindResult result;
if ((idx & 1) == 1)
{
result = FindResult.Exact;
idx = idx / 2;
}
else
{
result = FindResult.Previous;
idx = idx / 2 - 1;
}
stack.Add(new NodeIdxPair { Node = this, Idx = idx });
keyIndex = idx;
return result;
}
static BTreeLeafMember NewMemberFromCtx(CreateOrUpdateCtx ctx)
{
return new BTreeLeafMember
{
Key = ctx.WholeKey(),
Value = ctx.Value.ToByteArray()
};
}
public long CalcKeyCount()
{
return _keyvalues.Length;
}
public byte[] GetLeftMostKey()
{
return ByteBuffer.NewAsync(_keyBytes, _keyvalues[0].KeyOffset, _keyvalues[0].KeyLength).ToByteArray();
}
public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex)
{
stack.Add(new NodeIdxPair { Node = this, Idx = (int)keyIndex });
}
public long FindLastWithPrefix(byte[] prefix)
{
var left = 0;
var right = _keyvalues.Length - 1;
var keyBytes = _keyBytes;
int result;
int currentKeyOfs;
int currentKeyLen;
while (left < right)
{
var middle = (left + right) / 2;
currentKeyOfs = _keyvalues[middle].KeyOffset;
currentKeyLen = _keyvalues[middle].KeyLength;
result = BitArrayManipulation.CompareByteArray(prefix, 0, prefix.Length,
keyBytes, currentKeyOfs, Math.Min(currentKeyLen, prefix.Length));
if (result < 0)
{
right = middle;
}
else
{
left = middle + 1;
}
}
currentKeyOfs = _keyvalues[left].KeyOffset;
currentKeyLen = _keyvalues[left].KeyLength;
result = BitArrayManipulation.CompareByteArray(prefix, 0, prefix.Length,
keyBytes, currentKeyOfs, Math.Min(currentKeyLen, prefix.Length));
if (result < 0) left--;
return left;
}
public bool NextIdxValid(int idx)
{
return idx + 1 < _keyvalues.Length;
}
public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx)
{
// Nothing to do
}
public void FillStackByRightMost(List<NodeIdxPair> stack, int i)
{
// Nothing to do
}
public int GetLastChildrenIdx()
{
return _keyvalues.Length - 1;
}
public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex)
{
var newKeyValues = new Member[_keyvalues.Length + firstKeyIndex - lastKeyIndex - 1];
var newKeyBytes = new byte[_keyBytes.Length + _keyvalues[firstKeyIndex].KeyOffset - _keyvalues[lastKeyIndex].KeyOffset - _keyvalues[lastKeyIndex].KeyLength];
Array.Copy(_keyvalues, 0, newKeyValues, 0, (int)firstKeyIndex);
Array.Copy(_keyvalues, (int)lastKeyIndex + 1, newKeyValues, (int)firstKeyIndex, newKeyValues.Length - (int)firstKeyIndex);
Array.Copy(_keyBytes, 0, newKeyBytes, 0, _keyvalues[firstKeyIndex].KeyOffset);
Array.Copy(_keyBytes, _keyvalues[lastKeyIndex].KeyOffset + _keyvalues[lastKeyIndex].KeyLength, newKeyBytes, _keyvalues[firstKeyIndex].KeyOffset, newKeyBytes.Length - _keyvalues[firstKeyIndex].KeyOffset);
RecalculateOffsets(newKeyValues);
if (TransactionId == transactionId)
{
_keyvalues = newKeyValues;
_keyBytes = newKeyBytes;
return this;
}
return new BTreeLeafComp(transactionId, newKeyBytes, newKeyValues);
}
static void RecalculateOffsets(Member[] keyvalues)
{
ushort ofs = 0;
for (var i = 0; i < keyvalues.Length; i++)
{
keyvalues[i].KeyOffset = ofs;
ofs += keyvalues[i].KeyLength;
}
}
public ByteBuffer GetKey(int idx)
{
return ByteBuffer.NewAsync(_keyBytes, _keyvalues[idx].KeyOffset, _keyvalues[idx].KeyLength);
}
public ByteBuffer GetMemberValue(int idx)
{
var kv = _keyvalues[idx];
return ByteBuffer.NewAsync(kv.Value);
}
public void SetMemberValue(int idx, ByteBuffer value)
{
var kv = _keyvalues[idx];
kv.Value = value.ToByteArray();
_keyvalues[idx] = kv;
}
}
}
| |
namespace System.Workflow.ComponentModel
{
#region Imports
using System;
using System.Diagnostics;
using System.Reflection;
using System.Drawing;
using System.Collections;
using System.CodeDom;
using System.Globalization;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Collections.Generic;
#endregion
[ToolboxItem(false)]
[Designer(typeof(FaultHandlersActivityDesigner), typeof(IDesigner))]
[ToolboxBitmap(typeof(FaultHandlersActivity), "Resources.Exceptions.png")]
[ActivityValidator(typeof(FaultHandlersActivityValidator))]
[AlternateFlowActivity]
[SRCategory(SR.Standard)]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class FaultHandlersActivity : CompositeActivity, IActivityEventListener<ActivityExecutionStatusChangedEventArgs>
{
public FaultHandlersActivity()
{
}
public FaultHandlersActivity(string name)
: base(name)
{
}
protected internal override void Initialize(IServiceProvider provider)
{
if (this.Parent == null)
throw new InvalidOperationException(SR.GetString(SR.Error_MustHaveParent));
base.Initialize(provider);
}
protected internal override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
Debug.Assert(this.Parent.GetValue(ActivityExecutionContext.CurrentExceptionProperty) != null, "No Exception contained by parent");
Exception excep = this.Parent.GetValue(ActivityExecutionContext.CurrentExceptionProperty) as Exception;
if (excep != null)
{
Type exceptionType = excep.GetType();
foreach (FaultHandlerActivity exceptionHandler in this.EnabledActivities)
{
if (CanHandleException(exceptionHandler, exceptionType))
{
// remove exception from here, I ate it
this.Parent.RemoveProperty(ActivityExecutionContext.CurrentExceptionProperty);
exceptionHandler.SetException(excep);
exceptionHandler.RegisterForStatusChange(Activity.ClosedEvent, this);
executionContext.ExecuteActivity(exceptionHandler);
return ActivityExecutionStatus.Executing;
}
}
}
return ActivityExecutionStatus.Closed;
}
protected internal override ActivityExecutionStatus Cancel(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
Activity childActivity = this.EnabledActivities[i];
if (childActivity.ExecutionStatus == ActivityExecutionStatus.Executing)
executionContext.CancelActivity(childActivity);
if (childActivity.ExecutionStatus == ActivityExecutionStatus.Canceling ||
childActivity.ExecutionStatus == ActivityExecutionStatus.Faulting)
return this.ExecutionStatus;
}
return ActivityExecutionStatus.Closed;
}
#region IActivityEventListener<ActivityExecutionStatusChangedEventArgs> Members
void IActivityEventListener<ActivityExecutionStatusChangedEventArgs>.OnEvent(object sender, ActivityExecutionStatusChangedEventArgs e)
{
if (sender == null)
throw new ArgumentNullException("sender");
if (e == null)
throw new ArgumentNullException("e");
ActivityExecutionContext context = sender as ActivityExecutionContext;
if (context == null)
throw new ArgumentException(SR.Error_SenderMustBeActivityExecutionContext, "sender");
e.Activity.UnregisterForStatusChange(Activity.ClosedEvent, this);
context.CloseActivity();
}
[NonSerialized]
bool activeChildRemoved = false;
protected internal override void OnActivityChangeRemove(ActivityExecutionContext executionContext, Activity removedActivity)
{
if (removedActivity == null)
throw new ArgumentNullException("removedActivity");
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (removedActivity.ExecutionStatus == ActivityExecutionStatus.Closed && this.ExecutionStatus != ActivityExecutionStatus.Closed)
activeChildRemoved = true;
base.OnActivityChangeRemove(executionContext, removedActivity);
}
protected internal override void OnWorkflowChangesCompleted(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (activeChildRemoved)
{
executionContext.CloseActivity();
activeChildRemoved = false;
}
base.OnWorkflowChangesCompleted(executionContext);
}
protected override void OnClosed(IServiceProvider provider)
{
}
#endregion
private bool CanHandleException(FaultHandlerActivity exceptionHandler, Type et)
{
Type canHandleType = exceptionHandler.FaultType;
return (et == canHandleType || et.IsSubclassOf(canHandleType));
}
}
internal sealed class FaultHandlersActivityValidator : CompositeActivityValidator
{
public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
{
ValidationErrorCollection validationErrors = base.Validate(manager, obj);
FaultHandlersActivity exceptionHandlers = obj as FaultHandlersActivity;
if (exceptionHandlers == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(FaultHandlersActivity).FullName), "obj");
Hashtable exceptionTypes = new Hashtable();
ArrayList previousExceptionTypes = new ArrayList();
bool bFoundNotFaultHandlerActivity = false;
foreach (Activity activity in exceptionHandlers.EnabledActivities)
{
// All child activities must be FaultHandlerActivity
if (!(activity is FaultHandlerActivity))
{
if (!bFoundNotFaultHandlerActivity)
{
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_FaultHandlersActivityDeclNotAllFaultHandlerActivityDecl), ErrorNumbers.Error_FaultHandlersActivityDeclNotAllFaultHandlerActivityDecl));
bFoundNotFaultHandlerActivity = true;
}
}
else
{
FaultHandlerActivity exceptionHandler = (FaultHandlerActivity)activity;
Type catchType = exceptionHandler.FaultType;
if (catchType != null)
{
if (exceptionTypes[catchType] == null)
{
exceptionTypes[catchType] = 1;
previousExceptionTypes.Add(catchType);
}
else if ((int)exceptionTypes[catchType] == 1)
{
/*if (catchType == typeof(System.Exception))
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ScopeDuplicateFaultHandlerActivityForAll, exceptionHandlers.EnclosingDataContextActivity.GetType().Name), ErrorNumbers.Error_ScopeDuplicateFaultHandlerActivityForAll));
else*/
validationErrors.Add(new ValidationError(string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.Error_ScopeDuplicateFaultHandlerActivityFor), new object[] { Helpers.GetEnclosingActivity(exceptionHandlers).GetType().Name, catchType.FullName }), ErrorNumbers.Error_ScopeDuplicateFaultHandlerActivityFor));
exceptionTypes[catchType] = 2;
}
foreach (Type previousType in previousExceptionTypes)
{
if (previousType != catchType && previousType.IsAssignableFrom(catchType))
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_FaultHandlerActivityWrongOrder, catchType.Name, previousType.Name), ErrorNumbers.Error_FaultHandlerActivityWrongOrder));
}
}
}
}
// fault handlers can not contain fault handlers, compensation handler and cancellation handler
if (((ISupportAlternateFlow)exceptionHandlers).AlternateFlowActivities.Count > 0)
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ModelingConstructsCanNotContainModelingConstructs), ErrorNumbers.Error_ModelingConstructsCanNotContainModelingConstructs));
return validationErrors;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.Regions;
using Prism.Wpf.Tests.Mocks;
namespace Prism.Wpf.Tests.Regions
{
[TestClass]
public class RegionManagerFixture
{
[TestMethod]
public void CanAddRegion()
{
IRegion region1 = new MockPresentationRegion();
region1.Name = "MainRegion";
RegionManager regionManager = new RegionManager();
regionManager.Regions.Add(region1);
IRegion region2 = regionManager.Regions["MainRegion"];
Assert.AreSame(region1, region2);
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException))]
public void ShouldFailIfRegionDoesntExists()
{
RegionManager regionManager = new RegionManager();
IRegion region = regionManager.Regions["nonExistentRegion"];
}
[TestMethod]
public void CanCheckTheExistenceOfARegion()
{
RegionManager regionManager = new RegionManager();
bool result = regionManager.Regions.ContainsRegionWithName("noRegion");
Assert.IsFalse(result);
IRegion region = new MockPresentationRegion();
region.Name = "noRegion";
regionManager.Regions.Add(region);
result = regionManager.Regions.ContainsRegionWithName("noRegion");
Assert.IsTrue(result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AddingMultipleRegionsWithSameNameThrowsArgumentException()
{
var regionManager = new RegionManager();
regionManager.Regions.Add(new MockPresentationRegion { Name = "region name" });
regionManager.Regions.Add(new MockPresentationRegion { Name = "region name" });
}
[TestMethod]
public void AddPassesItselfAsTheRegionManagerOfTheRegion()
{
var regionManager = new RegionManager();
var region = new MockPresentationRegion();
region.Name = "region";
regionManager.Regions.Add(region);
Assert.AreSame(regionManager, region.RegionManager);
}
[TestMethod]
public void CreateRegionManagerCreatesANewInstance()
{
var regionManager = new RegionManager();
var createdRegionManager = regionManager.CreateRegionManager();
Assert.IsNotNull(createdRegionManager);
Assert.IsInstanceOfType(createdRegionManager, typeof(RegionManager));
Assert.AreNotSame(regionManager, createdRegionManager);
}
[TestMethod]
public void CanRemoveRegion()
{
var regionManager = new RegionManager();
IRegion region = new MockPresentationRegion();
region.Name = "TestRegion";
regionManager.Regions.Add(region);
regionManager.Regions.Remove("TestRegion");
Assert.IsFalse(regionManager.Regions.ContainsRegionWithName("TestRegion"));
}
[TestMethod]
public void ShouldRemoveRegionManagerWhenRemoving()
{
var regionManager = new RegionManager();
var region = new MockPresentationRegion();
region.Name = "TestRegion";
regionManager.Regions.Add(region);
regionManager.Regions.Remove("TestRegion");
Assert.IsNull(region.RegionManager);
}
[TestMethod]
public void UpdatingRegionsGetsCalledWhenAccessingRegionMembers()
{
var listener = new MySubscriberClass();
try
{
RegionManager.UpdatingRegions += listener.OnUpdatingRegions;
RegionManager regionManager = new RegionManager();
regionManager.Regions.ContainsRegionWithName("TestRegion");
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
listener.OnUpdatingRegionsCalled = false;
regionManager.Regions.Add(new MockPresentationRegion() { Name = "TestRegion" });
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
listener.OnUpdatingRegionsCalled = false;
var region = regionManager.Regions["TestRegion"];
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
listener.OnUpdatingRegionsCalled = false;
regionManager.Regions.Remove("TestRegion");
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
listener.OnUpdatingRegionsCalled = false;
regionManager.Regions.GetEnumerator();
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
}
finally
{
RegionManager.UpdatingRegions -= listener.OnUpdatingRegions;
}
}
[TestMethod]
public void ShouldSetObservableRegionContextWhenRegionContextChanges()
{
var region = new MockPresentationRegion();
var view = new MockDependencyObject();
var observableObject = RegionContext.GetObservableContext(view);
bool propertyChangedCalled = false;
observableObject.PropertyChanged += (sender, args) => propertyChangedCalled = true;
Assert.IsNull(observableObject.Value);
RegionManager.SetRegionContext(view, "MyContext");
Assert.IsTrue(propertyChangedCalled);
Assert.AreEqual("MyContext", observableObject.Value);
}
[TestMethod]
public void ShouldNotPreventSubscribersToStaticEventFromBeingGarbageCollected()
{
var subscriber = new MySubscriberClass();
RegionManager.UpdatingRegions += subscriber.OnUpdatingRegions;
RegionManager.UpdateRegions();
Assert.IsTrue(subscriber.OnUpdatingRegionsCalled);
WeakReference subscriberWeakReference = new WeakReference(subscriber);
subscriber = null;
GC.Collect();
Assert.IsFalse(subscriberWeakReference.IsAlive);
}
[TestMethod]
public void ExceptionMessageWhenCallingUpdateRegionsShouldBeClear()
{
try
{
ExceptionExtensions.RegisterFrameworkExceptionType(typeof(FrameworkException));
RegionManager.UpdatingRegions += new EventHandler(RegionManager_UpdatingRegions);
try
{
RegionManager.UpdateRegions();
Assert.Fail();
}
catch (Exception ex)
{
Assert.IsTrue(ex.Message.Contains("Abcde"));
}
}
finally
{
RegionManager.UpdatingRegions -= new EventHandler(RegionManager_UpdatingRegions);
}
}
public void RegionManager_UpdatingRegions(object sender, EventArgs e)
{
try
{
throw new Exception("Abcde");
}
catch (Exception ex)
{
throw new FrameworkException(ex);
}
}
public class MySubscriberClass
{
public bool OnUpdatingRegionsCalled;
public void OnUpdatingRegions(object sender, EventArgs e)
{
OnUpdatingRegionsCalled = true;
}
}
[TestMethod]
public void WhenAddingRegions_ThenRegionsCollectionNotifiesUpdate()
{
var regionManager = new RegionManager();
var region1 = new Region { Name = "region1" };
var region2 = new Region { Name = "region2" };
NotifyCollectionChangedEventArgs args = null;
regionManager.Regions.CollectionChanged += (s, e) => args = e;
regionManager.Regions.Add(region1);
Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action);
CollectionAssert.AreEqual(new object[] { region1 }, args.NewItems);
Assert.AreEqual(0, args.NewStartingIndex);
Assert.IsNull(args.OldItems);
Assert.AreEqual(-1, args.OldStartingIndex);
regionManager.Regions.Add(region2);
Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action);
CollectionAssert.AreEqual(new object[] { region2 }, args.NewItems);
Assert.AreEqual(0, args.NewStartingIndex);
Assert.IsNull(args.OldItems);
Assert.AreEqual(-1, args.OldStartingIndex);
}
[TestMethod]
public void WhenRemovingRegions_ThenRegionsCollectionNotifiesUpdate()
{
var regionManager = new RegionManager();
var region1 = new Region { Name = "region1" };
var region2 = new Region { Name = "region2" };
regionManager.Regions.Add(region1);
regionManager.Regions.Add(region2);
NotifyCollectionChangedEventArgs args = null;
regionManager.Regions.CollectionChanged += (s, e) => args = e;
regionManager.Regions.Remove("region2");
Assert.AreEqual(NotifyCollectionChangedAction.Remove, args.Action);
CollectionAssert.AreEqual(new object[] { region2 }, args.OldItems);
Assert.AreEqual(0, args.OldStartingIndex);
Assert.IsNull(args.NewItems);
Assert.AreEqual(-1, args.NewStartingIndex);
regionManager.Regions.Remove("region1");
Assert.AreEqual(NotifyCollectionChangedAction.Remove, args.Action);
CollectionAssert.AreEqual(new object[] { region1 }, args.OldItems);
Assert.AreEqual(0, args.OldStartingIndex);
Assert.IsNull(args.NewItems);
Assert.AreEqual(-1, args.NewStartingIndex);
}
[TestMethod]
public void WhenRemovingNonExistingRegion_ThenRegionsCollectionDoesNotNotifyUpdate()
{
var regionManager = new RegionManager();
var region1 = new Region { Name = "region1" };
regionManager.Regions.Add(region1);
NotifyCollectionChangedEventArgs args = null;
regionManager.Regions.CollectionChanged += (s, e) => args = e;
regionManager.Regions.Remove("region2");
Assert.IsNull(args);
}
}
internal class FrameworkException : Exception
{
public FrameworkException(Exception inner)
: base(string.Empty, inner)
{
}
}
}
| |
using Xunit;
using Xunit.Extensions;
namespace Bugsnag.Test
{
public class ConfigurationTests
{
[Theory]
[InlineData("Random API Key")]
[InlineData(null)]
[InlineData("")]
[InlineData("1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ")]
public void Constructor_CheckApiKeyIsRecordedCorrectly(string apiKey)
{
// Arrange + Act
var testConfig = new Configuration(apiKey);
// Assert
Assert.Equal(apiKey, testConfig.ApiKey);
}
[Theory]
[InlineData("https://another.point.com/")]
[InlineData("https://end.random.com/")]
public void EndpointUrl_UrlIsCreatedCorrectly(string url)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
testConfig.Endpoint = url;
// Assert
Assert.Equal(url, testConfig.EndpointUrl.AbsoluteUri);
}
[Theory]
[InlineData("stage 1")]
[InlineData("stage 2")]
[InlineData("stage 4")]
[InlineData("stage 7")]
[InlineData(null)]
public void ReleaseStage_IdentifiesReleaseStagesToNotifyOn(string stage)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
testConfig.NotifyReleaseStages = new[] { "stage 1", "stage 2", "stage 4", "stage 7" };
testConfig.ReleaseStage = stage;
// Assert
Assert.True(testConfig.IsNotifyReleaseStage());
}
[Theory]
[InlineData("stage 3")]
[InlineData("stage 5")]
[InlineData("stage 6")]
[InlineData("stage 8")]
[InlineData("")]
public void ReleaseStage_IdentifiesReleaseStagesToNotNotifyOn(string stage)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
testConfig.NotifyReleaseStages = new[] { "stage 1", "stage 2", "stage 4", "stage 7" };
testConfig.ReleaseStage = stage;
// Assert
Assert.False(testConfig.IsNotifyReleaseStage());
}
[Theory]
[InlineData("stage 1")]
[InlineData("stage 2")]
[InlineData("stage 3")]
[InlineData("")]
public void ReleaseStage_AllReleaseStageNotifyByDefault(string stage)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
testConfig.ReleaseStage = stage;
// Assert
Assert.True(testConfig.IsNotifyReleaseStage());
}
[Theory]
[InlineData(@"C:\MyProj\file1.cs")]
[InlineData(@"H:\Path\To\file2.cs")]
[InlineData(@"E:\file3.cs")]
[InlineData(null)]
[InlineData("")]
public void FilePrefixes_LeaveFilenamesUntouchedIfNotSet(string fileName)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
var actFileName = testConfig.RemoveFileNamePrefix(fileName);
// Assert
Assert.Equal(fileName, actFileName);
}
[Theory]
[InlineData(@"C:\MyProj\file1.cs", @"file1.cs")]
[InlineData(@"H:\Path\To\file2.cs", @"Path\To\file2.cs")]
[InlineData(@"E:\file3.cs", @"E:\file3.cs")]
[InlineData(null, null)]
[InlineData("", "")]
public void FilePrefixes_RemovePrefixesSuccessfully(string fileName, string expFileName)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
testConfig.FilePrefixes = new[] { @"C:\MyProj\", @"H:\", @"C:\MyOtherProj\Data" };
var actFileName = testConfig.RemoveFileNamePrefix(fileName);
// Assert
Assert.Equal(expFileName, actFileName);
}
[Theory]
[InlineData("ComA.ComB.Call()")]
[InlineData("ComC.MyCall()")]
[InlineData("ComD.ComA.ComB.Call()")]
[InlineData(null)]
[InlineData("")]
public void ProjectNamespaces_AllMethodsAreNotInNamespaceIfNotBeenSet(string methodName)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
var actInProject = testConfig.IsInProjectNamespace(methodName);
// Assert
Assert.False(actInProject);
}
[Theory]
[InlineData("ComA.ComB.Call()", true)]
[InlineData("ComC.MyCall()", true)]
[InlineData("ComD.ComA.ComB.Call()", false)]
[InlineData(null, false)]
[InlineData("", false)]
public void ProjectNamespaces_ProjectMethodCallsAreIdentifiedCorrectly(string methodName, bool expInProject)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
testConfig.ProjectNamespaces = new[] { "ComA", "ComC" };
var actInProject = testConfig.IsInProjectNamespace(methodName);
// Assert
Assert.Equal(expInProject, actInProject);
}
[Theory]
[InlineData("Class1")]
[InlineData("Class2")]
[InlineData("Class3")]
[InlineData("Class4")]
[InlineData("Class5")]
[InlineData(null)]
[InlineData("")]
public void IgnoreClasses_AllClassesAreNotIgnoredIfNotBeenSet(string className)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
var actIgnoreClass = testConfig.IsClassToIgnore(className);
// Assert
Assert.False(actIgnoreClass);
}
[Theory]
[InlineData("Class1", false)]
[InlineData("Class2", true)]
[InlineData("Class3", false)]
[InlineData("Class4", false)]
[InlineData("Class5", true)]
[InlineData(null, false)]
[InlineData("", false)]
public void IgnoreClasses_ClassesToIgnoreAreIdentifiedCorrectly(string className, bool expIgnoreClass)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
testConfig.IgnoreClasses = new[] { "Class2", "Class5" };
var actIgnoreClass = testConfig.IsClassToIgnore(className);
// Assert
Assert.Equal(expIgnoreClass, actIgnoreClass);
}
[Theory]
[InlineData("Entry1")]
[InlineData("Entry2")]
[InlineData("Entry3")]
[InlineData("Entry4")]
[InlineData("Entry5")]
[InlineData(null)]
[InlineData("")]
public void Filters_AllEntriesAreNotFilteredIfNotBeenSet(string entryKey)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
var actFilterEntry = testConfig.IsEntryFiltered(entryKey);
// Assert
Assert.False(actFilterEntry);
}
[Theory]
[InlineData("Entry1", true)]
[InlineData("Entry2", false)]
[InlineData("Entry3", true)]
[InlineData("Entry4", false)]
[InlineData("Entry5", true)]
[InlineData(null, false)]
[InlineData("", false)]
public void Filters_EntriesToFilterAreIdentifiedCorrectly(string entryKey, bool expFilterEntry)
{
// Arrange
var testConfig = new Configuration("123456");
// Act
testConfig.MetadataFilters = new[] { "Entry1", "Entry3", "Entry5" };
var actFilterEntry = testConfig.IsEntryFiltered(entryKey);
// Assert
Assert.Equal(expFilterEntry, actFilterEntry);
}
[Fact]
public void RunBeforeNotifyCallbacks_WillReturnIfCallbackExceptions()
{
// Arrange
var testConfig = new Configuration("123456");
var testExp = new System.Exception("Test Stack Overflow");
var testEvent = new Event(testExp);
bool callbackHasRun = false;
testConfig.BeforeNotify(err =>
{
callbackHasRun = true;
Assert.Equal(testEvent, err);
throw new System.AccessViolationException("Invalid Access");
});
// Act
bool returnValue = testConfig.RunBeforeNotifyCallbacks(testEvent);
// Assert
Assert.True(returnValue);
Assert.True(callbackHasRun);
}
[Fact]
public void RunBeforeNotifyCallbacks_WillRunMultipleCallbacks()
{
// Arrange
var testConfig = new Configuration("123456");
var testExp = new System.Exception("Test Stack Overflow");
var testEvent = new Event(testExp);
bool firstCallbackHasRun = false;
bool secondCallbackHasRun = false;
testConfig.BeforeNotify(err =>
{
firstCallbackHasRun = true;
Assert.Equal(testEvent, err);
return true;
});
testConfig.BeforeNotify(err =>
{
secondCallbackHasRun = true;
Assert.Equal(testEvent, err);
return true;
});
// Act
bool returnValue = testConfig.RunBeforeNotifyCallbacks(testEvent);
// Assert
Assert.True(returnValue);
Assert.True(firstCallbackHasRun);
Assert.True(secondCallbackHasRun);
}
[Fact]
public void RunBeforeNotifyCallbacks_WillStopRunning()
{
// Arrange
var testConfig = new Configuration("123456");
var testExp = new System.Exception("Test Stack Overflow");
var testEvent = new Event(testExp);
bool firstCallbackHasRun = false;
bool secondCallbackHasRun = false;
testConfig.BeforeNotify(err =>
{
firstCallbackHasRun = true;
Assert.Equal(testEvent, err);
return false;
});
testConfig.BeforeNotify(err =>
{
secondCallbackHasRun = true;
Assert.Equal(testEvent, err);
return true;
});
// Act
bool returnValue = testConfig.RunBeforeNotifyCallbacks(testEvent);
// Assert
Assert.False(returnValue);
Assert.True(firstCallbackHasRun);
Assert.False(secondCallbackHasRun);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Globalization;
#if(UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE)
using Newtonsoft.Json.Aot;
#endif
namespace Newtonsoft.Json.Utilities
{
internal static class StringUtils
{
public const string CarriageReturnLineFeed = "\r\n";
public const string Empty = "";
public const char CarriageReturn = '\r';
public const char LineFeed = '\n';
public const char Tab = '\t';
public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
ValidationUtils.ArgumentNotNull(format, "format");
return string.Format(provider, format, args);
}
/// <summary>
/// Determines whether the string contains white space.
/// </summary>
/// <param name="s">The string to test for white space.</param>
/// <returns>
/// <c>true</c> if the string contains white space; otherwise, <c>false</c>.
/// </returns>
public static bool ContainsWhiteSpace(string s)
{
if (s == null)
throw new ArgumentNullException("s");
for (int i = 0; i < s.Length; i++)
{
if (char.IsWhiteSpace(s[i]))
return true;
}
return false;
}
/// <summary>
/// Determines whether the string is all white space. Empty string will return false.
/// </summary>
/// <param name="s">The string to test whether it is all white space.</param>
/// <returns>
/// <c>true</c> if the string is all white space; otherwise, <c>false</c>.
/// </returns>
public static bool IsWhiteSpace(string s)
{
if (s == null)
throw new ArgumentNullException("s");
if (s.Length == 0)
return false;
for (int i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s[i]))
return false;
}
return true;
}
/// <summary>
/// Ensures the target string ends with the specified string.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
/// <returns>The target string with the value string at the end.</returns>
public static string EnsureEndsWith(string target, string value)
{
if (target == null)
throw new ArgumentNullException("target");
if (value == null)
throw new ArgumentNullException("value");
if (target.Length >= value.Length)
{
if (string.Compare(target, target.Length - value.Length, value, 0, value.Length, StringComparison.OrdinalIgnoreCase) ==
0)
return target;
string trimmedString = target.TrimEnd(null);
if (string.Compare(trimmedString, trimmedString.Length - value.Length, value, 0, value.Length,
StringComparison.OrdinalIgnoreCase) == 0)
return target;
}
return target + value;
}
public static bool IsNullOrEmptyOrWhiteSpace(string s)
{
if (string.IsNullOrEmpty(s))
return true;
else if (IsWhiteSpace(s))
return true;
else
return false;
}
/// <summary>
/// Perform an action if the string is not null or empty.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="action">The action to perform.</param>
public static void IfNotNullOrEmpty(string value, Action<string> action)
{
IfNotNullOrEmpty(value, action, null);
}
private static void IfNotNullOrEmpty(string value, Action<string> trueAction, Action<string> falseAction)
{
if (!string.IsNullOrEmpty(value))
{
if (trueAction != null)
trueAction(value);
}
else
{
if (falseAction != null)
falseAction(value);
}
}
/// <summary>
/// Indents the specified string.
/// </summary>
/// <param name="s">The string to indent.</param>
/// <param name="indentation">The number of characters to indent by.</param>
/// <returns></returns>
public static string Indent(string s, int indentation)
{
return Indent(s, indentation, ' ');
}
/// <summary>
/// Indents the specified string.
/// </summary>
/// <param name="s">The string to indent.</param>
/// <param name="indentation">The number of characters to indent by.</param>
/// <param name="indentChar">The indent character.</param>
/// <returns></returns>
public static string Indent(string s, int indentation, char indentChar)
{
if (s == null)
throw new ArgumentNullException("s");
if (indentation <= 0)
throw new ArgumentException("Must be greater than zero.", "indentation");
StringReader sr = new StringReader(s);
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line)
{
tw.Write(new string(indentChar, indentation));
tw.Write(line);
});
return sw.ToString();
}
private delegate void ActionLine(TextWriter textWriter, string line);
private static void ActionTextReaderLine(TextReader textReader, TextWriter textWriter, ActionLine lineAction)
{
string line;
bool firstLine = true;
while ((line = textReader.ReadLine()) != null)
{
if (!firstLine)
textWriter.WriteLine();
else
firstLine = false;
lineAction(textWriter, line);
}
}
/// <summary>
/// Numbers the lines.
/// </summary>
/// <param name="s">The string to number.</param>
/// <returns></returns>
public static string NumberLines(string s)
{
if (s == null)
throw new ArgumentNullException("s");
StringReader sr = new StringReader(s);
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
int lineNumber = 1;
ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line)
{
tw.Write(lineNumber.ToString(CultureInfo.InvariantCulture).PadLeft(4));
tw.Write(". ");
tw.Write(line);
lineNumber++;
});
return sw.ToString();
}
/// <summary>
/// Nulls an empty string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>Null if the string was null, otherwise the string unchanged.</returns>
public static string NullEmptyString(string s)
{
return (string.IsNullOrEmpty(s)) ? null : s;
}
public static string ReplaceNewLines(string s, string replacement)
{
StringReader sr = new StringReader(s);
StringBuilder sb = new StringBuilder();
bool first = true;
string line;
while ((line = sr.ReadLine()) != null)
{
if (first)
first = false;
else
sb.Append(replacement);
sb.Append(line);
}
return sb.ToString();
}
public static string Truncate(string s, int maximumLength)
{
return Truncate(s, maximumLength, "...");
}
public static string Truncate(string s, int maximumLength, string suffix)
{
if (suffix == null)
throw new ArgumentNullException("suffix");
if (maximumLength <= 0)
throw new ArgumentException("Maximum length must be greater than zero.", "maximumLength");
int subStringLength = maximumLength - suffix.Length;
if (subStringLength <= 0)
throw new ArgumentException("Length of suffix string is greater or equal to maximumLength");
if (s != null && s.Length > maximumLength)
{
string truncatedString = s.Substring(0, subStringLength);
// incase the last character is a space
truncatedString = truncatedString.Trim();
truncatedString += suffix;
return truncatedString;
}
else
{
return s;
}
}
public static StringWriter CreateStringWriter(int capacity)
{
StringBuilder sb = new StringBuilder(capacity);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
return sw;
}
public static int GetLength(string value)
{
if (value == null)
return -1;
else
return value.Length;
}
public static string ToCharAsUnicode(char c)
{
char h1 = MathUtils.IntToHex((c >> 12) & '\x000f');
char h2 = MathUtils.IntToHex((c >> 8) & '\x000f');
char h3 = MathUtils.IntToHex((c >> 4) & '\x000f');
char h4 = MathUtils.IntToHex(c & '\x000f');
return new string(new[] { '\\', 'u', h1, h2, h3, h4 });
}
public static void WriteCharAsUnicode(TextWriter writer, char c)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
char h1 = MathUtils.IntToHex((c >> 12) & '\x000f');
char h2 = MathUtils.IntToHex((c >> 8) & '\x000f');
char h3 = MathUtils.IntToHex((c >> 4) & '\x000f');
char h4 = MathUtils.IntToHex(c & '\x000f');
writer.Write('\\');
writer.Write('u');
writer.Write(h1);
writer.Write(h2);
writer.Write(h3);
writer.Write(h4);
}
public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
{
if (source == null)
throw new ArgumentNullException("source");
if (valueSelector == null)
throw new ArgumentNullException("valueSelector");
#if !(UNITY_IPHONE || UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII) || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII && !(UNITY_3_5 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3))
var caseInsensitiveResults = source.Where(s => string.Compare(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase) == 0).ToArray();
var resultCount = caseInsensitiveResults.Length;
#else
var caseInsensitiveResults = new List<TSource>();
source.ForEach(itm =>
{
if (string.Compare(valueSelector(itm), testValue, StringComparison.OrdinalIgnoreCase) == 0)
caseInsensitiveResults.Add(itm);
});
var resultCount = caseInsensitiveResults.Count;
#endif
if (resultCount <= 1)
{
return resultCount == 1 ? caseInsensitiveResults[0] : default(TSource);
}
else
{
//multiple results returned. now filter using case sensitivity
#if !(UNITY_IPHONE || UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII) || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII && !(UNITY_3_5 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3))
var caseSensitiveResults = source.Where(s => string.Compare(valueSelector(s), testValue, StringComparison.Ordinal) == 0);
return caseSensitiveResults.SingleOrDefault();
#else
var caseSensitiveResults = new List<TSource>();
source.ForEach(itm =>
{
if (string.Compare(valueSelector(itm), testValue, StringComparison.Ordinal) == 0)
caseSensitiveResults.Add(itm);
});
return caseSensitiveResults.Count > 0 ? caseSensitiveResults[0] : default(TSource);
#endif
}
}
public static string ToCamelCase(string s)
{
if (string.IsNullOrEmpty(s))
return s;
if (!char.IsUpper(s[0]))
return s;
string camelCase = char.ToLower(s[0], CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
if (s.Length > 1)
camelCase += s.Substring(1);
return camelCase;
}
}
}
#endif
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using KSP.UI.Screens;
//#if DEBUG
//using KramaxReloadExtensions;
//#endif
namespace AutoAsparagus
{
// #if DEBUG
// public class ASPFuelLine: ReloadableMonoBehaviour
// #else
public class ASPFuelLine: MonoBehaviour
// #endif
{
private class FuelSet
{
public Part fromPart { get; set; }
public Part toPart { get; set; }
public CompoundPart fl { get; set; }
}
private static SortedDictionary<int,List<Part>> OnionRings;
private static List<FuelSet> fuelSetsToConnect = new List<FuelSet> ();
private static Boolean isFuelLine (Part p, string partName)
{
if (p.name == partName) {
return true;
}
/*
// is the passed part a fuel line?
if (p is FuelLine) {
return true;
}
if (p is CompoundPart) {
foreach (PartModule pm in p.Modules){
if (pm.moduleName == "CModuleFuelLine") {
return true;
}
}
}*/
return false;
}
public static List<Part> getFuelLineTargets (Part p, string partName)
{
ASPConsoleStuff.printPart ("...searching fuel lines of part", p);
List<Part> targets = new List<Part> ();
foreach (Part child in p.children) {
if (isFuelLine (child, partName)) {
// FuelLine class has a "target" attribute; Part class doesn't, so we have to re-class to access ".target"
Part fuelLineTarget = ((CompoundPart)child).target;
if (fuelLineTarget != null) {
ASPConsoleStuff.printPart ("...found fuel line target", fuelLineTarget);
targets.Add (fuelLineTarget);
}
}
}
return targets;
}
/*private static bool isParent(Part a, Part b){
Part p = a;
while (p.parent != null) {
if (b == p.parent) {
return true;
}
p = p.parent;
}
return false;
}*/
public static Part findRootPart (Part p)
{
Part parent = p;
while (parent.parent != null) {
parent = parent.parent;
}
return parent;
}
private static Vector3 vector3direction (Vector3 from, Vector3 to)
{
// I can never remember which way the math goes
return (to - from).normalized;
}
private static bool fireRayAt (Part p, Vector3 origin, Vector3 dest, out Vector3 collisionpoint)
{
// returns true for obstructed, false for clear
if (p == null) {
ASPConsoleStuff.AAprint ("fireRayAt.p is null!");
collisionpoint = origin; // must be set to something
return true;
}
if (p.collider == null) {
//ASPConsoleStuff.AAprint ("fireRayAt.p.collider is null!");
//ASPConsoleStuff.printPart ("Part has no collider", p);
collisionpoint = origin; // must be set to something
return false;
}
/* Can't be null
if (origin == null) {
ASPConsoleStuff.AAprint ("fireRayAt.origin is null!");
}
if (dest == null) {
ASPConsoleStuff.AAprint ("fireRayAt.dest is null!");
}*/
Ray r = new Ray ();
/* Can't be null
if (r == null) {
ASPConsoleStuff.AAprint ("fireRayAt.r is null!");
}*/
r.origin = origin;
r.direction = vector3direction (origin, dest);
float distance = Vector3.Distance (origin, dest);
RaycastHit hit = new RaycastHit ();
/* Can't be null
if (hit == null) {
ASPConsoleStuff.AAprint ("fireRayAt.hit is null!");
}*/
if (p.collider.Raycast (r, out hit, distance)) {
/* Can't be null
if (hit == null) {
ASPConsoleStuff.AAprint ("fireRayAt.hit is null!");
}
*/
collisionpoint = hit.point;
return true;
} else {
collisionpoint = origin;
//ASPConsoleStuff.printPart ("!! ray failed aiming at", p);
return false;
}
}
private static void getStartDestPositions (Part sourceTank, Part destTank, Vector3 midway, out Vector3 startPosition, out Vector3 destPosition)
{
fireRayAt (sourceTank, midway, sourceTank.transform.position, out startPosition);
fireRayAt (destTank, midway, destTank.transform.position, out destPosition);
}
private static Boolean isFLpathObstructed (Part sourceTank, Part destTank, Vector3 midway)
{
if (sourceTank == null) {
ASPConsoleStuff.AAprint ("isFLpathObstructed.sourceTank is null!");
return true;
}
if (destTank == null) {
ASPConsoleStuff.AAprint ("isFLpathObstructed.destTank is null!");
return true;
}
/* can't be null
if (midway == null) {
ASPConsoleStuff.AAprint ("isFLpathObstructed.midway is null!");
return true;
}*/
Vector3 startPosition = new Vector3 ();
Vector3 destPosition = new Vector3 ();
getStartDestPositions (sourceTank, destTank, midway, out startPosition, out destPosition);
//Vector3 midPosition = Vector3.Lerp (startPosition, destPosition, 0.5f);
EditorLogic editor = EditorLogic.fetch;
ShipConstruct ship = editor.ship;
List<Part> parts = ship.parts;
//ASPConsoleStuff.printVector3 ("testing midway", midway);
Vector3 collisionpoint = new Vector3 ();
foreach (Part p in parts) {
if ((p == destTank) || (p == destTank)) {
continue;
}
if (fireRayAt (p, startPosition, destPosition, out collisionpoint)) {
//ASPConsoleStuff.printPart ("**** fuel line is obstructed at "+collisionpoint.ToString("F2")+" by", p);
if (!AutoAsparagus.blockingTanks.Contains (p)) {
AutoAsparagus.blockingTanks.Add (p);
}
return true;
}
/* Don't check against bounds since they're much more strict than the actual collider.
if (p.collider.bounds.Contains (midPosition)) {
#if DEBUG
ASPConsoleStuff.printPart ("**** fuel line is obstructed (midPosition) at "+collisionpoint.ToString("F2")+" by", p);
#endif
return true;
}
*/
}
List<Vector3> barrelStart = new List<Vector3> ();
List<Vector3> barrelDest = new List<Vector3> ();
const float barrelWidth = 0.1f; // magic
//barrelStart.Add (new Vector3 (startPosition.x-barrelWidth, startPosition.y, startPosition.z));
Vector3 barrelEdgePointStart = new Vector3 ();
Vector3 barrelEdgePointDest = new Vector3 ();
foreach (float yinc in new float[] {0f, barrelWidth, -barrelWidth}) {
barrelEdgePointStart.y = startPosition.y + yinc;
barrelEdgePointDest.y = destPosition.y + yinc;
foreach (float xinc in new float[] {0f, barrelWidth, -barrelWidth}) {
barrelEdgePointStart.x = startPosition.x + xinc;
barrelEdgePointDest.x = destPosition.x + xinc;
foreach (float zinc in new float[] {0f, barrelWidth, -barrelWidth}) {
barrelEdgePointStart.z = startPosition.z + zinc;
barrelStart.Add (barrelEdgePointStart);
barrelEdgePointDest.z = destPosition.z + zinc;
barrelDest.Add (barrelEdgePointDest);
}
}
}
foreach (Part p in parts) {
if ((p == sourceTank) || (p == destTank)) {
continue;
}
foreach (Vector3 barrelStartPos in barrelStart) {
foreach (Vector3 barrelDestPos in barrelDest) {
if (fireRayAt (p, barrelStartPos, barrelDestPos, out collisionpoint)) {
//ASPConsoleStuff.printPart ("**** fuel line barrel is obstructed at "+collisionpoint.ToString("F2")+" by", p);
if (!AutoAsparagus.blockingTanks.Contains (p)) {
AutoAsparagus.blockingTanks.Add (p);
}
return true;
}
/* Don't check against bounds since they're much more strict than the actual collider.
midPosition = Vector3.Lerp (barrelStartPos, barrelDestPos, 0.5f);
if (p.collider.bounds.Contains (midPosition)) {
#if DEBUG
ASPConsoleStuff.printPart ("**** fuel line is obstructed (barrel midPosition) at "+collisionpoint.ToString("F2")+" by", p);
#endif
return true;
}*/
}
}
}
/*Ray r = new Ray ();
r.origin = midway;
r.direction = (midway - destPosition).normalized;
RaycastHit hit = new RaycastHit ();
if (Physics.Linecast (startPosition, destPosition, out hit)) {
if (hit.rigidbody) {
Part p = hit.rigidbody.GetComponent<Part> ();
ASPConsoleStuff.printPart ("***** fuel line will collide with part", p);
}
return true;
};
List<RaycastHit> hits = new List<RaycastHit> ();
hits = new List<RaycastHit> (Physics.RaycastAll(r, Vector3.Distance (midway,destPosition)));
foreach (RaycastHit h in hits) {
if (h.collider == sourceTank.collider) {
continue;
}
if (h.collider == destTank.collider) {
continue;
}
if (h.rigidbody) {
Part p = h.rigidbody.GetComponent<Part> ();
ASPConsoleStuff.printPart ("***** fuel line will collide with part", p);
}
return true;
}
r = new Ray ();
r.origin = midway;
r.direction = (midway - startPosition).normalized;
// go both ways in case we start inside an object
hits = new List<RaycastHit> (Physics.RaycastAll(r, Vector3.Distance (midway,startPosition)));
foreach (RaycastHit h in hits) {
if (h.collider == sourceTank.collider) {
continue;
}
if (h.collider == destTank.collider) {
continue;
}
if (h.rigidbody) {
Part p = h.rigidbody.GetComponent<Part> ();
ASPConsoleStuff.printPart ("***** fuel line will collide with part", p);
}
return true;
}*/
return false;
}
public static bool AttachFuelLine (Part sourceTank, Part destTank, AvailablePart ap, int textureNum, string texturePath, string textureDisplayName)
{
ASPConsoleStuff.AAprint ("=== AttachFuelLine ===");
ASPConsoleStuff.printPart ("sourceTank", sourceTank);
ASPConsoleStuff.printPart ("destTank", destTank);
Vector3 midway = Vector3.Lerp (sourceTank.transform.position, destTank.transform.position, 0.5f);
Vector3 startPosition = new Vector3 ();
Vector3 destPosition = new Vector3 ();
ASPConsoleStuff.printVector3 ("sourceTank", sourceTank.transform.position);
ASPConsoleStuff.AAprint (" dist: " + (Vector3.Distance (sourceTank.transform.position, midway)).ToString ("F2"));
ASPConsoleStuff.printVector3 ("destTank", destTank.transform.position);
ASPConsoleStuff.AAprint (" dist: " + (Vector3.Distance (destTank.transform.position, midway)).ToString ("F2"));
ASPConsoleStuff.printVector3 ("midway", midway);
float adjustmentincrement = 0.2f; // how much to move the midpoint
float adjustment = 0.2f;
bool flcollide = isFLpathObstructed (sourceTank, destTank, midway);
while ((flcollide) && (adjustment < 100f)) {
Vector3 newmidway = new Vector3 (midway.x, midway.y, midway.z);
adjustment = adjustment + adjustmentincrement;
//adjustmentincrement = adjustmentincrement * 2f;
/*
f.transform.position = midway;
f.transform.LookAt (destTank.transform);
f.transform.Rotate (0, 90, 0);
f.transform.localPosition = f.transform.localRotation * new Vector3 (0, 0, adjustment);
newmidway = f.transform.position;
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (!flcollide) {
midway = newmidway;
break;
}
print ("break!");
flcollide = false;
*/
/*if (flcollide) {
Vector3 adjDirection = (sourceTank.transform.position - midway).normalized;
Quaternion q = Quaternion.AngleAxis(90,Vector3.forward);
adjDirection = q * adjDirection;
adjDirection = adjDirection * adjustmentincrement;
newmidway = newmidway + adjDirection;
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (!flcollide) {
midway = newmidway;
}*/
foreach (float yinc in new float[] {0f, adjustment, -adjustment}) {
newmidway.y = midway.y + yinc;
foreach (float xinc in new float[] {0f, adjustment, -adjustment}) {
newmidway.x = midway.x + xinc;
foreach (float zinc in new float[] {0f, adjustment, -adjustment}) {
newmidway.z = midway.z + zinc;
//ASPConsoleStuff.AAprint ("Testing adjustment of " + adjustment.ToString () + ", increment " + adjustmentincrement.ToString ());
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (!flcollide) {
midway = newmidway;
break;
}
}
if (!flcollide) {
midway = newmidway;
break;
}
}
if (!flcollide) {
midway = newmidway;
break;
}
}
/*
if (flcollide) {
newmidway.y = newmidway.y + adjustment;
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (flcollide) {
newmidway.y = newmidway.y - adjustment - adjustment;
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (!flcollide) {
midway = newmidway;
}
} else {
midway = newmidway;
}
}
if (flcollide) {
newmidway.y = midway.y; // only move in one dimension at once
newmidway.x = newmidway.x + adjustment;
ASPConsoleStuff.printVector3 ("Testing new midway", newmidway);
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (flcollide) {
newmidway.x = newmidway.x - adjustment - adjustment;
ASPConsoleStuff.printVector3 ("Testing new midway", newmidway);
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (!flcollide) {
midway = newmidway;
}
} else {
midway = newmidway;
}
}
if (flcollide) {
newmidway.x = midway.x; // only move in one dimension at once
newmidway.z = newmidway.z + adjustment;
ASPConsoleStuff.printVector3 ("Testing new midway", newmidway);
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (flcollide) {
newmidway.z = newmidway.z - adjustment - adjustment;
ASPConsoleStuff.printVector3 ("Testing new midway", newmidway);
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (!flcollide) {
midway = newmidway;
}
} else {
midway = newmidway;
}
}
*/
/*if (flcollide) {
Vector3 adjDirection = (sourceTank.transform.position - midway).normalized;
Quaternion q = Quaternion.AngleAxis(90,Vector3.forward);
adjDirection = q * adjDirection;
adjDirection = adjDirection * adjustmentincrement;
newmidway = newmidway + adjDirection;
flcollide = isFLpathObstructed (sourceTank, destTank, newmidway);
if (!flcollide) {
midway = newmidway;
}
}*/
}
if (adjustment >= 100) {
AutoAsparagus.osd ("Failed to find unobstructed path for fuel line!");
ASPConsoleStuff.printPart ("Failed to find unobstructed path between", sourceTank);
ASPConsoleStuff.printPart ("... and", destTank);
ASPConsoleStuff.printPartList ("Blocking Parts", "BP:", AutoAsparagus.blockingTanks);
AutoAsparagus.badStartTank = sourceTank;
AutoAsparagus.badDestTank = destTank;
fuelSetsToConnect = new List<FuelSet> ();
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return false;
}
ASPConsoleStuff.printVector3 ("New midway is", midway);
getStartDestPositions (sourceTank, destTank, midway, out startPosition, out destPosition);
ASPConsoleStuff.printVector3 ("startPosition", startPosition);
ASPConsoleStuff.printVector3 ("destPosition", destPosition);
AutoAsparagus.blockingTanks = new List<Part> (); // nothing's blocking since we've found a path
// Make a new FuelLine object
// Don't make the object until we're sure we can place it!
//AvailablePart ap = PartLoader.getPartInfoByName ("fuelLine");
UnityEngine.Object obj = UnityEngine.Object.Instantiate (ap.partPrefab);
CompoundPart f = (CompoundPart)obj;
f.gameObject.SetActive (true);
//f.gameObject.name = "fuelLine";
f.gameObject.name = ap.name;
f.partInfo = ap;
//f.highlightRecurse = true;
f.attachMode = AttachModes.SRF_ATTACH;
ASPConsoleStuff.AAprint (" set position in space");
// set position in space, relative to source tank
f.transform.localScale = sourceTank.transform.localScale;
f.transform.parent = sourceTank.transform; // must be BEFORE localposition!
//f.transform.parent = null;
//f.transform.parent = findRootPart(sourceTank).transform;
f.transform.position = startPosition;
//f.transform.parent = startTransform.parent;
//f.transform.position = startTransform.position;
//f.transform.rotation = startTransform.rotation;
// Aim the fuel node starting position at the destination position so we can calculate the direction later
//f.transform.LookAt (destTransform);
//f.transform.LookAt (destPosition);
f.transform.up = sourceTank.transform.up;
f.transform.forward = sourceTank.transform.forward;
f.transform.LookAt (destTank.transform);
f.transform.Rotate (0, 90, 0); // need to correct results from LookAt... dunno why.
ASPConsoleStuff.AAprint (" attach to source tank");
// attach to source tank
AttachNode an = new AttachNode ();
an.id = "srfAttach";
an.attachedPart = sourceTank;
an.attachMethod = AttachNodeMethod.HINGE_JOINT;
an.nodeType = AttachNode.NodeType.Surface;
an.size = 1; // found from inspecting fuel lines
an.orientation = new Vector3 (0.12500000f, 0.0f, 0.0f); // seems to be a magic number
f.srfAttachNode = an;
ASPConsoleStuff.printPart (" attach to destination", destTank);
// attach to destination tank
f.target = destTank;
ASPConsoleStuff.AAprint (" targetposition");
f.targetPosition = destPosition;
ASPConsoleStuff.AAprint (" direction");
//f.direction=(f.transform.position - destTank.transform.position).normalized;
//f.direction = f.transform.localRotation * f.transform.localPosition; // only works if destTank is parent
//f.direction = (f.transform.InverseTransformPoint(destTank.transform.position) - f.transform.localPosition).normalized; // works but crooked
//f.direction = (f.transform.InverseTransformPoint(destPosition) - f.transform.localPosition).normalized; // doesn't connect
//f.direction = (f.transform.InverseTransformPoint(destPosition) - f.transform.localPosition); // doesn't connect
f.direction = f.transform.InverseTransformPoint (destTank.transform.position).normalized; // correct!
/*if (isParent(sourceTank,destTank)){
f.direction = f.transform.localRotation * f.transform.localPosition;
} else {
f.direction = (f.transform.InverseTransformPoint(destTank.transform.position) - f.transform.localPosition).normalized;
}*/
/*
r = new Ray ();
r.origin = startPosition;
r.direction = f.direction;
hit = new RaycastHit();
if (destTank.collider.Raycast (r, out hit, 1000)){
ASPConsoleStuff.printVector3 ("f.direction hits at", hit.point);
ASPConsoleStuff.printVector3 ("destPosition at", destPosition);
print(" dist: "+(Vector3.Distance(hit.point,midway)).ToString("F2"));
} else {
print (" !!! f.direction ray failed!!!");
}*/
if (texturePath != null) {
foreach (PartModule pm in f.Modules) {
if (pm.moduleName == "FStextureSwitch2") {
pm.GetType ().GetField ("selectedTexture").SetValue (pm, textureNum);
pm.GetType ().GetField ("selectedTextureURL").SetValue (pm, texturePath);
}
}
}
// add to ship
ASPConsoleStuff.AAprint (" adding to ship");
sourceTank.addChild (f);
EditorLogic.fetch.ship.Add (f);
FuelSet fs = new FuelSet ();
fs.fromPart = sourceTank;
fs.toPart = destTank;
fs.fl = f;
fuelSetsToConnect.Add (fs);
ASPConsoleStuff.AAprint (" added to fuelSetsToConnect, total: " + fuelSetsToConnect.Count.ToString ());
return true;
}
public static void connectFuelLines ()
{
ASPConsoleStuff.AAprint ("=== Connecting " + fuelSetsToConnect.Count.ToString () + " fuel sets");
foreach (FuelSet fs in fuelSetsToConnect) {
ASPConsoleStuff.printPart ("Connecting FuelLine", fs.fl);
fs.fl.target = fs.toPart;
ASPConsoleStuff.printPart (".... to", fs.fl.target);
}
// clean out List in case someone runs connectFuelLines() again without running AddFuelLines()
fuelSetsToConnect = new List<FuelSet> ();
}
public static float distanceBetweenParts (Part a, Part b)
{
return Vector3.Distance (a.transform.position, b.transform.position);
}
private static bool hasFuelLine (Part p, string partName)
{
bool boolhasFuelLine = false;
foreach (Part child in p.children) {
if (isFuelLine (child, partName)) {
boolhasFuelLine = true;
}
}
return boolhasFuelLine;
}
private static Part nearestNeighborWithoutFuelLine (Part tank, string partName, List<Part> brothers)
{
// Check through symmetry partners, find closest tank that doesn't have a fuel line already
float closestDistance = 9999f;
Part closestPart = null;
foreach (Part p in brothers) {
if (!hasFuelLine (p, partName)) {
float distance = distanceBetweenParts (tank, p);
if (distance < closestDistance) {
closestDistance = distance;
closestPart = p;
}
}
}
return closestPart;
}
private static Part findParentFuelTank (Part p)
{
// First parent is normally decoupler, second or beyond will be the central tank
// If first parent is tank, we want to ignore it anyway
// FIXME: what about stacked tanks? tank -> tank -> decoupler -> tank -> tank -> tank
if (p == null) {
return null;
}
ASPConsoleStuff.printPart ("findParentFuelTank", p);
Part partToCheck = p.parent;
if (partToCheck == null) {
return null;
}
int safetyfactor = 10000;
while (partToCheck != null) {
safetyfactor = safetyfactor - 1;
if (safetyfactor == 0) {
AutoAsparagus.osd ("Infinite loop in findParentFuelTank(), aborting :(");
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return null;
}
partToCheck = partToCheck.parent;
if (partToCheck == null) {
return null;
}
if (ASPStaging.isConnectableFuelTank (partToCheck)) {
return partToCheck;
}
}
return null;
}
private static Part makeFuelLineChain (List<Part> tanksToConnect, Part startTank, AvailablePart ap, int textureNum, string texturePath, string textureDisplayName, int numberOfTanks)
{
Part currentTank = startTank;
tanksToConnect.Remove (startTank);
ASPConsoleStuff.printPart ("=== makeFuelLineChain, starting at", currentTank);
if (currentTank == null) {
ASPConsoleStuff.print ("makeFuelLineChain passed a null part!");
return null;
}
// connect first part to parent fuel tank
Part parentTank = findParentFuelTank (currentTank);
if (parentTank == null) {
ASPConsoleStuff.printPart ("no parent fuel tank found found! Not connecting", currentTank);
} else {
if (!AttachFuelLine (currentTank, parentTank, ap, textureNum, texturePath, textureDisplayName)) {
tanksToConnect = new List<Part> ();
return null;
}
}
// Decide on fuel line chain length (not including fuel line to parent fuel tank we just did)
// 10-way symmetry will have (10-2)/2 = 4 for each side
// 8-way symmetry will have (8-2)/2 = 3 for each side
// 6-way symmetry will have (6-2)/2 = 2 for each side
// 4-way symmetry will have (4-2)/2 = 1 for each side
// 2-way symmetry will have (2-2)/2 = 0 for each side (we will just connect the tanks to the central tank)
int tanksToDropAtOnce = 2;
int[] primes = new int[] {
17,
13,
11,
7,
5,
3,
2,
};
foreach (int prime in primes) {
ASPConsoleStuff.AAprint ("Testing prime " + prime.ToString ());
if ((numberOfTanks % prime) == 0) {
tanksToDropAtOnce = prime;
}
}
int chainLength = (numberOfTanks / tanksToDropAtOnce - 1);
ASPConsoleStuff.AAprint ("Fuel line chain length: " + chainLength.ToString () + ", dropping " + tanksToDropAtOnce.ToString () + " tanks at once (from " + numberOfTanks.ToString () + " tanks)");
// Now connect chainLength number of tanks to the first part
int currentChainLength = chainLength;
Part lastTank = currentTank;
Part nextTank = null;
int safetyfactor = 10000;
while (currentChainLength > 0) {
safetyfactor = safetyfactor - 1;
if (safetyfactor == 0) {
AutoAsparagus.osd ("Infinite loop in makeFuelLineChain, aborting :(");
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return null;
}
ASPConsoleStuff.printPart ("connecting chain link #" + currentChainLength.ToString (), currentTank);
nextTank = nearestNeighborWithoutFuelLine (currentTank, ap.name, tanksToConnect);
if (nextTank == null) {
ASPConsoleStuff.printPart ("no nearestNeighborWithoutFuelLine found! Not connecting", currentTank);
} else {
// we're working backwards, away from central tank, so we connect the new tank to the existing one
if (!AttachFuelLine (nextTank, currentTank, ap, textureNum, texturePath, textureDisplayName)) {
tanksToConnect = new List<Part> ();
return null;
}
lastTank = nextTank;
currentTank = nextTank;
tanksToConnect.Remove (currentTank);
}
currentChainLength = currentChainLength - 1;
}
// return the tank for the next chain
ASPConsoleStuff.printPart ("lastTank=", lastTank);
nextTank = nearestNeighborWithoutFuelLine (lastTank, ap.name, tanksToConnect);
ASPConsoleStuff.printPart ("Should start next chain with", nextTank);
return nextTank;
}
private static Part findStartofChain (List<Part> tanksToConnect, Part rootPart, string partName)
{
// start at the root node, and then look progressively down the tree for tanks to stage
// don't recurse down depth-first; instead do breadth-first searching
ASPConsoleStuff.printPart ("=== findStartofChain, starting with", rootPart);
List<Part> children = rootPart.children;
Part currentTank = null;
ASPConsoleStuff.printPartList ("rootChildren", "child", children);
int safetyfactor = 10000;
while ((currentTank == null) && (children.Count > 0)) {
safetyfactor = safetyfactor - 1;
if (safetyfactor == 0) {
AutoAsparagus.osd ("Infinite loop in findStartofChain, aborting :(");
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return null;
}
List<Part> newchildren = new List<Part> ();
// check every child at this level, before moving a level down the tree
foreach (Part child in children) {
currentTank = chooseNextTankToConnect (tanksToConnect, child, partName);
if (currentTank != null) {
ASPConsoleStuff.printPart ("findStartofChain returning", currentTank);
return currentTank;
}
foreach (Part gc in child.children) {
newchildren.Add (gc);
}
}
children = newchildren;
}
return null;
}
public static int countDecouplersToRoot (Part p)
{
int x = 0;
Part currentPart = p;
while (currentPart != null) {
if (ASPStaging.isDecoupler (currentPart)) {
if (currentPart.parent != null) { // don't count a root decoupler as an actual decoupler
x = x + 1;
}
}
currentPart = currentPart.parent;
}
return x;
}
public static Part findCentralTank (Part p)
{
ASPConsoleStuff.printPart ("findCentralTank", p);
Part currentPart = p;
Part centralTank = null;
while (currentPart != null) {
if (ASPStaging.isFuelTank (currentPart)) {
centralTank = currentPart;
}
currentPart = currentPart.parent;
}
return centralTank;
}
public static void AddAsparagusFuelLines (AvailablePart ap, int textureNum, string[] texturePath, string[] textureDisplayName, bool rainbow)
{
ASPConsoleStuff.AAprint ("=== AddAsparagusFuelLines ===");
AutoAsparagus.badStartTank = null;
AutoAsparagus.badDestTank = null;
AutoAsparagus.blockingTanks = new List<Part> ();
// Get all the parts of the ship
EditorLogic editor = EditorLogic.fetch;
ShipConstruct ship = editor.ship;
List<Part> parts = ship.parts;
parts [0].SetHighlight (false, true);
// start a new list of fuel lines to connect
//fuelSetsToConnect = new List<FuelSet>();
// Find the symmetrical fuel tanks
List<Part> tanks = ASPStaging.findFuelTanks (parts);
List<Part> tanksToConnect = new List<Part> ();
// get list of tanks to connect
int safetyfactor = 10000;
while (tanks.Count > 0) {
safetyfactor = safetyfactor - 1;
if (safetyfactor == 0) {
AutoAsparagus.osd ("Infinite loop in AddFuelLines:tanks.Count, aborting :(");
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return;
}
Part p = tanks [0];
bool connectTank = true;
if (hasFuelLine (p, ap.name)) {
ASPConsoleStuff.printPart ("Tank already has a fuel line", p);
connectTank = false;
}
if (connectTank) {
ASPConsoleStuff.printPart ("... will connect tank", p);
tanksToConnect.Add (p);
}
tanks.Remove (p);
}
/*
repeat for every central tank with >1 decoupler {
all decoupler+tank attached is onionRing[0]
all decoupler+tank attached to onionRing[0] is onionRing [1]
all decoupler+tank attached to onionRing[1] is onionRing [2], etc
fuel routing:
start central tank: getclosest of onionRing[0]
wire up onionRing[0] with onionRing[0].Count/2 tanks
getclosest of onionRing[1], wire up onionRing[1].Count/2 tanks
getclosest of onionRing[2], wire up onionRing[2].Count/2 tanks, etc
start again from central tank: getclosest of onionRing[0]
wire up onionRing[0] with onionRing[0].Count/2 tanks
getclosest of onionRing[1], wire up onionRing[1].Count/2 tanks
getclosest of onionRing[2], wire up onionRing[2].Count/2 tanks, etc
}
*/
OnionRings = new SortedDictionary<int, List<Part>> ();
int onionRingLevel = 0;
foreach (Part p in tanksToConnect) {
onionRingLevel = countDecouplersToRoot (p);
if (onionRingLevel > 0) { // only connect tanks that can be decoupled
Part centralTank = findCentralTank (p);
ASPConsoleStuff.printPart ("onionRing part at level " + onionRingLevel.ToString (), p);
ASPConsoleStuff.printPart ("central tank", centralTank);
onionRingLevel = onionRingLevel + 1000 * Math.Abs (centralTank.GetInstanceID ());
ASPConsoleStuff.AAprint ("new onionRingLevel: " + onionRingLevel.ToString ());
if (OnionRings.ContainsKey (onionRingLevel)) {
OnionRings [onionRingLevel].Add (p);
} else {
List<Part> foo = new List<Part> ();
foo.Add (p);
OnionRings.Add (onionRingLevel, foo);
}
}
}
// debug printing of onion rings
foreach (int key in OnionRings.Keys) {
ASPConsoleStuff.AAprint ("Onion ring: " + key.ToString ());
foreach (Part p in OnionRings[key]) {
ASPConsoleStuff.printPart ("onion", p);
}
}
foreach (int onionLevel in OnionRings.Keys) {
int orignalNumberOfTanks = OnionRings [onionLevel].Count;
ASPConsoleStuff.AAprint ("Onion ring: " + onionLevel.ToString () + ", " + orignalNumberOfTanks + " tanks");
if (orignalNumberOfTanks < 2) {
ASPConsoleStuff.AAprint ("Skipping ring because it has too few members");
} else {
tanksToConnect = OnionRings [onionLevel];
Part nextTank = null;
safetyfactor = 10000;
while (tanksToConnect.Count > 0) {
safetyfactor = safetyfactor - 1;
if (safetyfactor == 0) {
AutoAsparagus.osd ("Infinite loop in AddFuelLines:tanksToConnect.Count, aborting :(");
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return;
}
if (nextTank == null) {
nextTank = findStartofChain (tanksToConnect, parts [0], ap.name);
if (nextTank == null) { // rut roh
break;
}
}
ASPConsoleStuff.printPart ("AddFuelLines: nextTank", nextTank);
ASPConsoleStuff.printPartList ("AddFuelLines: Tanks to connect", "tank", tanksToConnect);
string texturePathString = null;
string textureName = null;
if (texturePath != null) {
texturePathString = texturePath [textureNum];
textureName = textureDisplayName [textureNum];
}
nextTank = makeFuelLineChain (tanksToConnect, nextTank, ap, textureNum, texturePathString, textureName, orignalNumberOfTanks);
if (rainbow) {
ASPConsoleStuff.AAprint ("oh, rainBOWs..." + textureNum.ToString ());
textureNum = textureNum + 1;
if (textureNum > (texturePath.Length - 1)) {
textureNum = 0;
}
}
}
}
}
//StageManager.Instance.SortIcons (true);
}
private static bool isTargetofFuelLine (Part target, string partName)
{
// Check if any fuel line anywhere points to this part
EditorLogic editor = EditorLogic.fetch;
ShipConstruct ship = editor.ship;
List<Part> parts = ship.parts;
foreach (Part p in parts) {
if (isFuelLine (p, partName)) {
CompoundPart f = (CompoundPart)p;
if (f.target == target) {
return true;
}
}
}
return false;
}
private static Part chooseNextTankToConnect (List<Part> tanksToConnect, Part rootPart, string partName)
{
// Find the inner-most tank that needs to be connected
ASPConsoleStuff.printPart ("chooseNextTankToConnect", rootPart);
foreach (Part p in rootPart.children) {
ASPConsoleStuff.printPart ("considering for start of chain", p);
if (tanksToConnect.Contains (p)) {
ASPConsoleStuff.AAprint ("... is in tanksToConnect");
if ((!hasFuelLine (p, partName)) && (!isTargetofFuelLine (p, partName))) {
ASPConsoleStuff.AAprint ("... no fuel lines");
Part parentTank = findParentFuelTank (p);
/*
if ((hasFuelLine (parentTank)) && (!isTargetofFuelLine(parentTank))) {
ASPConsoleStuff.printPart ("... parent has fuel line but isn't target, returning p",p);
// tank that starts an inner chain
return p;
}
Part gp = findParentFuelTank(parentTank);
if (gp == null) {
ASPConsoleStuff.printPart ("... gp is null, returning p",p);
// we're on the first ring.. just return any part
return p;
}
*/
if (!isTargetofFuelLine (parentTank, partName)) {
ASPConsoleStuff.printPart ("... parent isn't target of fuel line, returning p", p);
// tank that starts an inner chain
return p;
}
}
}
}
return null;
}
public static void AddOnionFuelLines (AvailablePart ap, int textureNum, string[] texturePath, string[] textureDisplayName, bool rainbow)
{
ASPConsoleStuff.AAprint ("=== AddOnionFuelLines ===");
AutoAsparagus.badStartTank = null;
AutoAsparagus.badDestTank = null;
AutoAsparagus.blockingTanks = new List<Part> ();
// Get all the parts of the ship
EditorLogic editor = EditorLogic.fetch;
ShipConstruct ship = editor.ship;
List<Part> parts = ship.parts;
parts [0].SetHighlight (false, true);
// start a new list of fuel lines to connect
//fuelSetsToConnect = new List<FuelSet>();
// Find the symmetrical fuel tanks
List<Part> tanks = ASPStaging.findFuelTanks (parts);
List<Part> tanksToConnect = new List<Part> ();
// get list of tanks to connect
int safetyfactor = 10000;
while (tanks.Count > 0) {
safetyfactor = safetyfactor - 1;
if (safetyfactor == 0) {
AutoAsparagus.osd ("Infinite loop in AddOnionFuelLines:tanks.Count, aborting :(");
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return;
}
Part p = tanks [0];
bool connectTank = true;
foreach (Part child in p.children) {
if (isFuelLine (child, ap.name)) {
ASPConsoleStuff.printPart ("Tank already has a fuel line", p);
connectTank = false;
}
}
if (connectTank) {
ASPConsoleStuff.printPart ("... will connect tank", p);
tanksToConnect.Add (p);
}
tanks.Remove (p);
}
safetyfactor = 10000;
while (tanksToConnect.Count > 0) {
safetyfactor = safetyfactor - 1;
if (safetyfactor == 0) {
AutoAsparagus.osd ("Infinite loop in AddOnionFuelLines:tankstoConnect.Count, aborting :(");
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return;
}
ASPConsoleStuff.printPartList ("Tanks to connect", "tank", tanksToConnect);
Part currentTank = tanksToConnect [0];
// connect first part to parent fuel tank
Part parentTank = findParentFuelTank (currentTank);
if (parentTank == null) {
ASPConsoleStuff.printPart ("no parent fuel tank found found! Not connecting", currentTank);
} else {
string texturePathString = null;
string textureName = null;
if (texturePath != null) {
texturePathString = texturePath [textureNum];
textureName = textureDisplayName [textureNum];
}
AttachFuelLine (currentTank, parentTank, ap, textureNum, texturePathString, textureName);
if (rainbow) {
ASPConsoleStuff.AAprint ("oh, rainBOWs..." + textureNum.ToString ());
textureNum = textureNum + 1;
if (textureNum > (texturePath.Length - 1)) {
textureNum = 0;
}
}
}
tanksToConnect.Remove (currentTank);
}
//StageManager.Instance.SortIcons (true);
}
public static int DeleteAllFuelLines (string partName)
{
EditorLogic editor = EditorLogic.fetch;
ShipConstruct ship = editor.ship;
List<Part> parts = ship.parts;
List<Part> partsToDelete = new List<Part> ();
foreach (Part p in parts) {
if (isFuelLine (p, partName)) {
ASPConsoleStuff.printPart ("Marking fuel line for death", p);
partsToDelete.Add (p);
}
}
int safetyfactor = 10000;
int count = 0;
while (partsToDelete.Count > 0) {
safetyfactor = safetyfactor - 1;
if (safetyfactor == 0) {
AutoAsparagus.osd ("Infinite loop in DeleteAllFuelLines:partsToDelete.Count, aborting :(");
AutoAsparagus.mystate = AutoAsparagus.ASPState.ERROR;
return count;
}
Part p = partsToDelete [0];
ASPConsoleStuff.printPart ("Deleting part", p);
Part parent = p.parent;
if (parent != null) {
parent.removeChild (p);
}
parts.Remove (p);
partsToDelete.Remove (p);
count = count + 1;
}
return 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;
using System.Collections.Generic;
using List_ListUtils;
namespace List_ListUtils
{
public class SimpleRef<T>
{
private T _val;
public SimpleRef(T t)
{
_val = t;
}
public T Val
{
get { return _val; }
set { _val = value; }
}
}
public struct SimpleVal<T>
{
private T _val;
public SimpleVal(T t)
{
_val = t;
}
public T Val
{
get { return _val; }
set { _val = value; }
}
}
public interface IComparableValue
{
System.IComparable Val { get; set; }
int CompareTo(IComparableValue obj);
}
public class ValueComparer<T> : System.Collections.Generic.IComparer<T> where T : IComparableValue
{
public int Compare(T x, T y)
{
if (null == (object)x)
if (null == (object)y)
return 0;
else
return -1;
if (null == (object)y)
return 1;
if (null == (object)x.Val)
if (null == (object)y.Val)
return 0;
else
return -1;
return x.Val.CompareTo(y.Val);
}
public bool Equals(T x, T y)
{
return 0 == Compare(x, y);
}
public int GetHashCode(T x)
{
return x.GetHashCode();
}
}
public class IValueComparer<T> : System.Collections.Generic.IComparer<T> where T : IComparableValue
{
public int Compare(T x, T y)
{
if (null == (object)x)
if (null == (object)y)
return 0;
else
return -1;
if (null == (object)x.Val)
if (null == (object)y.Val)
return 0;
else
return -1;
return x.Val.CompareTo(y.Val);
}
public bool Equals(T x, T y)
{
return 0 == Compare(x, y);
}
public int GetHashCode(T x)
{
return x.GetHashCode();
}
}
public class RefX1<T> : System.IComparable<RefX1<T>> where T : System.IComparable
{
private T _val;
public T Val
{
get { return _val; }
set { _val = value; }
}
public RefX1(T t) { _val = t; }
public int CompareTo(RefX1<T> obj)
{
if (null == obj)
return 1;
if (null == _val)
if (null == obj.Val)
return 0;
else
return -1;
return _val.CompareTo(obj.Val);
}
public override bool Equals(object obj)
{
if (obj is RefX1<T>)
{
RefX1<T> v = (RefX1<T>)obj;
return (CompareTo(v) == 0);
}
return false;
}
public override int GetHashCode() { return base.GetHashCode(); }
public bool Equals(RefX1<T> x)
{
return 0 == CompareTo(x);
}
}
public struct ValX1<T> : System.IComparable<ValX1<T>> where T : System.IComparable
{
private T _val;
public T Val
{
get { return _val; }
set { _val = value; }
}
public ValX1(T t) { _val = t; }
public int CompareTo(ValX1<T> obj)
{
if (Object.ReferenceEquals(_val, obj._val)) return 0;
if (null == _val)
return -1;
return _val.CompareTo(obj.Val);
}
public override bool Equals(object obj)
{
if (obj is ValX1<T>)
{
ValX1<T> v = (ValX1<T>)obj;
return (CompareTo(v) == 0);
}
return false;
}
public override int GetHashCode() { return ((object)this).GetHashCode(); }
public bool Equals(ValX1<T> x)
{
return 0 == CompareTo(x);
}
}
public class RefX1_IC<T> : IComparableValue where T : System.IComparable
{
private T _val;
public System.IComparable Val
{
get { return _val; }
set { _val = (T)(object)value; }
}
public RefX1_IC(T t) { _val = t; }
public int CompareTo(IComparableValue obj)
{
if (null == (object)obj)
return 1;
if (null == (object)_val)
if (null == (object)obj.Val)
return 0;
else
return -1;
return _val.CompareTo(obj.Val);
}
}
public struct ValX1_IC<T> : IComparableValue where T : System.IComparable
{
private T _val;
public System.IComparable Val
{
get { return _val; }
set { _val = (T)(object)value; }
}
public ValX1_IC(T t) { _val = t; }
public int CompareTo(IComparableValue obj)
{
return _val.CompareTo(obj.Val);
}
}
public class TestCollection<T> : ICollection<T>
{
//
//Expose the array to give more test flexibility...
//
public T[] _items;
public TestCollection() { }
public TestCollection(T[] items)
{
_items = items;
}
//
//ICollection<T>
//
public void CopyTo(T[] array, int index)
{
Array.Copy(_items, 0, array, index, _items.Length);
}
public int Count
{
get
{
if (_items == null)
return 0;
else
return _items.Length;
}
}
public Object SyncRoot
{ get { return this; } }
public bool IsSynchronized
{ get { return false; } }
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
throw new NotSupportedException();
}
public bool Remove(T item)
{
throw new NotSupportedException();
}
public bool IsReadOnly
{
get
{
throw new NotSupportedException();
}
}
//
//IEnumerable<T>
//
public IEnumerator<T> GetEnumerator()
{
return new TestCollectionEnumerator<T>(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new TestCollectionEnumerator<T>(this);
}
//
//TestCollectionEnumerator<T>
//
private class TestCollectionEnumerator<T1> : IEnumerator<T1>
{
private TestCollection<T1> _col;
private int _index;
public void Dispose() { }
public TestCollectionEnumerator(TestCollection<T1> col)
{
_col = col;
_index = -1;
}
public bool MoveNext()
{
return (++_index < _col._items.Length);
}
public T1 Current
{
get { return _col._items[_index]; }
}
Object System.Collections.IEnumerator.Current
{
get { return _col._items[_index]; }
}
public void Reset()
{
_index = -1;
}
}
}
public class Test
{
public static int counter = 0;
public static bool result = true;
public static bool Eval(bool exp)
{
counter++;
return Eval(exp, null);
}
public static bool Eval(bool exp, String errorMsg)
{
if (!exp)
{
//This would never be reset, since we start with true and only set it to false if the Eval fails
result = exp;
String err = errorMsg;
if (err == null)
err = "Test Failed at location: " + counter;
Console.WriteLine(err);
}
return exp;
}
public static bool Eval(bool exp, String format, params object[] arg)
{
if (!exp)
{
return Eval(exp, String.Format(format, arg));
}
return true;
}
public static bool Eval<T>(T expected, T actual, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
public static bool Eval<T>(T expected, T actual, String format, params object[] arg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, String.Format(format, arg) +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
}
}
| |
// Copyright 2017, Google LLC 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.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.PubSub.V1.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedSubscriberClientSnippets
{
/// <summary>Snippet for CreateSubscriptionAsync</summary>
public async Task CreateSubscriptionAsync()
{
// Snippet: CreateSubscriptionAsync(SubscriptionName,TopicName,PushConfig,int?,CallSettings)
// Additional: CreateSubscriptionAsync(SubscriptionName,TopicName,PushConfig,int?,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SubscriptionName name = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
PushConfig pushConfig = new PushConfig();
int ackDeadlineSeconds = 0;
// Make the request
Subscription response = await subscriberClient.CreateSubscriptionAsync(name, topic, pushConfig, ackDeadlineSeconds);
// End snippet
}
/// <summary>Snippet for CreateSubscription</summary>
public void CreateSubscription()
{
// Snippet: CreateSubscription(SubscriptionName,TopicName,PushConfig,int?,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SubscriptionName name = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
PushConfig pushConfig = new PushConfig();
int ackDeadlineSeconds = 0;
// Make the request
Subscription response = subscriberClient.CreateSubscription(name, topic, pushConfig, ackDeadlineSeconds);
// End snippet
}
/// <summary>Snippet for CreateSubscriptionAsync</summary>
public async Task CreateSubscriptionAsync_RequestObject()
{
// Snippet: CreateSubscriptionAsync(Subscription,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
Subscription request = new Subscription
{
SubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicNameOneof = TopicNameOneof.From(new TopicName("[PROJECT]", "[TOPIC]")),
};
// Make the request
Subscription response = await subscriberClient.CreateSubscriptionAsync(request);
// End snippet
}
/// <summary>Snippet for CreateSubscription</summary>
public void CreateSubscription_RequestObject()
{
// Snippet: CreateSubscription(Subscription,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
Subscription request = new Subscription
{
SubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicNameOneof = TopicNameOneof.From(new TopicName("[PROJECT]", "[TOPIC]")),
};
// Make the request
Subscription response = subscriberClient.CreateSubscription(request);
// End snippet
}
/// <summary>Snippet for GetSubscriptionAsync</summary>
public async Task GetSubscriptionAsync()
{
// Snippet: GetSubscriptionAsync(SubscriptionName,CallSettings)
// Additional: GetSubscriptionAsync(SubscriptionName,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
Subscription response = await subscriberClient.GetSubscriptionAsync(subscription);
// End snippet
}
/// <summary>Snippet for GetSubscription</summary>
public void GetSubscription()
{
// Snippet: GetSubscription(SubscriptionName,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
Subscription response = subscriberClient.GetSubscription(subscription);
// End snippet
}
/// <summary>Snippet for GetSubscriptionAsync</summary>
public async Task GetSubscriptionAsync_RequestObject()
{
// Snippet: GetSubscriptionAsync(GetSubscriptionRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
GetSubscriptionRequest request = new GetSubscriptionRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
};
// Make the request
Subscription response = await subscriberClient.GetSubscriptionAsync(request);
// End snippet
}
/// <summary>Snippet for GetSubscription</summary>
public void GetSubscription_RequestObject()
{
// Snippet: GetSubscription(GetSubscriptionRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
GetSubscriptionRequest request = new GetSubscriptionRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
};
// Make the request
Subscription response = subscriberClient.GetSubscription(request);
// End snippet
}
/// <summary>Snippet for UpdateSubscriptionAsync</summary>
public async Task UpdateSubscriptionAsync_RequestObject()
{
// Snippet: UpdateSubscriptionAsync(UpdateSubscriptionRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
UpdateSubscriptionRequest request = new UpdateSubscriptionRequest
{
Subscription = new Subscription
{
AckDeadlineSeconds = 42,
},
UpdateMask = new FieldMask
{
Paths = {
"ack_deadline_seconds",
},
},
};
// Make the request
Subscription response = await subscriberClient.UpdateSubscriptionAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateSubscription</summary>
public void UpdateSubscription_RequestObject()
{
// Snippet: UpdateSubscription(UpdateSubscriptionRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
UpdateSubscriptionRequest request = new UpdateSubscriptionRequest
{
Subscription = new Subscription
{
AckDeadlineSeconds = 42,
},
UpdateMask = new FieldMask
{
Paths = {
"ack_deadline_seconds",
},
},
};
// Make the request
Subscription response = subscriberClient.UpdateSubscription(request);
// End snippet
}
/// <summary>Snippet for ListSubscriptionsAsync</summary>
public async Task ListSubscriptionsAsync()
{
// Snippet: ListSubscriptionsAsync(ProjectName,string,int?,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
ProjectName project = new ProjectName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListSubscriptionsResponse, Subscription> response =
subscriberClient.ListSubscriptionsAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Subscription item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSubscriptionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Subscription item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Subscription> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Subscription item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSubscriptions</summary>
public void ListSubscriptions()
{
// Snippet: ListSubscriptions(ProjectName,string,int?,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
ProjectName project = new ProjectName("[PROJECT]");
// Make the request
PagedEnumerable<ListSubscriptionsResponse, Subscription> response =
subscriberClient.ListSubscriptions(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (Subscription item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSubscriptionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Subscription item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Subscription> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Subscription item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSubscriptionsAsync</summary>
public async Task ListSubscriptionsAsync_RequestObject()
{
// Snippet: ListSubscriptionsAsync(ListSubscriptionsRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
ListSubscriptionsRequest request = new ListSubscriptionsRequest
{
ProjectAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListSubscriptionsResponse, Subscription> response =
subscriberClient.ListSubscriptionsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Subscription item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSubscriptionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Subscription item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Subscription> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Subscription item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSubscriptions</summary>
public void ListSubscriptions_RequestObject()
{
// Snippet: ListSubscriptions(ListSubscriptionsRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
ListSubscriptionsRequest request = new ListSubscriptionsRequest
{
ProjectAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListSubscriptionsResponse, Subscription> response =
subscriberClient.ListSubscriptions(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Subscription item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSubscriptionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Subscription item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Subscription> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Subscription item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeleteSubscriptionAsync</summary>
public async Task DeleteSubscriptionAsync()
{
// Snippet: DeleteSubscriptionAsync(SubscriptionName,CallSettings)
// Additional: DeleteSubscriptionAsync(SubscriptionName,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
await subscriberClient.DeleteSubscriptionAsync(subscription);
// End snippet
}
/// <summary>Snippet for DeleteSubscription</summary>
public void DeleteSubscription()
{
// Snippet: DeleteSubscription(SubscriptionName,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
subscriberClient.DeleteSubscription(subscription);
// End snippet
}
/// <summary>Snippet for DeleteSubscriptionAsync</summary>
public async Task DeleteSubscriptionAsync_RequestObject()
{
// Snippet: DeleteSubscriptionAsync(DeleteSubscriptionRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
DeleteSubscriptionRequest request = new DeleteSubscriptionRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
};
// Make the request
await subscriberClient.DeleteSubscriptionAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteSubscription</summary>
public void DeleteSubscription_RequestObject()
{
// Snippet: DeleteSubscription(DeleteSubscriptionRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
DeleteSubscriptionRequest request = new DeleteSubscriptionRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
};
// Make the request
subscriberClient.DeleteSubscription(request);
// End snippet
}
/// <summary>Snippet for ModifyAckDeadlineAsync</summary>
public async Task ModifyAckDeadlineAsync()
{
// Snippet: ModifyAckDeadlineAsync(SubscriptionName,IEnumerable<string>,int,CallSettings)
// Additional: ModifyAckDeadlineAsync(SubscriptionName,IEnumerable<string>,int,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> ackIds = new List<string>();
int ackDeadlineSeconds = 0;
// Make the request
await subscriberClient.ModifyAckDeadlineAsync(subscription, ackIds, ackDeadlineSeconds);
// End snippet
}
/// <summary>Snippet for ModifyAckDeadline</summary>
public void ModifyAckDeadline()
{
// Snippet: ModifyAckDeadline(SubscriptionName,IEnumerable<string>,int,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> ackIds = new List<string>();
int ackDeadlineSeconds = 0;
// Make the request
subscriberClient.ModifyAckDeadline(subscription, ackIds, ackDeadlineSeconds);
// End snippet
}
/// <summary>Snippet for ModifyAckDeadlineAsync</summary>
public async Task ModifyAckDeadlineAsync_RequestObject()
{
// Snippet: ModifyAckDeadlineAsync(ModifyAckDeadlineRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { },
AckDeadlineSeconds = 0,
};
// Make the request
await subscriberClient.ModifyAckDeadlineAsync(request);
// End snippet
}
/// <summary>Snippet for ModifyAckDeadline</summary>
public void ModifyAckDeadline_RequestObject()
{
// Snippet: ModifyAckDeadline(ModifyAckDeadlineRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { },
AckDeadlineSeconds = 0,
};
// Make the request
subscriberClient.ModifyAckDeadline(request);
// End snippet
}
/// <summary>Snippet for AcknowledgeAsync</summary>
public async Task AcknowledgeAsync()
{
// Snippet: AcknowledgeAsync(SubscriptionName,IEnumerable<string>,CallSettings)
// Additional: AcknowledgeAsync(SubscriptionName,IEnumerable<string>,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> ackIds = new List<string>();
// Make the request
await subscriberClient.AcknowledgeAsync(subscription, ackIds);
// End snippet
}
/// <summary>Snippet for Acknowledge</summary>
public void Acknowledge()
{
// Snippet: Acknowledge(SubscriptionName,IEnumerable<string>,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
IEnumerable<string> ackIds = new List<string>();
// Make the request
subscriberClient.Acknowledge(subscription, ackIds);
// End snippet
}
/// <summary>Snippet for AcknowledgeAsync</summary>
public async Task AcknowledgeAsync_RequestObject()
{
// Snippet: AcknowledgeAsync(AcknowledgeRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
AcknowledgeRequest request = new AcknowledgeRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { },
};
// Make the request
await subscriberClient.AcknowledgeAsync(request);
// End snippet
}
/// <summary>Snippet for Acknowledge</summary>
public void Acknowledge_RequestObject()
{
// Snippet: Acknowledge(AcknowledgeRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
AcknowledgeRequest request = new AcknowledgeRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { },
};
// Make the request
subscriberClient.Acknowledge(request);
// End snippet
}
/// <summary>Snippet for PullAsync</summary>
public async Task PullAsync()
{
// Snippet: PullAsync(SubscriptionName,bool?,int,CallSettings)
// Additional: PullAsync(SubscriptionName,bool?,int,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
bool returnImmediately = false;
int maxMessages = 0;
// Make the request
PullResponse response = await subscriberClient.PullAsync(subscription, returnImmediately, maxMessages);
// End snippet
}
/// <summary>Snippet for Pull</summary>
public void Pull()
{
// Snippet: Pull(SubscriptionName,bool?,int,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
bool returnImmediately = false;
int maxMessages = 0;
// Make the request
PullResponse response = subscriberClient.Pull(subscription, returnImmediately, maxMessages);
// End snippet
}
/// <summary>Snippet for PullAsync</summary>
public async Task PullAsync_RequestObject()
{
// Snippet: PullAsync(PullRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
PullRequest request = new PullRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
MaxMessages = 0,
};
// Make the request
PullResponse response = await subscriberClient.PullAsync(request);
// End snippet
}
/// <summary>Snippet for Pull</summary>
public void Pull_RequestObject()
{
// Snippet: Pull(PullRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
PullRequest request = new PullRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
MaxMessages = 0,
};
// Make the request
PullResponse response = subscriberClient.Pull(request);
// End snippet
}
/// <summary>Snippet for StreamingPull</summary>
public async Task StreamingPull()
{
// Snippet: StreamingPull(CallSettings,BidirectionalStreamingSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize streaming call, retrieving the stream object
SubscriberClient.StreamingPullStream duplexStream = subscriberClient.StreamingPull();
// Sending requests and retrieving responses can be arbitrarily interleaved.
// Exact sequence will depend on client/server behavior.
// Create task to do something with responses from server
Task responseHandlerTask = Task.Run(async () =>
{
IAsyncEnumerator<StreamingPullResponse> responseStream = duplexStream.ResponseStream;
while (await responseStream.MoveNext())
{
StreamingPullResponse response = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
});
// Send requests to the server
bool done = false;
while (!done)
{
// Initialize a request
StreamingPullRequest request = new StreamingPullRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
StreamAckDeadlineSeconds = 0,
};
// Stream a request to the server
await duplexStream.WriteAsync(request);
// Set "done" to true when sending requests is complete
}
// Complete writing requests to the stream
await duplexStream.WriteCompleteAsync();
// Await the response handler.
// This will complete once all server responses have been processed.
await responseHandlerTask;
// End snippet
}
/// <summary>Snippet for ModifyPushConfigAsync</summary>
public async Task ModifyPushConfigAsync()
{
// Snippet: ModifyPushConfigAsync(SubscriptionName,PushConfig,CallSettings)
// Additional: ModifyPushConfigAsync(SubscriptionName,PushConfig,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
PushConfig pushConfig = new PushConfig();
// Make the request
await subscriberClient.ModifyPushConfigAsync(subscription, pushConfig);
// End snippet
}
/// <summary>Snippet for ModifyPushConfig</summary>
public void ModifyPushConfig()
{
// Snippet: ModifyPushConfig(SubscriptionName,PushConfig,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
PushConfig pushConfig = new PushConfig();
// Make the request
subscriberClient.ModifyPushConfig(subscription, pushConfig);
// End snippet
}
/// <summary>Snippet for ModifyPushConfigAsync</summary>
public async Task ModifyPushConfigAsync_RequestObject()
{
// Snippet: ModifyPushConfigAsync(ModifyPushConfigRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
ModifyPushConfigRequest request = new ModifyPushConfigRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
PushConfig = new PushConfig(),
};
// Make the request
await subscriberClient.ModifyPushConfigAsync(request);
// End snippet
}
/// <summary>Snippet for ModifyPushConfig</summary>
public void ModifyPushConfig_RequestObject()
{
// Snippet: ModifyPushConfig(ModifyPushConfigRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
ModifyPushConfigRequest request = new ModifyPushConfigRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
PushConfig = new PushConfig(),
};
// Make the request
subscriberClient.ModifyPushConfig(request);
// End snippet
}
/// <summary>Snippet for ListSnapshotsAsync</summary>
public async Task ListSnapshotsAsync()
{
// Snippet: ListSnapshotsAsync(ProjectName,string,int?,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
ProjectName project = new ProjectName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListSnapshotsResponse, Snapshot> response =
subscriberClient.ListSnapshotsAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Snapshot item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSnapshotsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Snapshot item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Snapshot> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Snapshot item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSnapshots</summary>
public void ListSnapshots()
{
// Snippet: ListSnapshots(ProjectName,string,int?,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
ProjectName project = new ProjectName("[PROJECT]");
// Make the request
PagedEnumerable<ListSnapshotsResponse, Snapshot> response =
subscriberClient.ListSnapshots(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (Snapshot item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSnapshotsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Snapshot item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Snapshot> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Snapshot item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSnapshotsAsync</summary>
public async Task ListSnapshotsAsync_RequestObject()
{
// Snippet: ListSnapshotsAsync(ListSnapshotsRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
ListSnapshotsRequest request = new ListSnapshotsRequest
{
ProjectAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListSnapshotsResponse, Snapshot> response =
subscriberClient.ListSnapshotsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Snapshot item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSnapshotsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Snapshot item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Snapshot> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Snapshot item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSnapshots</summary>
public void ListSnapshots_RequestObject()
{
// Snippet: ListSnapshots(ListSnapshotsRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
ListSnapshotsRequest request = new ListSnapshotsRequest
{
ProjectAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListSnapshotsResponse, Snapshot> response =
subscriberClient.ListSnapshots(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Snapshot item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSnapshotsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Snapshot item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Snapshot> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Snapshot item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CreateSnapshotAsync</summary>
public async Task CreateSnapshotAsync()
{
// Snippet: CreateSnapshotAsync(SnapshotName,SubscriptionName,CallSettings)
// Additional: CreateSnapshotAsync(SnapshotName,SubscriptionName,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SnapshotName name = new SnapshotName("[PROJECT]", "[SNAPSHOT]");
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
Snapshot response = await subscriberClient.CreateSnapshotAsync(name, subscription);
// End snippet
}
/// <summary>Snippet for CreateSnapshot</summary>
public void CreateSnapshot()
{
// Snippet: CreateSnapshot(SnapshotName,SubscriptionName,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SnapshotName name = new SnapshotName("[PROJECT]", "[SNAPSHOT]");
SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
// Make the request
Snapshot response = subscriberClient.CreateSnapshot(name, subscription);
// End snippet
}
/// <summary>Snippet for CreateSnapshotAsync</summary>
public async Task CreateSnapshotAsync_RequestObject()
{
// Snippet: CreateSnapshotAsync(CreateSnapshotRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
CreateSnapshotRequest request = new CreateSnapshotRequest
{
SnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"),
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
};
// Make the request
Snapshot response = await subscriberClient.CreateSnapshotAsync(request);
// End snippet
}
/// <summary>Snippet for CreateSnapshot</summary>
public void CreateSnapshot_RequestObject()
{
// Snippet: CreateSnapshot(CreateSnapshotRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
CreateSnapshotRequest request = new CreateSnapshotRequest
{
SnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"),
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
};
// Make the request
Snapshot response = subscriberClient.CreateSnapshot(request);
// End snippet
}
/// <summary>Snippet for UpdateSnapshotAsync</summary>
public async Task UpdateSnapshotAsync_RequestObject()
{
// Snippet: UpdateSnapshotAsync(UpdateSnapshotRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
UpdateSnapshotRequest request = new UpdateSnapshotRequest
{
Snapshot = new Snapshot
{
ExpireTime = new Timestamp
{
Seconds = 123456L,
},
},
UpdateMask = new FieldMask
{
Paths = {
"expire_time",
},
},
};
// Make the request
Snapshot response = await subscriberClient.UpdateSnapshotAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateSnapshot</summary>
public void UpdateSnapshot_RequestObject()
{
// Snippet: UpdateSnapshot(UpdateSnapshotRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
UpdateSnapshotRequest request = new UpdateSnapshotRequest
{
Snapshot = new Snapshot
{
ExpireTime = new Timestamp
{
Seconds = 123456L,
},
},
UpdateMask = new FieldMask
{
Paths = {
"expire_time",
},
},
};
// Make the request
Snapshot response = subscriberClient.UpdateSnapshot(request);
// End snippet
}
/// <summary>Snippet for DeleteSnapshotAsync</summary>
public async Task DeleteSnapshotAsync()
{
// Snippet: DeleteSnapshotAsync(SnapshotName,CallSettings)
// Additional: DeleteSnapshotAsync(SnapshotName,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SnapshotName snapshot = new SnapshotName("[PROJECT]", "[SNAPSHOT]");
// Make the request
await subscriberClient.DeleteSnapshotAsync(snapshot);
// End snippet
}
/// <summary>Snippet for DeleteSnapshot</summary>
public void DeleteSnapshot()
{
// Snippet: DeleteSnapshot(SnapshotName,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SnapshotName snapshot = new SnapshotName("[PROJECT]", "[SNAPSHOT]");
// Make the request
subscriberClient.DeleteSnapshot(snapshot);
// End snippet
}
/// <summary>Snippet for DeleteSnapshotAsync</summary>
public async Task DeleteSnapshotAsync_RequestObject()
{
// Snippet: DeleteSnapshotAsync(DeleteSnapshotRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
SnapshotAsSnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"),
};
// Make the request
await subscriberClient.DeleteSnapshotAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteSnapshot</summary>
public void DeleteSnapshot_RequestObject()
{
// Snippet: DeleteSnapshot(DeleteSnapshotRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
SnapshotAsSnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"),
};
// Make the request
subscriberClient.DeleteSnapshot(request);
// End snippet
}
/// <summary>Snippet for SeekAsync</summary>
public async Task SeekAsync_RequestObject()
{
// Snippet: SeekAsync(SeekRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SeekRequest request = new SeekRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
};
// Make the request
SeekResponse response = await subscriberClient.SeekAsync(request);
// End snippet
}
/// <summary>Snippet for Seek</summary>
public void Seek_RequestObject()
{
// Snippet: Seek(SeekRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SeekRequest request = new SeekRequest
{
SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"),
};
// Make the request
SeekResponse response = subscriberClient.Seek(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string,Policy,CallSettings)
// Additional: SetIamPolicyAsync(string,Policy,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString();
Policy policy = new Policy();
// Make the request
Policy response = await subscriberClient.SetIamPolicyAsync(formattedResource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string,Policy,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString();
Policy policy = new Policy();
// Make the request
Policy response = subscriberClient.SetIamPolicy(formattedResource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync_RequestObject()
{
// Snippet: SetIamPolicyAsync(SetIamPolicyRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
SetIamPolicyRequest request = new SetIamPolicyRequest
{
Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(),
Policy = new Policy(),
};
// Make the request
Policy response = await subscriberClient.SetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy_RequestObject()
{
// Snippet: SetIamPolicy(SetIamPolicyRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
SetIamPolicyRequest request = new SetIamPolicyRequest
{
Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(),
Policy = new Policy(),
};
// Make the request
Policy response = subscriberClient.SetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string,CallSettings)
// Additional: GetIamPolicyAsync(string,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString();
// Make the request
Policy response = await subscriberClient.GetIamPolicyAsync(formattedResource);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString();
// Make the request
Policy response = subscriberClient.GetIamPolicy(formattedResource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync_RequestObject()
{
// Snippet: GetIamPolicyAsync(GetIamPolicyRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
GetIamPolicyRequest request = new GetIamPolicyRequest
{
Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(),
};
// Make the request
Policy response = await subscriberClient.GetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy_RequestObject()
{
// Snippet: GetIamPolicy(GetIamPolicyRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
GetIamPolicyRequest request = new GetIamPolicyRequest
{
Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(),
};
// Make the request
Policy response = subscriberClient.GetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string,IEnumerable<string>,CallSettings)
// Additional: TestIamPermissionsAsync(string,IEnumerable<string>,CancellationToken)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString();
IEnumerable<string> permissions = new List<string>();
// Make the request
TestIamPermissionsResponse response = await subscriberClient.TestIamPermissionsAsync(formattedResource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString();
IEnumerable<string> permissions = new List<string>();
// Make the request
TestIamPermissionsResponse response = subscriberClient.TestIamPermissions(formattedResource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync_RequestObject()
{
// Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = await SubscriberClient.CreateAsync();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(),
Permissions = { },
};
// Make the request
TestIamPermissionsResponse response = await subscriberClient.TestIamPermissionsAsync(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions_RequestObject()
{
// Snippet: TestIamPermissions(TestIamPermissionsRequest,CallSettings)
// Create client
SubscriberClient subscriberClient = SubscriberClient.Create();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(),
Permissions = { },
};
// Make the request
TestIamPermissionsResponse response = subscriberClient.TestIamPermissions(request);
// End snippet
}
}
}
| |
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 TestWebApiApp.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 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>ConversionValueRule</c> resource.</summary>
public sealed partial class ConversionValueRuleName : gax::IResourceName, sys::IEquatable<ConversionValueRuleName>
{
/// <summary>The possible contents of <see cref="ConversionValueRuleName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>
/// .
/// </summary>
CustomerConversionValueRule = 1,
}
private static gax::PathTemplate s_customerConversionValueRule = new gax::PathTemplate("customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}");
/// <summary>Creates a <see cref="ConversionValueRuleName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ConversionValueRuleName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ConversionValueRuleName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ConversionValueRuleName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ConversionValueRuleName"/> with the pattern
/// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleId">
/// The <c>ConversionValueRule</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="ConversionValueRuleName"/> constructed from the provided ids.
/// </returns>
public static ConversionValueRuleName FromCustomerConversionValueRule(string customerId, string conversionValueRuleId) =>
new ConversionValueRuleName(ResourceNameType.CustomerConversionValueRule, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionValueRuleId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleId, nameof(conversionValueRuleId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConversionValueRuleName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleId">
/// The <c>ConversionValueRule</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ConversionValueRuleName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>.
/// </returns>
public static string Format(string customerId, string conversionValueRuleId) =>
FormatCustomerConversionValueRule(customerId, conversionValueRuleId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConversionValueRuleName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleId">
/// The <c>ConversionValueRule</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ConversionValueRuleName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>.
/// </returns>
public static string FormatCustomerConversionValueRule(string customerId, string conversionValueRuleId) =>
s_customerConversionValueRule.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleId, nameof(conversionValueRuleId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ConversionValueRuleName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="conversionValueRuleName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ConversionValueRuleName"/> if successful.</returns>
public static ConversionValueRuleName Parse(string conversionValueRuleName) => Parse(conversionValueRuleName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ConversionValueRuleName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="conversionValueRuleName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ConversionValueRuleName"/> if successful.</returns>
public static ConversionValueRuleName Parse(string conversionValueRuleName, bool allowUnparsed) =>
TryParse(conversionValueRuleName, allowUnparsed, out ConversionValueRuleName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ConversionValueRuleName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="conversionValueRuleName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ConversionValueRuleName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string conversionValueRuleName, out ConversionValueRuleName result) =>
TryParse(conversionValueRuleName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ConversionValueRuleName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="conversionValueRuleName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ConversionValueRuleName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string conversionValueRuleName, bool allowUnparsed, out ConversionValueRuleName result)
{
gax::GaxPreconditions.CheckNotNull(conversionValueRuleName, nameof(conversionValueRuleName));
gax::TemplatedResourceName resourceName;
if (s_customerConversionValueRule.TryParseName(conversionValueRuleName, out resourceName))
{
result = FromCustomerConversionValueRule(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(conversionValueRuleName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ConversionValueRuleName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversionValueRuleId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ConversionValueRuleId = conversionValueRuleId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ConversionValueRuleName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleId">
/// The <c>ConversionValueRule</c> ID. Must not be <c>null</c> or empty.
/// </param>
public ConversionValueRuleName(string customerId, string conversionValueRuleId) : this(ResourceNameType.CustomerConversionValueRule, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionValueRuleId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleId, nameof(conversionValueRuleId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>ConversionValueRule</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string ConversionValueRuleId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerConversionValueRule: return s_customerConversionValueRule.Expand(CustomerId, ConversionValueRuleId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ConversionValueRuleName);
/// <inheritdoc/>
public bool Equals(ConversionValueRuleName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ConversionValueRuleName a, ConversionValueRuleName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ConversionValueRuleName a, ConversionValueRuleName b) => !(a == b);
}
public partial class ConversionValueRule
{
/// <summary>
/// <see cref="ConversionValueRuleName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal ConversionValueRuleName ResourceNameAsConversionValueRuleName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ConversionValueRuleName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CustomerName"/>-typed view over the <see cref="OwnerCustomer"/> resource name property.
/// </summary>
internal CustomerName OwnerCustomerAsCustomerName
{
get => string.IsNullOrEmpty(OwnerCustomer) ? null : CustomerName.Parse(OwnerCustomer, allowUnparsed: true);
set => OwnerCustomer = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using FluentAssertions;
using Xunit;
using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
namespace Microsoft.DotNet.Cli.Sln.Internal.Tests
{
public class GivenAnSlnFile : TestBase
{
private const string SolutionModified = @"
Microsoft Visual Studio Solution File, Format Version 14.00
# Visual Studio 16
VisualStudioVersion = 16.0.26006.2
MinimumVisualStudioVersion = 11.0.40219.1
Project(""{7072A694-548F-4CAE-A58F-12D257D5F486}"") = ""AppModified"", ""AppModified\AppModified.csproj"", ""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = TRUE
EndGlobalSection
EndGlobal
";
private const string SolutionWithAppAndLibProjects = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
Project(""{13B669BE-BB05-4DDF-9536-439F39A36129}"") = ""Lib"", ""..\Lib\Lib.csproj"", ""{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|x64.ActiveCfg = Debug|x64
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|x64.Build.0 = Debug|x64
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|x86.ActiveCfg = Debug|x86
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|x86.Build.0 = Debug|x86
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|Any CPU.Build.0 = Release|Any CPU
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|x64.ActiveCfg = Release|x64
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|x64.Build.0 = Release|x64
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|x86.ActiveCfg = Release|x86
{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
[Fact]
public void WhenGivenAValidSlnFileItReadsAndVerifiesContents()
{
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionWithAppAndLibProjects);
SlnFile slnFile = SlnFile.Read(tmpFile.Path);
slnFile.FormatVersion.Should().Be("12.00");
slnFile.ProductDescription.Should().Be("Visual Studio 15");
slnFile.VisualStudioVersion.Should().Be("15.0.26006.2");
slnFile.MinimumVisualStudioVersion.Should().Be("10.0.40219.1");
slnFile.BaseDirectory.Should().Be(Path.GetDirectoryName(tmpFile.Path));
slnFile.FullPath.Should().Be(tmpFile.Path);
slnFile.Projects.Count.Should().Be(2);
var project = slnFile.Projects[0];
project.Id.Should().Be("{7072A694-548F-4CAE-A58F-12D257D5F486}");
project.TypeGuid.Should().Be("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}");
project.Name.Should().Be("App");
project.FilePath.Should().Be(Path.Combine("App", "App.csproj"));
project = slnFile.Projects[1];
project.Id.Should().Be("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}");
project.TypeGuid.Should().Be("{13B669BE-BB05-4DDF-9536-439F39A36129}");
project.Name.Should().Be("Lib");
project.FilePath.Should().Be(Path.Combine("..", "Lib", "Lib.csproj"));
slnFile.SolutionConfigurationsSection.Count.Should().Be(6);
slnFile.SolutionConfigurationsSection
.GetValue("Debug|Any CPU", string.Empty)
.Should().Be("Debug|Any CPU");
slnFile.SolutionConfigurationsSection
.GetValue("Debug|x64", string.Empty)
.Should().Be("Debug|x64");
slnFile.SolutionConfigurationsSection
.GetValue("Debug|x86", string.Empty)
.Should().Be("Debug|x86");
slnFile.SolutionConfigurationsSection
.GetValue("Release|Any CPU", string.Empty)
.Should().Be("Release|Any CPU");
slnFile.SolutionConfigurationsSection
.GetValue("Release|x64", string.Empty)
.Should().Be("Release|x64");
slnFile.SolutionConfigurationsSection
.GetValue("Release|x86", string.Empty)
.Should().Be("Release|x86");
slnFile.ProjectConfigurationsSection.Count.Should().Be(2);
var projectConfigSection = slnFile
.ProjectConfigurationsSection
.GetPropertySet("{7072A694-548F-4CAE-A58F-12D257D5F486}");
projectConfigSection.Count.Should().Be(12);
projectConfigSection
.GetValue("Debug|Any CPU.ActiveCfg", string.Empty)
.Should().Be("Debug|Any CPU");
projectConfigSection
.GetValue("Debug|Any CPU.Build.0", string.Empty)
.Should().Be("Debug|Any CPU");
projectConfigSection
.GetValue("Debug|x64.ActiveCfg", string.Empty)
.Should().Be("Debug|x64");
projectConfigSection
.GetValue("Debug|x64.Build.0", string.Empty)
.Should().Be("Debug|x64");
projectConfigSection
.GetValue("Debug|x86.ActiveCfg", string.Empty)
.Should().Be("Debug|x86");
projectConfigSection
.GetValue("Debug|x86.Build.0", string.Empty)
.Should().Be("Debug|x86");
projectConfigSection
.GetValue("Release|Any CPU.ActiveCfg", string.Empty)
.Should().Be("Release|Any CPU");
projectConfigSection
.GetValue("Release|Any CPU.Build.0", string.Empty)
.Should().Be("Release|Any CPU");
projectConfigSection
.GetValue("Release|x64.ActiveCfg", string.Empty)
.Should().Be("Release|x64");
projectConfigSection
.GetValue("Release|x64.Build.0", string.Empty)
.Should().Be("Release|x64");
projectConfigSection
.GetValue("Release|x86.ActiveCfg", string.Empty)
.Should().Be("Release|x86");
projectConfigSection
.GetValue("Release|x86.Build.0", string.Empty)
.Should().Be("Release|x86");
projectConfigSection = slnFile
.ProjectConfigurationsSection
.GetPropertySet("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}");
projectConfigSection.Count.Should().Be(12);
projectConfigSection
.GetValue("Debug|Any CPU.ActiveCfg", string.Empty)
.Should().Be("Debug|Any CPU");
projectConfigSection
.GetValue("Debug|Any CPU.Build.0", string.Empty)
.Should().Be("Debug|Any CPU");
projectConfigSection
.GetValue("Debug|x64.ActiveCfg", string.Empty)
.Should().Be("Debug|x64");
projectConfigSection
.GetValue("Debug|x64.Build.0", string.Empty)
.Should().Be("Debug|x64");
projectConfigSection
.GetValue("Debug|x86.ActiveCfg", string.Empty)
.Should().Be("Debug|x86");
projectConfigSection
.GetValue("Debug|x86.Build.0", string.Empty)
.Should().Be("Debug|x86");
projectConfigSection
.GetValue("Release|Any CPU.ActiveCfg", string.Empty)
.Should().Be("Release|Any CPU");
projectConfigSection
.GetValue("Release|Any CPU.Build.0", string.Empty)
.Should().Be("Release|Any CPU");
projectConfigSection
.GetValue("Release|x64.ActiveCfg", string.Empty)
.Should().Be("Release|x64");
projectConfigSection
.GetValue("Release|x64.Build.0", string.Empty)
.Should().Be("Release|x64");
projectConfigSection
.GetValue("Release|x86.ActiveCfg", string.Empty)
.Should().Be("Release|x86");
projectConfigSection
.GetValue("Release|x86.Build.0", string.Empty)
.Should().Be("Release|x86");
slnFile.Sections.Count.Should().Be(3);
var solutionPropertiesSection = slnFile.Sections.GetSection("SolutionProperties");
solutionPropertiesSection.Properties.Count.Should().Be(1);
solutionPropertiesSection.Properties
.GetValue("HideSolutionNode", string.Empty)
.Should().Be("FALSE");
}
[Fact]
public void WhenGivenAValidSlnFileItModifiesSavesAndVerifiesContents()
{
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionWithAppAndLibProjects);
SlnFile slnFile = SlnFile.Read(tmpFile.Path);
slnFile.FormatVersion = "14.00";
slnFile.ProductDescription = "Visual Studio 16";
slnFile.VisualStudioVersion = "16.0.26006.2";
slnFile.MinimumVisualStudioVersion = "11.0.40219.1";
slnFile.Projects.Count.Should().Be(2);
var project = slnFile.Projects[0];
project.Id = "{9A19103F-16F7-4668-BE54-9A1E7A4F7556}";
project.TypeGuid = "{7072A694-548F-4CAE-A58F-12D257D5F486}";
project.Name = "AppModified";
project.FilePath = Path.Combine("AppModified", "AppModified.csproj");
slnFile.Projects.Remove(slnFile.Projects[1]);
slnFile.SolutionConfigurationsSection.Count.Should().Be(6);
slnFile.SolutionConfigurationsSection.Remove("Release|Any CPU");
slnFile.SolutionConfigurationsSection.Remove("Release|x64");
slnFile.SolutionConfigurationsSection.Remove("Release|x86");
slnFile.ProjectConfigurationsSection.Count.Should().Be(2);
var projectConfigSection = slnFile
.ProjectConfigurationsSection
.GetPropertySet("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}");
slnFile.ProjectConfigurationsSection.Remove(projectConfigSection);
slnFile.Sections.Count.Should().Be(3);
var solutionPropertiesSection = slnFile.Sections.GetSection("SolutionProperties");
solutionPropertiesSection.Properties.Count.Should().Be(1);
solutionPropertiesSection.Properties.SetValue("HideSolutionNode", "TRUE");
slnFile.Write();
File.ReadAllText(tmpFile.Path)
.Should().Be(SolutionModified);
}
[Theory]
[InlineData("Invalid Solution")]
[InlineData("Microsoft Visual Studio Solution File, Format Version ")]
public void WhenGivenASolutionWithMissingHeaderItThrows(string fileContents)
{
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(fileContents);
Action action = () =>
{
SlnFile.Read(tmpFile.Path);
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 1: File header is missing");
}
[Fact]
public void WhenGivenASolutionWithMultipleGlobalSectionsItThrows()
{
const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
EndGlobal
Global
EndGlobal
";
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionFile);
Action action = () =>
{
SlnFile.Read(tmpFile.Path);
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 5: Global section specified more than once");
}
[Fact]
public void WhenGivenASolutionWithGlobalSectionNotClosedItThrows()
{
const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
";
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionFile);
Action action = () =>
{
SlnFile.Read(tmpFile.Path);
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 3: Global section not closed");
}
[Fact]
public void WhenGivenASolutionWithProjectSectionNotClosedItThrows()
{
const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
";
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionFile);
Action action = () =>
{
SlnFile.Read(tmpFile.Path);
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 3: Project section not closed");
}
[Fact]
public void WhenGivenASolutionWithInvalidProjectSectionItThrows()
{
const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Project""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
";
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionFile);
Action action = () =>
{
SlnFile.Read(tmpFile.Path);
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 3: Project section is missing '(' when parsing the line starting at position 0");
}
[Fact]
public void WhenGivenASolutionWithInvalidSectionTypeItThrows()
{
const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
GlobalSection(SolutionConfigurationPlatforms) = thisIsUnknown
EndGlobalSection
EndGlobal
";
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionFile);
Action action = () =>
{
SlnFile.Read(tmpFile.Path);
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 4: Invalid section type: thisIsUnknown");
}
[Fact]
public void WhenGivenASolutionWithMissingSectionIdTypeItThrows()
{
const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
GlobalSection = preSolution
EndGlobalSection
EndGlobal
";
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionFile);
Action action = () =>
{
SlnFile.Read(tmpFile.Path);
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 4: Section id missing");
}
[Fact]
public void WhenGivenASolutionWithSectionNotClosedItThrows()
{
const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
EndGlobal
";
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionFile);
Action action = () =>
{
SlnFile.Read(tmpFile.Path);
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 6: Closing section tag not found");
}
[Fact]
public void WhenGivenASolutionWithInvalidPropertySetItThrows()
{
const string SolutionFile = @"
Microsoft Visual Studio Solution File, Format Version 12.00
Project(""{7072A694-548F-4CAE-A58F-12D257D5F486}"") = ""AppModified"", ""AppModified\AppModified.csproj"", ""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}""
EndProject
Global
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486} Debug|Any CPU ActiveCfg = Debug|Any CPU
EndGlobalSection
EndGlobal
";
var tmpFile = Temp.CreateFile();
tmpFile.WriteAllText(SolutionFile);
Action action = () =>
{
var slnFile = SlnFile.Read(tmpFile.Path);
if (slnFile.ProjectConfigurationsSection.Count == 0)
{
// Need to force loading of nested property sets
}
};
action.ShouldThrow<InvalidSolutionFormatException>()
.WithMessage("Invalid format in line 7: Property set is missing '.'");
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#define CONTRACTS_FULL
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;
using System.Runtime.InteropServices;
using System.Reflection;
namespace PreInference
{
class StraightLineTests
{
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(s != null);")]
public int StraightForwardNotNull(string s)
{
return s.Length;
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((x + 2) > 0);")]
[RegressionOutcome("Consider replacing the expression (x + 2) > 0 with an equivalent, yet not overflowing expression. Fix: x > (0 - 2)")]
public void Simplification1(int x)
{
int z = x + 1;
Contract.Assert(z + 1 > 0);
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(x > 0);")]
public void Simplification2(int x)
{
int z = x + 1;
Contract.Assert(z - 1 > 0);
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(x > 0);")]
public void Simplification3(int x)
{
int z = x - 1;
Contract.Assert(z + 1 > 0);
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((x - 2) > 0);")]
public void Simplification4(int x)
{
int z = x - 1;
Contract.Assert(z - 1 > 0);
}
[RegressionOutcome("Contract.Requires(arr != null);")]
[RegressionOutcome("Contract.Requires(2 < arr.Length);")]
[ClousotRegressionTest]
public void Redundant(byte[] arr)
{
arr[0] = 10;
arr[2] = 123;
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(arr != null);")]
[RegressionOutcome("Contract.Requires(0 <= k);")]
[RegressionOutcome("Contract.Requires((k + 2) < arr.Length);")]
public void Redundant(byte[] arr, int k)
{
arr[k + 0] = 10;
arr[k + 2] = 123;
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(arr != null);")]
[RegressionOutcome("Contract.Requires(0 <= k);")]
[RegressionOutcome("Contract.Requires((k + 2) < arr.Length);")]
[RegressionOutcome("Possible off-by one: did you mean indexing with k instead of k + 1?. Fix: k")]
public void RedundantWithPostfixIncrement(byte[] arr, int k)
{
arr[k] = 1;
var k1 = k + 1;
arr[k1] = 123;
var k2 = k1 + 1;
arr[k2] = 2;
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((k + 2) < s.Length);")]
public void RedundantWithPreFixIncrementOfParameter(int k, string[] s)
{
Contract.Requires(s != null);
Contract.Requires(k >= 0);
s[k] = "1";
s[++k] = "2;";
s[++k] = "3";
}
}
public class ControlFlowInference
{
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((x <= 0 || s != null));")]
public int Conditional(int x, string s)
{
if (x > 0)
{
return s.Length;
}
return x;
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(obj != null);")]
public void NotNull(int z, object obj)
{
if (z > 0)
obj.GetHashCode();
obj.GetType();
}
// we do not infer the precondition with this system as the propagations stops because of the local
// Also no text fix
// However we have a suggestion
[ClousotRegressionTest]
public int WithMethodCall(string s)
{
var b = Foo(s);
if (b)
{
return s.Length;
}
else
{
return s.Length + 1;
}
}
// no precondition to infer
[ClousotRegressionTest]
//[RegressionOutcome("Contract.Assume(tmp == 29);")] // we moved the some assume suggestions into codefixes
[RegressionOutcome("This condition should hold: tmp == 29. Add an assume, a postcondition to method DaysInMonth, or consider a different initialization. Fix: Add (after) Contract.Assume(tmp == 29);")]
public int Local(int z)
{
var tmp = DateTime.DaysInMonth(2012, 12);
Contract.Assert(tmp == 29);
return tmp;
}
// infer z == 29: the guard is implied by the precondition
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(z == 29);")]
public int Local2(int z, int k)
{
Contract.Requires(k >= 0);
if (k >= -12)
{
Contract.Assert(z == 29);
}
return z;
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(!(b));")] // if b, the we get an error
[RegressionOutcome("Contract.Requires(x > 0);")] // if x <= 0, we get an error no matter what
[RegressionOutcome("Consider initializing x with a value other than -123 (e.g., satisfying x > 0). Fix: 1;")]
public int Branch(int x, bool b)
{
if (b)
{
x = -123;
}
Contract.Assert(x > 0);
return x;
}
// nothing to infer
[ClousotRegressionTest]
[RegressionOutcome("Consider initializing x with a value other than 12 (e.g., satisfying x < 0). Fix: -1;")]
public void Branch2(int x)
{
if (Foo("ciao"))
{
x = -12;
}
else
{
x = 12;
}
Contract.Assert(x < 0);
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(s != null);")]
public void Branch3(int x, ref int z, string s)
{
// we need the join here
if (x > 0)
{
z = 11;
}
else
{
z = 122;
}
Contract.Assert(s != null);
}
// We need a join here in which we get rid of the path
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(s != null);")]
public void Branch4(int x, ref int z, string s)
{
if (x > 0)
{
z = 11;
}
else
{
z = 122;
}
if (x % 2 == 0)
{
z += 1;
}
else
{
z -= 1;
}
Contract.Assert(s != null);
}
[ClousotRegressionTest]
// We should not infer "Contract.Requires(((x > 0 || (x % 2) != 0) || s != null));" because this means that simplification failed
[RegressionOutcome("Contract.Requires(((x % 2) != 0 || s != null));")]
public void Branch5(int x, ref int z, string s)
{
if (x > 0)
{
z = 11;
}
else
{
z = 122;
}
if (x % 2 == 0)
{
z += 1;
}
else
{
return;
}
Contract.Assert(s != null);
}
public bool Foo(string s)
{
return s != null;
}
[ClousotRegressionTest]
public void Test_RequiresAnInt_Positive()
{
RequiresAnInt(12);
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(!((" + "@\"12\"" +" as System.Int32)));")]
public void Test_RequiresAnInt_Negative()
{
RequiresAnInt("12");
}
[ClousotRegressionTest]
// We do not suggest anymore requires from "throw "-> "assert false" transformations
// [RegressionOutcome("Contract.Requires(!((s as System.Int32)));")]
public void RequiresAnInt(object s)
{
if ((s is Int32))
{
throw new ArgumentException();
}
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((i < 0 || j > 0));")]
public int Mixed(int i, int j)
{
if (i < 0)
throw new ArgumentOutOfRangeException("should be >= 0!!!");
Contract.Assert(j > 0);
return i * 2;
}
}
public class PreInferenceWithLoops
{
// infer input <= 0 ==> input == 0
// (equivalent to input >= 0)
// Cannot be inferred with precondition over all the paths
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(input >= 0);")]
public void Loop(int input)
{
var j = 0;
for (; j < input; j++)
{
}
Contract.Assert(input == j);
}
// infer x != 0 ==> x > 0
// Cannot be inferred with precondition over all the paths
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(x >= 0);")]
public void Loop2(int x)
{
while (x != 0)
{
Contract.Assert(x > 0);
x--;
}
}
// infer strings.Length > 0
// The other precondition is \exists j \in [0, strings.Length). strings[j] == null, but it is way out of reach at the moment
// Cannot be inferred with precondition over all the paths
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(0 < strings.Length);")]
public int Loop3(string[] strings)
{
Contract.Requires(strings != null);
int i = 0;
while (strings[i] != null)
{
i++;
}
return i;
}
[ClousotRegressionTest]
// [RegressionOutcome("Contract.Requires((0 >= m1 || 0 < f));")] // 3/20/2014: Now we infer a better precondition
[RegressionOutcome("Contract.Requires((0 >= m1 || m1 <= f));")]
public void Loop4(int m1, int f)
{
int i = 0;
while (i < m1)
{
Contract.Assert(i < f);
i++;
}
}
[ClousotRegressionTest]
// [RegressionOutcome("Contract.Requires((0 >= m1 || 0 < f));")] // Fixed
[RegressionOutcome("Contract.Requires((0 >= m1 || m1 <= f));")]
public void Loop4WithPreconditionNotStrongEnough(int m1, int f)
{
Contract.Requires(m1 >= 0); // as we may have the equality, then we may never execute the loop
int i = 0;
while (i < m1)
{
Contract.Assert(i < f);
i++;
}
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(m1 <= f);")]
public void Loop4WithPrecondition(int m1, int f)
{
Contract.Requires(m1 > 0); // this simplifies the precondition above, as we know now we always execute the loop at least once
int i = 0;
while (i < m1)
{
Contract.Assert(i < f);
i++;
}
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(strs != null);")]
[RegressionOutcome("Contract.Requires(0 <= start);")]
[RegressionOutcome("Contract.Requires(start < strs.Length);")]
public int SearchZero(string[] strs, int start)
{
while (strs[start] != null)
{
start++;
}
return start;
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(x == 12);")]
public void AfterWhileLoop_ConditionAlwaysTrue(int x, int z)
{
Contract.Requires(z >= 0);
while (z > 0)
{
z--;
}
// here z == 0;
// uses this information to drop the z <= 0 antecendent
if (z == 0)
{
Contract.Assert(x == 12);
}
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(x == 12);")]
public void AfterWhileLoop_ConditionAlwaysTrueWithStrongerPrecondition(int x, int z)
{
Contract.Requires(z > 0);
while (z > 0)
{
z--;
}
// here z == 0;
if (z == 0)
{
Contract.Assert(x == 12);
}
}
// infers x <0 || y > 0
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((x < 0 || y > 0));")]
public void SrivastavaGulwaniPLDI09(int x, int y)
{
while (x < 0)
{
x = x + y;
y++;
}
Contract.Assert(y > 0);
}
}
public class SomeClass
{
public string[] SomeString;
}
public class PreconditionOrder
{
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(((s == null || s.SomeString == null) || 0 <= index));")]
[RegressionOutcome("Contract.Requires(((s == null || s.SomeString == null) || index < s.SomeString.Length));")]
[RegressionOutcome("Consider strengthening the null check. Fix: Add && index < s.SomeString.Length")]
public static string SomeMethod(SomeClass s, int index)
{
if (s != null)
{
if (s.SomeString != null)
return s.SomeString[index];
}
return null;
}
}
}
namespace mscorlib
{
public class MyAppDomainSetup
{
public string PrivateBinPath;
public object DeveloperPath;
public string[] Value
{
get
{
return new string[0x12];
}
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((blob == null || 0 < blob.Length));")]
[RegressionOutcome("Consider strengthening the null check. Fix: Add && 0 < blob.Length")]
private static object Deserialize(byte[] blob)
{
if (blob == null)
{
return null;
}
if (blob[0] == 0)
{
return 1;
}
return null;
}
internal void SetupFusionContext(IntPtr fusionContext, MyAppDomainSetup oldInfo)
{
throw new NotImplementedException();
}
}
public class AppDomain
{
// Here we had 2 bugs in the pretty printing:
// 1. infer: info != null && info != null && info != null ...
// 2. infer (info != null && (info.DeveloperPath != null ==> info != null)
// We should only infer info != null
// Note: we do not analyze this.Value in the regression run, this is why we get the messages
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(info != null);")]
// [RegressionOutcome("Contract.Requires((oldInfo != null || info.Value != null));")]
// [RegressionOutcome("Contract.Requires((oldInfo != null || 0 < info.Value.Length));")]
// [RegressionOutcome("Contract.Requires((oldInfo != null || 5 < info.Value.Length));")]
// [RegressionOutcome("Contract.Assume(info.Value != null);")] // We also infer this assume - we moved the inference of assume to the codefixes
// [RegressionOutcome("This condition should hold: info.Value != null. Add an assume, a postcondition, or consider a different initialization. Fix: Add (after) Contract.Assume(info.Value != null);")]
[RegressionOutcome("Contract.Requires((oldInfo != null || 5 < ((mscorlib.MyAppDomainSetup)info).Value.Length));")]
[RegressionOutcome("Contract.Requires((oldInfo != null || 0 < ((mscorlib.MyAppDomainSetup)info).Value.Length));")]
[RegressionOutcome("Contract.Requires((oldInfo != null || ((mscorlib.MyAppDomainSetup)info).Value != null));")]
//[RegressionOutcome("This condition should hold: ((mscorlib.MyAppDomainSetup)info).Value != null. Add an assume, a postcondition, or consider a different initialization. Fix: Add (after) Contract.Assume(((mscorlib.MyAppDomainSetup)info).Value != null);")]
[RegressionOutcome("This condition should hold: ((mscorlib.MyAppDomainSetup)info).Value != null. Add an assume, a postcondition to method get_Value, or consider a different initialization. Fix: Add (after) Contract.Assume(((mscorlib.MyAppDomainSetup)info).Value != null);")]
// When we infer a test strengthening, we check that at least one of the vars in the fix is in the condition. We do not extend this for accesspaths
//[RegressionOutcome("Consider strengthening the guard. Fix: Add && 1 < info.Value.Length")]
[RegressionOutcome("Possible off-by one: did you mean indexing with 0 instead of 1?. Fix: 0")]
private void SetupFusionStore(MyAppDomainSetup info, MyAppDomainSetup oldInfo)
{
if (oldInfo == null)
{
if ((info.Value[0] == null) || (info.Value[1] == null))
{
// dummy
}
if (info.Value[5] == null)
{
info.PrivateBinPath = RuntimeEnvironment.GetRuntimeDirectory();
}
if (info.DeveloperPath == null)
{
info.DeveloperPath = RuntimeEnvironment.GetRuntimeDirectory();
}
}
IntPtr fusionContext = this.GetFusionContext();
info.SetupFusionContext(fusionContext, oldInfo);
}
private IntPtr GetFusionContext()
{
throw new NotImplementedException();
}
}
public class LinkedStructure
{
public bool HasElementType;
public LinkedStructure next;
private LinkedStructure GetElementType()
{
return next;
}
// nothing to infer
[ClousotRegressionTest]
// [RegressionOutcome("Contract.Assume((elementType.GetElementType()) != null);")] // we moved the some assume suggestions into codefixes
// Here we build the left argument by ourselves, as the heap analysis does not have a name for it
[RegressionOutcome("This condition should hold: elementType.GetElementType() != null. Add an assume, a postcondition to method mscorlib.LinkedStructure.GetElementType(), or consider a different initialization. Fix: Add (after) Contract.Assume(elementType.GetElementType() != null);")]
internal string SigToString()
{
var elementType = this;
while (elementType.HasElementType)
{
elementType = elementType.GetElementType();
}
return elementType.ToString();
}
}
public class Guid
{
// Here we do not want to generate the trivial precondition hex || !hex || guidChars.Length > ...
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((!(hex) || guidChars != null));")]
[RegressionOutcome("Contract.Requires((!(hex) || 0 <= offset));")]
[RegressionOutcome("Contract.Requires((!(hex) || offset < guidChars.Length));")]
[RegressionOutcome("Contract.Requires((!(hex) || (offset + 1) < guidChars.Length));")]
private static int HexsToCharsReduced(char[] guidChars, int offset, int a, int b, bool hex)
{
if (hex)
{
guidChars[offset++] = 'x';
}
if (hex)
{
guidChars[offset++] = ',';
}
return offset;
}
private static char HexToChar(int a)
{
a &= 15;
return ((a > 9) ? ((char)((a - 10) + 0x61)) : ((char)(a + 0x30)));
}
}
public class ActivationAttributeStack
{
public object[] activationAttributes;
public object[] activationTypes;
public int freeIndex; /* made the field public to have the precondition inference working */
// it is ok not to infer a precondition on this.activationAttributes, as we do not have boxed expressions for array loads (which appears in the test below)
[ClousotRegressionTest]
#if CLOUSOT2
[RegressionOutcome("Contract.Requires((this.freeIndex == 0 || this.activationTypes != null));")]
[RegressionOutcome("Contract.Requires((this.freeIndex == 0 || 0 <= (this.freeIndex - 1)));")]
[RegressionOutcome("Contract.Requires((this.freeIndex == 0 || (this.freeIndex - 1) < this.activationTypes.Length));")]
#else
[RegressionOutcome("Contract.Requires((!(this.freeIndex) || this.activationTypes != null));")]
[RegressionOutcome("Contract.Requires((!(this.freeIndex) || 0 <= (this.freeIndex - 1)));")]
[RegressionOutcome("Contract.Requires((!(this.freeIndex) || (this.freeIndex - 1) < this.activationTypes.Length));")]
// we infer !(this.freeIndex) instead of (this.freeIndex == 0) because we have some issues with types
#endif
[RegressionOutcome("Consider strengthening the guard. Fix: Add && (this.freeIndex - 1) < this.activationAttributes.Length")]
internal void Pop(Type typ)
{
#pragma warning disable 252
if ((this.freeIndex != 0) && (this.activationTypes[this.freeIndex - 1] == typ))
{
this.freeIndex--;
this.activationTypes[this.freeIndex] = null;
this.activationAttributes[this.freeIndex] = null;
#pragma warning restore 252
}
}
}
public class CustomAttributeData
{
public object m_namedArgs;
public CustomAttributeEncoding[] m_namedParams;
public MemberInfo[] m_members;
public Type m_scope;
// Nothing should be inferred as the assertion depends on a quantified property over the array m_namedParams
[ClousotRegressionTest]
public virtual IList<object> get_NamedArguments()
{
if (this.m_namedArgs == null)
{
if (this.m_namedParams == null)
{
return null;
}
int index = 0;
int num4 = 0;
while (index < this.m_namedParams.Length)
{
if (this.m_namedParams[index] != CustomAttributeEncoding.Undefined)
{
Contract.Assert(this.m_members != null); // Cannot prove it
num4++;
}
index++;
}
}
return null;
}
public enum CustomAttributeEncoding
{
Array = 29,
Boolean = 2,
Byte = 5,
Char = 3,
Double = 13,
Enum = 85,
Field = 83,
Float = 12,
Int16 = 6,
Int32 = 8,
Int64 = 10,
Object = 81,
Property = 84,
SByte = 4,
String = 14,
Type = 80,
UInt16 = 7,
UInt32 = 9,
UInt64 = 11,
Undefined = 0
}
}
public class SimplificationOfPremises
{
public int m_RelocFixupCount;
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(0 <= this.m_RelocFixupCount);")]
internal int[] GetTokenFixups()
{
if (this.m_RelocFixupCount == 0)
{
return null;
}
int[] destinationArray = new int[this.m_RelocFixupCount];
return destinationArray;
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(z >= 0);")]
[RegressionOutcome("Consider replacing z < 0. Fix: 0 <= z")]
public int[] WrongArrayInit(int z)
{
// we were not simplifying the premise
if (z < 0)
{
return new int[z];
}
return null;
}
}
public class InferredDisjunction
{
// Nothing to complain, precondition is proven
[ClousotRegressionTest]
public void CallFoo()
{
Foo(null, -1);
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((obj == null || z > 0));")]
public void Foo(object obj, int z)
{
if (obj != null)
{
Contract.Assert(z > 0);
}
}
}
public class OverflowTesting
{
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(elements != null);")]
[RegressionOutcome("Contract.Requires((nextFree != elements.Length || 0 <= (elements.Length * 2 + 1)));")]
public void Add(int[] elements, int nextFree, int x)
{
Contract.Requires(0 <= nextFree);
Contract.Requires(nextFree <= elements.Length);
if (nextFree == elements.Length)
{
var tmp = new int[nextFree * 2 + 1]; // This may overflow and get negative. We suggest a precondition for that
Array.Copy(elements, tmp, elements.Length);
elements = tmp;
}
elements[nextFree] = x;
nextFree++;
}
}
public class MoreComplexInference
{
[ClousotRegressionTest]
// [RegressionOutcome("Contract.Requires((length + offset) <= str.Length);")] // Now we have a better requires
// This is wrong!!! We should not correct the preconditions for the callers
//[RegressionOutcome("Did you mean i <= str.Length instead of i < str.Length?. Fix: i <= str.Length")]
[RegressionOutcome("Contract.Requires((offset >= (length + offset) || (length + offset) <= str.Length));")]
[RegressionOutcome("Consider adding the assumption (length + offset) <= str.Length. Fix: Add Contract.Assume((length + offset) <= str.Length);")]
#if CLOUSOT2
[RegressionOutcome("This condition should hold: i < str.Length. Add an assume, a postcondition to method System.String.Length.get(), or consider a different initialization. Fix: Add (after) Contract.Assume(i < str.Length);")]
[RegressionOutcome("This condition should hold: (length + offset) <= str.Length. Add an assume, a postcondition to method System.String.Length.get(), or consider a different initialization. Fix: Add (after) Contract.Assume((length + offset) <= str.Length);")]
#else
[RegressionOutcome("This condition should hold: i < str.Length. Add an assume, a postcondition to method System.String.get_Length, or consider a different initialization. Fix: Add (after) Contract.Assume(i < str.Length);")]
[RegressionOutcome("This condition should hold: (length + offset) <= str.Length. Add an assume, a postcondition to method System.String.get_Length, or consider a different initialization. Fix: Add (after) Contract.Assume((length + offset) <= str.Length);")]
#endif
public static int GetChar(string str, int offset, int length)
{
Contract.Requires(str != null);
Contract.Requires(offset >= 0);
Contract.Requires(length >= 0);
Contract.Requires(length < str.Length);
Contract.Requires(offset < str.Length);
int val = 0;
for (int i = offset; i < length + offset; i++)
{
char c = str[i]; // Method call, not removed by the compiler
}
return val;
}
}
public class False
{
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(x != null);")]
[RegressionOutcome("Contract.Requires(y >= 0);")]
[RegressionOutcome("Contract.Requires(z > y);")]
public void Foo(object x, int y, int z)
{
if(x == null) // x != null
Contract.Assert(false);
if(y < 0) // infer: x == null || y >= 0 simplified to y >= 0
Contract.Assert(false);
if(z <= y) // infer: x == null || y < 0 || z > y simplified to z > y
Contract.Assert(false);
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(capacity >= 0);")]
[RegressionOutcome("Contract.Requires(length >= 0);")]
[RegressionOutcome("Contract.Requires(startIndex >= 0);")]
[RegressionOutcome("Contract.Requires((value == null || startIndex <= (value.Length - length)));")]
[RegressionOutcome("Consider adding the assumption startIndex <= (value.Length - length). Fix: Add Contract.Assume(startIndex <= (value.Length - length));")]
#if CLOUSOT2
[RegressionOutcome("This condition should hold: startIndex <= (value.Length - length). Add an assume, a postcondition to method System.String.Length.get(), or consider a different initialization. Fix: Add (after) Contract.Assume(startIndex <= (value.Length - length));")]
#else
[RegressionOutcome("This condition should hold: startIndex <= (value.Length - length). Add an assume, a postcondition to method System.String.get_Length, or consider a different initialization. Fix: Add (after) Contract.Assume(startIndex <= (value.Length - length));")]
#endif
public static void StringBuilderSmallRepro(string value, int startIndex, int length, int capacity)
{
if (capacity < 0)
{
Contract.Assert(false);
}
if (length < 0)
{
Contract.Assert(false);
}
if (startIndex < 0)
{
Contract.Assert(false);
}
if (value == null)
{
value = string.Empty;
}
if (startIndex > (value.Length - length))
{
Contract.Assert(false);
}
}
}
}
namespace ReplaceExpressionsByMoreVisibleGetters
{
public class PublicGetterRepro
{
private int a, b;
public PublicGetterRepro(int a, int b)
{
this.a = a;
this.b = b;
}
[ClousotRegressionTest]
public int Length
{
get
{
Contract.Ensures(Contract.Result<int>() == a + b);
return a + b;
}
}
[ClousotRegressionTest]
// We do not infer it anymore
//[RegressionOutcome("Contract.Requires(i <= this.Length);")]
#if CLOUSOT2
[RegressionOutcome("This condition should hold: i <= this.Length. Add an assume, a postcondition to method ReplaceExpressionsByMoreVisibleGetters.PublicGetterRepro.Length.get(), or consider a different initialization. Fix: Add (after) Contract.Assume(i <= this.Length);")]
#else
[RegressionOutcome("This condition should hold: i <= this.Length. Add an assume, a postcondition to method ReplaceExpressionsByMoreVisibleGetters.PublicGetterRepro.get_Length, or consider a different initialization. Fix: Add (after) Contract.Assume(i <= this.Length);")]
#endif
public int Precondition(int i)
{
// we should infer i <= this.Length, instead of i <= a + b
if (i > this.Length)
{
throw new ArgumentOutOfRangeException();
}
return i + 1;
}
}
}
namespace UserRepro
{
public class RobAshton
{
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(((a % b) == 0 || a != 0));")]
[RegressionOutcome("Contract.Requires((a != Int32.MinValue || b != -1));")]
[RegressionOutcome("Contract.Requires(((a % b) == 0 || (b != Int32.MinValue || a != -1)));")]
private static bool AreBothWaysDivisibleBy2(int a, int b)
{
Contract.Requires(b != 0);
return a % b == 0 || b % a == 0;
}
}
public class Maf
{
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(((t as System.Collections.IEnumerable) != null || tabs >= 0));")]
[RegressionOutcome("Contract.Requires((!((t as System.String)) || tabs >= 0));")]
public void TestInference(object t, int tabs)
{
var asEnumerable = t as IEnumerable;
if (asEnumerable != null && !(t is string))
{
// do nothing
}
else // asNumerable == null || t is string
{
Contract.Assert(tabs >= 0);
}
}
}
}
namespace Shuvendu
{
class Program
{
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(0 <= x);")]
[RegressionOutcome("Contract.Requires(((x <= 0 || x - 1 != t) || 1 == x));")]
public void Foo(int x, int t)
{
var i = x;
var j = 0;
while (i > 0)
{
//Contract.Assert(i + j == x);
i--; j++;
if (i == t)
break;
}
Contract.Assert(j == x);
}
}
}
namespace BugRepro
{
public class Reactor
{
public enum State { On, Off}
public State state;
public Reactor()
{
this.state = State.Off;
}
public void turnReactorOn()
{
Contract.Requires(this.state == State.Off);
Contract.Ensures(this.state == State.On);
this.state = State.On;
}
public void SCRAM()
{
Contract.Requires(this.state == State.On);
Contract.Ensures(this.state == State.Off);
this.state = State.Off;
}
}
public class Tmp
{
public readonly Reactor r = new Reactor();
public Reactor.State state;
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires((!(restart) || !(wt)));")]
[RegressionOutcome("Contract.Requires((restart || wt));")]
[RegressionOutcome("Consider initializing this.state with a value other than 1 (e.g., satisfying this.state == 0). Fix: 0;")]
[RegressionOutcome("Consider initializing this.state with a value other than 0 (e.g., satisfying this.state == 1). Fix: 1;")]
public void SimpleTest(bool wt, bool restart)
{
Contract.Requires(this.state == Reactor.State.Off);
this.state = Reactor.State.On;
if (wt)
{
Contract.Assert(this.state == Reactor.State.On);
this.state = Reactor.State.Off;
}
if (restart)
{
Contract.Assert(this.state == Reactor.State.On);
this.state = Reactor.State.Off;
}
Contract.Assert(this.state== Reactor.State.Off);
}
[ClousotRegressionTest]
[RegressionOutcome("Contract.Requires(this.r != null);")]
[RegressionOutcome("Contract.Requires((!(restart) || !(wt)));")]
[RegressionOutcome("Contract.Requires((restart || wt));")]
[RegressionOutcome("Consider initializing this.r.state with a value other than 0 (e.g., satisfying this.r.state == 1). Fix: 1;")]
public void MoreComplexTest(bool wt, bool restart)
{
Contract.Requires(this.r.state == Reactor.State.Off);
this.r.turnReactorOn();
if(wt)
{
this.r.SCRAM();
}
if(restart)
{
this.r.SCRAM();
}
this.r.turnReactorOn();
this.r.SCRAM();
}
}
}
| |
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Voyage.Terraingine.DataCore;
namespace Voyage.Terraingine.Snowfall
{
/// <summary>
/// Class for applying a snowfall generator to a TerrainPage.
/// </summary>
public class Driver : Voyage.Terraingine.PlugIn
{
#region Data Members
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button btnRun;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.NumericUpDown numLevel;
private System.Windows.Forms.NumericUpDown numBlend;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
#endregion
#region Properties
/// <summary>
/// Gets the TerrainPage used.
/// </summary>
public TerrainPage TerrainPage
{
get { return _page; }
}
#endregion
#region Methods
/// <summary>
/// Creates a snowfall generator form.
/// </summary>
public Driver()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.CenterToParent();
base.InitializeBase();
_name = "Snowfall";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Runs the plug-in.
/// </summary>
public override void Run()
{
if ( _page != null )
{
numLevel.Maximum = Convert.ToDecimal( _page.MaximumVertexHeight );
numBlend.Maximum = Convert.ToDecimal( _page.MaximumVertexHeight );
numLevel.Value = Convert.ToDecimal( _page.MaximumVertexHeight / 2f );
if ( _page.TerrainPatch.GetTexture() != null )
ShowDialog( _owner );
else
MessageBox.Show( "No texture is currently selected", "Cannot Perform Operation",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
}
}
/// <summary>
/// Applies the snowfall generator to the TerrainPage.
/// </summary>
/// <param name="level">The snow level (elevation).</param>
/// <param name="blend">The snow blending distance.</param>
private void CreateSnow( float level, float blend )
{
DataCore.Texture tex = _page.TerrainPatch.GetTexture();
DataCore.Texture newTex = new Voyage.Terraingine.DataCore.Texture();
Bitmap image = new Bitmap( 128, 128, System.Drawing.Imaging.PixelFormat.Format32bppArgb );
float xScale = _page.TerrainPatch.Width / image.Width;
float yScale = _page.TerrainPatch.Height / image.Height;
string filename;
Vector2 origin;
Vector3 point;
int v1, v2, v3;
float alpha;
int fileCount = -1;
for ( int j = 0; j < image.Height; j++ )
{
for ( int i = 0; i < image.Width; i++ )
{
origin = new Vector2( (float) i * xScale, (float) j * yScale );
_page.GetPlane( origin, out v1, out v2, out v3, out point );
if ( point.Y >= level )
{
if ( point.Y >= level + blend )
image.SetPixel( i, j, Color.FromArgb( 0, Color.White ) );
else
{
alpha = 255f - ( point.Y - level ) / blend * 255f;
image.SetPixel( i, j, Color.FromArgb( (int) alpha, Color.White ) );
}
}
else
image.SetPixel( i, j, Color.FromArgb( 255, Color.White ) );
}
}
do
{
fileCount++;
filename = Path.GetDirectoryName( tex.FileName ) + "\\" +
Path.GetFileNameWithoutExtension( tex.FileName ) + "_snowfall" + fileCount + ".bmp";
} while ( File.Exists( filename ) );
image.Save( filename, System.Drawing.Imaging.ImageFormat.Bmp );
newTex.FileName = filename;
newTex.Name = "Snowfall";
newTex.Operation = TextureOperation.BlendTextureAlpha;
newTex.OperationText = "Use Texture Alpha";
_page.TerrainPatch.AddTexture( newTex );
_textures = _page.TerrainPatch.Textures;
}
/// <summary>
/// Runs the snowfall generator.
/// </summary>
private void btnRun_Click(object sender, System.EventArgs e)
{
float level = ( float ) numLevel.Value;
float blend = ( float ) numBlend.Value;
CreateSnow( level, blend );
_success = true;
_modifiedTextures = true;
this.Close();
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.numLevel = new System.Windows.Forms.NumericUpDown();
this.numBlend = new System.Windows.Forms.NumericUpDown();
this.btnRun = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.numLevel)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numBlend)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Snow Level:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 32);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(100, 16);
this.label2.TabIndex = 1;
this.label2.Text = "Blend Distance:";
//
// numLevel
//
this.numLevel.DecimalPlaces = 3;
this.numLevel.Increment = new System.Decimal(new int[] {
1,
0,
0,
196608});
this.numLevel.Location = new System.Drawing.Point(112, 8);
this.numLevel.Maximum = new System.Decimal(new int[] {
1,
0,
0,
0});
this.numLevel.Name = "numLevel";
this.numLevel.Size = new System.Drawing.Size(64, 20);
this.numLevel.TabIndex = 2;
//
// numBlend
//
this.numBlend.DecimalPlaces = 3;
this.numBlend.Increment = new System.Decimal(new int[] {
1,
0,
0,
196608});
this.numBlend.Location = new System.Drawing.Point(112, 32);
this.numBlend.Maximum = new System.Decimal(new int[] {
1,
0,
0,
0});
this.numBlend.Name = "numBlend";
this.numBlend.Size = new System.Drawing.Size(64, 20);
this.numBlend.TabIndex = 3;
this.numBlend.Value = new System.Decimal(new int[] {
1,
0,
0,
65536});
//
// btnRun
//
this.btnRun.Location = new System.Drawing.Point(8, 64);
this.btnRun.Name = "btnRun";
this.btnRun.TabIndex = 6;
this.btnRun.Text = "Run";
this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(112, 64);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 7;
this.btnCancel.Text = "Cancel";
//
// Driver
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(200, 96);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnRun);
this.Controls.Add(this.numBlend);
this.Controls.Add(this.numLevel);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Location = new System.Drawing.Point(0, 0);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Driver";
this.ShowInTaskbar = false;
this.Text = "Snowfall Emulator";
((System.ComponentModel.ISupportInitialize)(this.numLevel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numBlend)).EndInit();
this.ResumeLayout(false);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace Medo.Security.Cryptography.PasswordSafe {
/// <summary>
/// Entry.
/// </summary>
public class Entry {
/// <summary>
/// Creates a new instance.
/// </summary>
public Entry()
: this(new Record[] {
new Record(RecordType.Uuid, Guid.NewGuid().ToByteArray()),
new Record(RecordType.Title, new byte[0]),
new Record(RecordType.Password, new byte[0])
}) {
}
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="title">Title.</param>
public Entry(string title) : this() {
Title = title;
}
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="group">Group.</param>
/// <param name="title">Title.</param>
public Entry(GroupPath group, string title) : this() {
Group = group;
Title = title;
}
internal Entry(ICollection<Record> records) {
Records = new RecordCollection(this, records);
}
internal EntryCollection Owner { get; set; }
/// <summary>
/// Used to mark document as changed.
/// </summary>
protected void MarkAsChanged() {
if (Owner != null) { Owner.MarkAsChanged(); }
}
/// <summary>
/// Gets/sets UUID.
/// </summary>
public Guid Uuid {
get { return Records.Contains(RecordType.Uuid) ? Records[RecordType.Uuid].Uuid : Guid.Empty; }
set { Records[RecordType.Uuid].Uuid = value; }
}
/// <summary>
/// Gets/sets group.
/// </summary>
public GroupPath Group {
get { return Records.Contains(RecordType.Group) ? Records[RecordType.Group].Text : ""; }
set { Records[RecordType.Group].Text = value; }
}
/// <summary>
/// Gets/sets title.
/// </summary>
public string Title {
get { return Records.Contains(RecordType.Title) ? Records[RecordType.Title].Text : ""; }
set { Records[RecordType.Title].Text = value; }
}
/// <summary>
/// Gets/sets user name.
/// </summary>
public string UserName {
get { return Records.Contains(RecordType.UserName) ? Records[RecordType.UserName].Text : ""; }
set { Records[RecordType.UserName].Text = value; }
}
/// <summary>
/// Gets/sets notes.
/// </summary>
public string Notes {
get { return Records.Contains(RecordType.Notes) ? Records[RecordType.Notes].Text : ""; }
set { Records[RecordType.Notes].Text = value; }
}
/// <summary>
/// Gets/sets password.
/// </summary>
public string Password {
get { return Records.Contains(RecordType.Password) ? Records[RecordType.Password].Text : ""; }
set { Records[RecordType.Password].Text = value; }
}
/// <summary>
/// Gets/sets creation time.
/// </summary>
public DateTime CreationTime {
get { return Records.Contains(RecordType.CreationTime) ? Records[RecordType.CreationTime].Time : DateTime.MinValue; }
set { Records[RecordType.CreationTime].Time = value; }
}
/// <summary>
/// Gets/sets password modification time.
/// </summary>
public DateTime PasswordModificationTime {
get { return Records.Contains(RecordType.PasswordModificationTime) ? Records[RecordType.PasswordModificationTime].Time : DateTime.MinValue; }
set { Records[RecordType.PasswordModificationTime].Time = value; }
}
/// <summary>
/// Gets/sets last access time.
/// </summary>
public DateTime LastAccessTime {
get { return Records.Contains(RecordType.LastAccessTime) ? Records[RecordType.LastAccessTime].Time : DateTime.MinValue; }
set { Records[RecordType.LastAccessTime].Time = value; }
}
/// <summary>
/// Gets/sets password expiry time.
/// </summary>
public DateTime PasswordExpiryTime {
get { return Records.Contains(RecordType.PasswordExpiryTime) ? Records[RecordType.PasswordExpiryTime].Time : DateTime.MinValue; }
set { Records[RecordType.PasswordExpiryTime].Time = value; }
}
/// <summary>
/// Gets/sets last modification time.
/// </summary>
public DateTime LastModificationTime {
get { return Records.Contains(RecordType.LastModificationTime) ? Records[RecordType.LastModificationTime].Time : DateTime.MinValue; }
set { Records[RecordType.LastModificationTime].Time = value; }
}
/// <summary>
/// Gets/sets URL.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Password Safe file format doesn't require this URL to follow URL format.")]
public string Url {
get { return Records.Contains(RecordType.Url) ? Records[RecordType.Url].Text : ""; }
set { Records[RecordType.Url].Text = value; }
}
/// <summary>
/// Gets/sets e-mail address.
/// </summary>
public string Email {
get { return Records.Contains(RecordType.EmailAddress) ? Records[RecordType.EmailAddress].Text : ""; }
set { Records[RecordType.EmailAddress].Text = value; }
}
/// <summary>
/// Gets/sets two factor key.
/// Should be encoded as base 32.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Property returns copy of the array (in Field.GetBytes() and Field.SetBytes()).")]
public byte[] TwoFactorKey {
get { return Records.Contains(RecordType.TwoFactorKey) ? Records[RecordType.TwoFactorKey].GetBytes() : new byte[0]; }
set { Records[RecordType.TwoFactorKey].SetBytes(value); }
}
/// <summary>
/// Gets/sets credit card number.
/// Number should consist of digits and spaces.
/// </summary>
public string CreditCardNumber {
get { return Records.Contains(RecordType.CreditCardNumber) ? Records[RecordType.CreditCardNumber].Text : ""; }
set { Records[RecordType.CreditCardNumber].Text = value; }
}
/// <summary>
/// Gets/sets credit card expiration.
/// Format should be MM/YY, where MM is 01-12, and YY 00-99.
/// </summary>
public string CreditCardExpiration {
get { return Records.Contains(RecordType.CreditCardExpiration) ? Records[RecordType.CreditCardExpiration].Text : ""; }
set { Records[RecordType.CreditCardExpiration].Text = value; }
}
/// <summary>
/// Gets/sets credit card verification value.
/// CVV (CVV2) is three or four digits.
/// </summary>
public string CreditCardVerificationValue {
get { return Records.Contains(RecordType.CreditCardVerificationValue) ? Records[RecordType.CreditCardVerificationValue].Text : ""; }
set { Records[RecordType.CreditCardVerificationValue].Text = value; }
}
/// <summary>
/// Gets/sets credit card PIN.
/// PIN is four to twelve digits long (ISO-9564).
/// </summary>
public string CreditCardPin {
get { return Records.Contains(RecordType.CreditCardPin) ? Records[RecordType.CreditCardPin].Text : ""; }
set { Records[RecordType.CreditCardPin].Text = value; }
}
/// <summary>
/// Gets/sets UTF-8 encoded text used for QR code generation.
/// </summary>
public string QRCode {
get { return Records.Contains(RecordType.QRCode) ? Records[RecordType.QRCode].Text : ""; }
set { Records[RecordType.QRCode].Text = value; }
}
/// <summary>
/// Gets/sets auto-type text.
/// </summary>
public string Autotype {
get { return Records.Contains(RecordType.Autotype) ? Records[RecordType.Autotype].Text : ""; }
set { Records[RecordType.Autotype].Text = value; }
}
/// <summary>
/// Return auto-type tokens with textual fields filled in. Command fields, e.g. Wait, are not filled.
/// Following commands are possible:
/// * TwoFactorCode: 6-digit code for two-factor authentication.
/// * Delay: Delay between characters in milliseconds.
/// * Wait: Pause in milliseconds.
/// * Legacy: Switches processing to legacy mode.
/// </summary>
public IEnumerable<AutotypeToken> AutotypeTokens {
get { return AutotypeToken.GetAutotypeTokens(Autotype, this); }
}
/// <summary>
/// Gets password history.
/// </summary>
public PasswordHistoryCollection PasswordHistory {
get { return new PasswordHistoryCollection(Records); }
}
/// <summary>
/// Gets password policy.
/// </summary>
public PasswordPolicy PasswordPolicy {
get { return new PasswordPolicy(Records); }
}
/// <summary>
/// Gets password policy name.
/// </summary>
public string PasswordPolicyName {
get { return Records.Contains(RecordType.PasswordPolicyName) ? Records[RecordType.PasswordPolicyName].Text : ""; }
set { Records[RecordType.PasswordPolicyName].Text = value; }
}
/// <summary>
/// Gets list of records.
/// </summary>
public RecordCollection Records { get; }
/// <summary>
/// Returns a string representation of an object.
/// </summary>
public override string ToString() {
return Records.Contains(RecordType.Title) ? Records[RecordType.Title].Text : "";
}
#region ICollection extra
/// <summary>
/// Gets field based on a type.
/// If multiple elements exist with the same field type, the first one is returned.
/// If type does not exist, it is created.
///
/// If value is set to null, field is removed.
/// </summary>
/// <param name="type">Type.</param>
/// <exception cref="ArgumentOutOfRangeException">Only null value is supported.</exception>
public Record this[RecordType type] {
get { return Records[type]; }
set { Records[type] = value; }
}
#endregion
#region Clone
/// <summary>
/// Returns the exact copy of the entry.
/// </summary>
public Entry Clone() {
var records = new List<Record>();
foreach (var record in Records) {
records.Add(record.Clone());
}
return new Entry(records);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class PredefinedTypes
{
private SymbolTable _runtimeBinderSymbolTable;
private readonly BSYMMGR _pBSymmgr;
private AggregateSymbol[] _predefSyms; // array of predefined symbol types.
private KAID _aidMsCorLib; // The assembly ID for all predefined types.
public PredefinedTypes(BSYMMGR pBSymmgr)
{
_pBSymmgr = pBSymmgr;
_aidMsCorLib = KAID.kaidNil;
_runtimeBinderSymbolTable = null;
}
// We want to delay load the predef syms as needed.
private AggregateSymbol DelayLoadPredefSym(PredefinedType pt)
{
CType type = _runtimeBinderSymbolTable.GetCTypeFromType(PredefinedTypeFacts.GetAssociatedSystemType(pt));
AggregateSymbol sym = type.getAggregate();
// If we failed to load this thing, we have problems.
if (sym == null)
{
return null;
}
return InitializePredefinedType(sym, pt);
}
internal static AggregateSymbol InitializePredefinedType(AggregateSymbol sym, PredefinedType pt)
{
sym.SetPredefined(true);
sym.SetPredefType(pt);
sym.SetSkipUDOps(pt <= PredefinedType.PT_ENUM && pt != PredefinedType.PT_INTPTR && pt != PredefinedType.PT_UINTPTR && pt != PredefinedType.PT_TYPE);
return sym;
}
public bool Init(ErrorHandling errorContext, SymbolTable symtable)
{
_runtimeBinderSymbolTable = symtable;
Debug.Assert(_pBSymmgr != null);
Debug.Assert(_predefSyms == null);
if (_aidMsCorLib == KAID.kaidNil)
{
// If we haven't found mscorlib yet, first look for System.Object. Then use its assembly as
// the location for all other pre-defined types.
AggregateSymbol aggObj = FindPredefinedType(errorContext, PredefinedTypeFacts.GetName(PredefinedType.PT_OBJECT), KAID.kaidGlobal, AggKindEnum.Class, 0, true);
if (aggObj == null)
return false;
_aidMsCorLib = aggObj.GetAssemblyID();
}
_predefSyms = new AggregateSymbol[(int)PredefinedType.PT_COUNT];
Debug.Assert(_predefSyms != null);
return true;
}
////////////////////////////////////////////////////////////////////////////////
// finds an existing declaration for a predefined type.
// returns null on failure. If isRequired is true, an error message is also
// given.
private static readonly char[] s_nameSeparators = new char[] { '.' };
private AggregateSymbol FindPredefinedType(ErrorHandling errorContext, string pszType, KAID aid, AggKindEnum aggKind, int arity, bool isRequired)
{
Debug.Assert(!string.IsNullOrEmpty(pszType)); // Shouldn't be the empty string!
NamespaceOrAggregateSymbol bagCur = _pBSymmgr.GetRootNS();
Name name = null;
string[] nameParts = pszType.Split(s_nameSeparators);
for (int i = 0, n = nameParts.Length; i < n; i++)
{
name = _pBSymmgr.GetNameManager().Add(nameParts[i]);
if (i == n - 1)
{
// This is the last component. Handle it special below.
break;
}
// first search for an outer type which is also predefined
// this must be first because we always create a namespace for
// outer names, even for nested types
AggregateSymbol aggNext = _pBSymmgr.LookupGlobalSymCore(name, bagCur, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol();
if (aggNext != null && aggNext.InAlias(aid) && aggNext.IsPredefined())
{
bagCur = aggNext;
}
else
{
// ... if no outer type, then search for namespaces
NamespaceSymbol nsNext = _pBSymmgr.LookupGlobalSymCore(name, bagCur, symbmask_t.MASK_NamespaceSymbol).AsNamespaceSymbol();
bool bIsInAlias = true;
if (nsNext == null)
{
bIsInAlias = false;
}
else
{
bIsInAlias = nsNext.InAlias(aid);
}
if (!bIsInAlias)
{
// Didn't find the namespace in this aid.
if (isRequired)
{
errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, pszType);
}
return null;
}
bagCur = nsNext;
}
}
AggregateSymbol aggAmbig;
AggregateSymbol aggBad;
AggregateSymbol aggFound = FindPredefinedTypeCore(name, bagCur, aid, aggKind, arity, out aggAmbig, out aggBad);
if (aggFound == null)
{
// Didn't find the AggregateSymbol.
if (isRequired)
{
if (aggBad != null)
errorContext.ErrorRef(ErrorCode.ERR_PredefinedTypeBadType, aggBad);
else
errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, pszType);
}
return null;
}
if (aggAmbig == null && aid != KAID.kaidGlobal)
{
// Look in kaidGlobal to make sure there isn't a conflicting one.
AggregateSymbol tmp;
AggregateSymbol agg2 = FindPredefinedTypeCore(name, bagCur, KAID.kaidGlobal, aggKind, arity, out aggAmbig, out tmp);
Debug.Assert(agg2 != null);
if (agg2 != aggFound)
aggAmbig = agg2;
}
return aggFound;
}
private AggregateSymbol FindPredefinedTypeCore(Name name, NamespaceOrAggregateSymbol bag, KAID aid, AggKindEnum aggKind, int arity,
out AggregateSymbol paggAmbig, out AggregateSymbol paggBad)
{
AggregateSymbol aggFound = null;
paggAmbig = null;
paggBad = null;
for (AggregateSymbol aggCur = _pBSymmgr.LookupGlobalSymCore(name, bag, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol();
aggCur != null;
aggCur = BSYMMGR.LookupNextSym(aggCur, bag, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol())
{
if (!aggCur.InAlias(aid) || aggCur.GetTypeVarsAll().Count != arity)
{
continue;
}
if (aggCur.AggKind() != aggKind)
{
if (paggBad == null)
{
paggBad = aggCur;
}
continue;
}
if (aggFound != null)
{
Debug.Assert(paggAmbig == null);
paggAmbig = aggCur;
break;
}
aggFound = aggCur;
if (paggAmbig == null)
{
break;
}
}
return aggFound;
}
public void ReportMissingPredefTypeError(ErrorHandling errorContext, PredefinedType pt)
{
Debug.Assert(_pBSymmgr != null);
Debug.Assert(_predefSyms != null);
Debug.Assert((PredefinedType)0 <= pt && pt < PredefinedType.PT_COUNT && _predefSyms[(int)pt] == null);
// We do not assert that !predefTypeInfo[pt].isRequired because if the user is defining
// their own MSCorLib and is defining a required PredefType, they'll run into this error
// and we need to allow it to go through.
errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, PredefinedTypeFacts.GetName(pt));
}
public AggregateSymbol GetReqPredefAgg(PredefinedType pt)
{
if (!PredefinedTypeFacts.IsRequired(pt)) throw Error.InternalCompilerError();
if (_predefSyms[(int)pt] == null)
{
// Delay load this thing.
_predefSyms[(int)pt] = DelayLoadPredefSym(pt);
}
return _predefSyms[(int)pt];
}
public AggregateSymbol GetOptPredefAgg(PredefinedType pt)
{
if (_predefSyms[(int)pt] == null)
{
// Delay load this thing.
_predefSyms[(int)pt] = DelayLoadPredefSym(pt);
}
Debug.Assert(_predefSyms != null);
return _predefSyms[(int)pt];
}
////////////////////////////////////////////////////////////////////////////////
// Some of the predefined types have built-in names, like "int" or "string" or
// "object". This return the nice name if one exists; otherwise null is
// returned.
private static string GetNiceName(PredefinedType pt)
{
return PredefinedTypeFacts.GetNiceName(pt);
}
public static string GetNiceName(AggregateSymbol type)
{
if (type.IsPredefined())
return GetNiceName(type.GetPredefType());
else
return null;
}
public static string GetFullName(PredefinedType pt)
{
return PredefinedTypeFacts.GetName(pt);
}
public static bool isRequired(PredefinedType pt)
{
return PredefinedTypeFacts.IsRequired(pt);
}
}
internal static class PredefinedTypeFacts
{
internal static string GetName(PredefinedType type)
{
return s_pdTypes[(int)type].name;
}
internal static bool IsRequired(PredefinedType type)
{
return s_pdTypes[(int)type].required;
}
internal static FUNDTYPE GetFundType(PredefinedType type)
{
return s_pdTypes[(int)type].fundType;
}
internal static Type GetAssociatedSystemType(PredefinedType type)
{
return s_pdTypes[(int)type].AssociatedSystemType;
}
internal static bool IsSimpleType(PredefinedType type)
{
switch (type)
{
case PredefinedType.PT_BYTE:
case PredefinedType.PT_SHORT:
case PredefinedType.PT_INT:
case PredefinedType.PT_LONG:
case PredefinedType.PT_FLOAT:
case PredefinedType.PT_DOUBLE:
case PredefinedType.PT_DECIMAL:
case PredefinedType.PT_CHAR:
case PredefinedType.PT_BOOL:
case PredefinedType.PT_SBYTE:
case PredefinedType.PT_USHORT:
case PredefinedType.PT_UINT:
case PredefinedType.PT_ULONG:
return true;
default:
return false;
}
}
internal static bool IsNumericType(PredefinedType type)
{
switch (type)
{
case PredefinedType.PT_BYTE:
case PredefinedType.PT_SHORT:
case PredefinedType.PT_INT:
case PredefinedType.PT_LONG:
case PredefinedType.PT_FLOAT:
case PredefinedType.PT_DOUBLE:
case PredefinedType.PT_DECIMAL:
case PredefinedType.PT_SBYTE:
case PredefinedType.PT_USHORT:
case PredefinedType.PT_UINT:
case PredefinedType.PT_ULONG:
return true;
default:
return false;
}
}
internal static string GetNiceName(PredefinedType type)
{
switch (type)
{
case PredefinedType.PT_BYTE:
return "byte";
case PredefinedType.PT_SHORT:
return "short";
case PredefinedType.PT_INT:
return "int";
case PredefinedType.PT_LONG:
return "long";
case PredefinedType.PT_FLOAT:
return "float";
case PredefinedType.PT_DOUBLE:
return "double";
case PredefinedType.PT_DECIMAL:
return "decimal";
case PredefinedType.PT_CHAR:
return "char";
case PredefinedType.PT_BOOL:
return "bool";
case PredefinedType.PT_SBYTE:
return "sbyte";
case PredefinedType.PT_USHORT:
return "ushort";
case PredefinedType.PT_UINT:
return "uint";
case PredefinedType.PT_ULONG:
return "ulong";
case PredefinedType.PT_OBJECT:
return "object";
case PredefinedType.PT_STRING:
return "string";
default:
return null;
}
}
internal static bool IsPredefinedType(string name)
{
return s_pdTypeNames.ContainsKey(name);
}
internal static PredefinedType GetPredefTypeIndex(string name)
{
return s_pdTypeNames[name];
}
private sealed class PredefinedTypeInfo
{
internal readonly PredefinedType type;
internal readonly string name;
internal readonly bool required;
internal readonly FUNDTYPE fundType;
internal readonly Type AssociatedSystemType;
internal PredefinedTypeInfo(PredefinedType type, Type associatedSystemType, string name, bool required, int arity, AggKindEnum aggKind, FUNDTYPE fundType, bool inMscorlib)
{
this.type = type;
this.name = name;
this.required = required;
this.fundType = fundType;
AssociatedSystemType = associatedSystemType;
}
internal PredefinedTypeInfo(PredefinedType type, Type associatedSystemType, string name, bool required, int arity, bool inMscorlib)
: this(type, associatedSystemType, name, required, arity, AggKindEnum.Class, FUNDTYPE.FT_REF, inMscorlib)
{
}
}
private static readonly PredefinedTypeInfo[] s_pdTypes = new PredefinedTypeInfo[] {
new PredefinedTypeInfo(PredefinedType.PT_BYTE, typeof(byte), "System.Byte", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U1, true),
new PredefinedTypeInfo(PredefinedType.PT_SHORT, typeof(short), "System.Int16", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I2, true),
new PredefinedTypeInfo(PredefinedType.PT_INT, typeof(int), "System.Int32", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I4, true),
new PredefinedTypeInfo(PredefinedType.PT_LONG, typeof(long), "System.Int64", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I8, true),
new PredefinedTypeInfo(PredefinedType.PT_FLOAT, typeof(float), "System.Single", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_R4, true),
new PredefinedTypeInfo(PredefinedType.PT_DOUBLE, typeof(double), "System.Double", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_R8, true),
new PredefinedTypeInfo(PredefinedType.PT_DECIMAL, typeof(decimal), "System.Decimal", false, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_CHAR, typeof(char), "System.Char", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U2, true),
new PredefinedTypeInfo(PredefinedType.PT_BOOL, typeof(bool), "System.Boolean", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I1, true),
new PredefinedTypeInfo(PredefinedType.PT_SBYTE, typeof(sbyte), "System.SByte", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I1, true),
new PredefinedTypeInfo(PredefinedType.PT_USHORT, typeof(ushort), "System.UInt16", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U2, true),
new PredefinedTypeInfo(PredefinedType.PT_UINT, typeof(uint), "System.UInt32", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U4, true),
new PredefinedTypeInfo(PredefinedType.PT_ULONG, typeof(ulong), "System.UInt64", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U8, true),
new PredefinedTypeInfo(PredefinedType.PT_INTPTR, typeof(IntPtr), "System.IntPtr", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_UINTPTR, typeof(UIntPtr), "System.UIntPtr", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_OBJECT, typeof(object), "System.Object", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_STRING, typeof(string), "System.String", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DELEGATE, typeof(Delegate), "System.Delegate", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_MULTIDEL, typeof(MulticastDelegate), "System.MulticastDelegate", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ARRAY, typeof(Array), "System.Array", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_EXCEPTION, typeof(Exception), "System.Exception", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_TYPE, typeof(Type), "System.Type", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_MONITOR, typeof(System.Threading.Monitor), "System.Threading.Monitor", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_VALUE, typeof(ValueType), "System.ValueType", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ENUM, typeof(Enum), "System.Enum", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DATETIME, typeof(DateTime), "System.DateTime", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_DEBUGGABLEATTRIBUTE, typeof(DebuggableAttribute), "System.Diagnostics.DebuggableAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DEBUGGABLEATTRIBUTE_DEBUGGINGMODES, typeof(DebuggableAttribute.DebuggingModes), "System.Diagnostics.DebuggableAttribute.DebuggingModes", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_IN, typeof(System.Runtime.InteropServices.InAttribute), "System.Runtime.InteropServices.InAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_OUT, typeof(System.Runtime.InteropServices.OutAttribute), "System.Runtime.InteropServices.OutAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTE, typeof(Attribute), "System.Attribute", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTEUSAGE, typeof(AttributeUsageAttribute), "System.AttributeUsageAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTETARGETS, typeof(AttributeTargets), "System.AttributeTargets", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_OBSOLETE, typeof(ObsoleteAttribute), "System.ObsoleteAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_CONDITIONAL, typeof(ConditionalAttribute), "System.Diagnostics.ConditionalAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_CLSCOMPLIANT, typeof(CLSCompliantAttribute), "System.CLSCompliantAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_GUID, typeof(System.Runtime.InteropServices.GuidAttribute), "System.Runtime.InteropServices.GuidAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DEFAULTMEMBER, typeof(System.Reflection.DefaultMemberAttribute), "System.Reflection.DefaultMemberAttribute", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_PARAMS, typeof(ParamArrayAttribute), "System.ParamArrayAttribute", true, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_COMIMPORT, typeof(System.Runtime.InteropServices.ComImportAttribute), "System.Runtime.InteropServices.ComImportAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_FIELDOFFSET, typeof(System.Runtime.InteropServices.FieldOffsetAttribute), "System.Runtime.InteropServices.FieldOffsetAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_STRUCTLAYOUT, typeof(System.Runtime.InteropServices.StructLayoutAttribute), "System.Runtime.InteropServices.StructLayoutAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_LAYOUTKIND, typeof(System.Runtime.InteropServices.LayoutKind), "System.Runtime.InteropServices.LayoutKind", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_MARSHALAS, typeof(System.Runtime.InteropServices.MarshalAsAttribute), "System.Runtime.InteropServices.MarshalAsAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DLLIMPORT, typeof(System.Runtime.InteropServices.DllImportAttribute), "System.Runtime.InteropServices.DllImportAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_INDEXERNAME, typeof(System.Runtime.CompilerServices.IndexerNameAttribute), "System.Runtime.CompilerServices.IndexerNameAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DECIMALCONSTANT, typeof(System.Runtime.CompilerServices.DecimalConstantAttribute), "System.Runtime.CompilerServices.DecimalConstantAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DEFAULTVALUE, typeof(System.Runtime.InteropServices.DefaultParameterValueAttribute), "System.Runtime.InteropServices.DefaultParameterValueAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_UNMANAGEDFUNCTIONPOINTER, typeof(System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute), "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_CALLINGCONVENTION, typeof(System.Runtime.InteropServices.CallingConvention), "System.Runtime.InteropServices.CallingConvention", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_I4, true),
new PredefinedTypeInfo(PredefinedType.PT_CHARSET, typeof(System.Runtime.InteropServices.CharSet), "System.Runtime.InteropServices.CharSet", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_TYPEHANDLE, typeof(RuntimeTypeHandle), "System.RuntimeTypeHandle", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_FIELDHANDLE, typeof(RuntimeFieldHandle), "System.RuntimeFieldHandle", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_METHODHANDLE, typeof(RuntimeMethodHandle), "System.RuntimeMethodHandle", false, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_G_DICTIONARY, typeof(Dictionary<,>), "System.Collections.Generic.Dictionary`2", false, 2, true),
new PredefinedTypeInfo(PredefinedType.PT_IASYNCRESULT, typeof(IAsyncResult), "System.IAsyncResult", false, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_ASYNCCBDEL, typeof(AsyncCallback), "System.AsyncCallback", false, 0, AggKindEnum.Delegate, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_IDISPOSABLE, typeof(IDisposable), "System.IDisposable", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_IENUMERABLE, typeof(System.Collections.IEnumerable), "System.Collections.IEnumerable", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_IENUMERATOR, typeof(System.Collections.IEnumerator), "System.Collections.IEnumerator", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_SYSTEMVOID, typeof(void), "System.Void", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_RUNTIMEHELPERS, typeof(System.Runtime.CompilerServices.RuntimeHelpers), "System.Runtime.CompilerServices.RuntimeHelpers", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_VOLATILEMOD, typeof(System.Runtime.CompilerServices.IsVolatile), "System.Runtime.CompilerServices.IsVolatile", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_COCLASS, typeof(System.Runtime.InteropServices.CoClassAttribute), "System.Runtime.InteropServices.CoClassAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ACTIVATOR, typeof(Activator), "System.Activator", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_G_IENUMERABLE, typeof(IEnumerable<>), "System.Collections.Generic.IEnumerable`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_G_IENUMERATOR, typeof(IEnumerator<>), "System.Collections.Generic.IEnumerator`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_G_OPTIONAL, typeof(Nullable<>), "System.Nullable`1", false, 1, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true),
new PredefinedTypeInfo(PredefinedType.PT_FIXEDBUFFER, typeof(System.Runtime.CompilerServices.FixedBufferAttribute), "System.Runtime.CompilerServices.FixedBufferAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DEFAULTCHARSET, typeof(System.Runtime.InteropServices.DefaultCharSetAttribute), "System.Runtime.InteropServices.DefaultCharSetAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_COMPILATIONRELAXATIONS, typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute), "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_RUNTIMECOMPATIBILITY, typeof(System.Runtime.CompilerServices.RuntimeCompatibilityAttribute), "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_FRIENDASSEMBLY, typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute), "System.Runtime.CompilerServices.InternalsVisibleToAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERHIDDEN, typeof(DebuggerHiddenAttribute), "System.Diagnostics.DebuggerHiddenAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_TYPEFORWARDER, typeof(System.Runtime.CompilerServices.TypeForwardedToAttribute), "System.Runtime.CompilerServices.TypeForwardedToAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_KEYFILE, typeof(System.Reflection.AssemblyKeyFileAttribute), "System.Reflection.AssemblyKeyFileAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_KEYNAME, typeof(System.Reflection.AssemblyKeyNameAttribute), "System.Reflection.AssemblyKeyNameAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DELAYSIGN, typeof(System.Reflection.AssemblyDelaySignAttribute), "System.Reflection.AssemblyDelaySignAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_NOTSUPPORTEDEXCEPTION, typeof(NotSupportedException), "System.NotSupportedException", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_COMPILERGENERATED, typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), "System.Runtime.CompilerServices.CompilerGeneratedAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_UNSAFEVALUETYPE, typeof(System.Runtime.CompilerServices.UnsafeValueTypeAttribute), "System.Runtime.CompilerServices.UnsafeValueTypeAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYFLAGS, typeof(System.Reflection.AssemblyFlagsAttribute), "System.Reflection.AssemblyFlagsAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYVERSION, typeof(System.Reflection.AssemblyVersionAttribute), "System.Reflection.AssemblyVersionAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYCULTURE, typeof(System.Reflection.AssemblyCultureAttribute), "System.Reflection.AssemblyCultureAttribute", false, 0, true),
// LINQ
new PredefinedTypeInfo(PredefinedType.PT_G_IQUERYABLE, typeof(System.Linq.IQueryable<>), "System.Linq.IQueryable`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false),
new PredefinedTypeInfo(PredefinedType.PT_IQUERYABLE, typeof(System.Linq.IQueryable), "System.Linq.IQueryable", false, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, false),
new PredefinedTypeInfo(PredefinedType.PT_STRINGBUILDER, typeof(System.Text.StringBuilder), "System.Text.StringBuilder", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_G_ICOLLECTION, typeof(ICollection<>), "System.Collections.Generic.ICollection`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_G_ILIST, typeof(IList<>), "System.Collections.Generic.IList`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true),
new PredefinedTypeInfo(PredefinedType.PT_EXTENSION, typeof(System.Runtime.CompilerServices.ExtensionAttribute), "System.Runtime.CompilerServices.ExtensionAttribute", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_G_EXPRESSION, typeof(System.Linq.Expressions.Expression<>), "System.Linq.Expressions.Expression`1", false, 1, false),
new PredefinedTypeInfo(PredefinedType.PT_EXPRESSION, typeof(System.Linq.Expressions.Expression), "System.Linq.Expressions.Expression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_LAMBDAEXPRESSION, typeof(System.Linq.Expressions.LambdaExpression), "System.Linq.Expressions.LambdaExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_BINARYEXPRESSION, typeof(System.Linq.Expressions.BinaryExpression), "System.Linq.Expressions.BinaryExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_UNARYEXPRESSION, typeof(System.Linq.Expressions.UnaryExpression), "System.Linq.Expressions.UnaryExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_CONDITIONALEXPRESSION, typeof(System.Linq.Expressions.ConditionalExpression), "System.Linq.Expressions.ConditionalExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_CONSTANTEXPRESSION, typeof(System.Linq.Expressions.ConstantExpression), "System.Linq.Expressions.ConstantExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_PARAMETEREXPRESSION, typeof(System.Linq.Expressions.ParameterExpression), "System.Linq.Expressions.ParameterExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_MEMBEREXPRESSION, typeof(System.Linq.Expressions.MemberExpression), "System.Linq.Expressions.MemberExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_METHODCALLEXPRESSION, typeof(System.Linq.Expressions.MethodCallExpression), "System.Linq.Expressions.MethodCallExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_NEWEXPRESSION, typeof(System.Linq.Expressions.NewExpression), "System.Linq.Expressions.NewExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_BINDING, typeof(System.Linq.Expressions.MemberBinding), "System.Linq.Expressions.MemberBinding", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_MEMBERINITEXPRESSION, typeof(System.Linq.Expressions.MemberInitExpression), "System.Linq.Expressions.MemberInitExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_LISTINITEXPRESSION, typeof(System.Linq.Expressions.ListInitExpression), "System.Linq.Expressions.ListInitExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_TYPEBINARYEXPRESSION, typeof(System.Linq.Expressions.TypeBinaryExpression), "System.Linq.Expressions.TypeBinaryExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_NEWARRAYEXPRESSION, typeof(System.Linq.Expressions.NewArrayExpression), "System.Linq.Expressions.NewArrayExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_MEMBERASSIGNMENT, typeof(System.Linq.Expressions.MemberAssignment), "System.Linq.Expressions.MemberAssignment", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_MEMBERLISTBINDING, typeof(System.Linq.Expressions.MemberListBinding), "System.Linq.Expressions.MemberListBinding", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_MEMBERMEMBERBINDING, typeof(System.Linq.Expressions.MemberMemberBinding), "System.Linq.Expressions.MemberMemberBinding", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_INVOCATIONEXPRESSION, typeof(System.Linq.Expressions.InvocationExpression), "System.Linq.Expressions.InvocationExpression", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_FIELDINFO, typeof(System.Reflection.FieldInfo), "System.Reflection.FieldInfo", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_METHODINFO, typeof(System.Reflection.MethodInfo), "System.Reflection.MethodInfo", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_CONSTRUCTORINFO, typeof(System.Reflection.ConstructorInfo), "System.Reflection.ConstructorInfo", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_PROPERTYINFO, typeof(System.Reflection.PropertyInfo), "System.Reflection.PropertyInfo", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_METHODBASE, typeof(System.Reflection.MethodBase), "System.Reflection.MethodBase", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_MEMBERINFO, typeof(System.Reflection.MemberInfo), "System.Reflection.MemberInfo", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERDISPLAY, typeof(DebuggerDisplayAttribute), "System.Diagnostics.DebuggerDisplayAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERBROWSABLE, typeof(DebuggerBrowsableAttribute), "System.Diagnostics.DebuggerBrowsableAttribute", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERBROWSABLESTATE, typeof(DebuggerBrowsableState), "System.Diagnostics.DebuggerBrowsableState", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_I4, true),
new PredefinedTypeInfo(PredefinedType.PT_G_EQUALITYCOMPARER, typeof(EqualityComparer<>), "System.Collections.Generic.EqualityComparer`1", false, 1, true),
new PredefinedTypeInfo(PredefinedType.PT_ELEMENTINITIALIZER, typeof(System.Linq.Expressions.ElementInit), "System.Linq.Expressions.ElementInit", false, 0, false),
new PredefinedTypeInfo(PredefinedType.PT_MISSING, typeof(System.Reflection.Missing), "System.Reflection.Missing", false, 0, true),
new PredefinedTypeInfo(PredefinedType.PT_G_IREADONLYLIST, typeof(IReadOnlyList<>), "System.Collections.Generic.IReadOnlyList`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false),
new PredefinedTypeInfo(PredefinedType.PT_G_IREADONLYCOLLECTION, typeof(IReadOnlyCollection<>), "System.Collections.Generic.IReadOnlyCollection`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false),
};
private static readonly Dictionary<string, PredefinedType> s_pdTypeNames = CreatePredefinedTypeFacts();
private static Dictionary<string, PredefinedType> CreatePredefinedTypeFacts()
{
var pdTypeNames = new Dictionary<string, PredefinedType>((int)PredefinedType.PT_COUNT);
#if DEBUG
for (int i = 0; i < (int)PredefinedType.PT_COUNT; i++)
{
Debug.Assert(s_pdTypes[i].type == (PredefinedType)i);
}
#endif
for (int i = 0; i < (int)PredefinedType.PT_COUNT; i++)
{
pdTypeNames.Add(s_pdTypes[i].name, (PredefinedType)i);
}
return pdTypeNames;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.CSharp.Analyzers.Maintainability.CSharpAvoidUninstantiatedInternalClasses,
Microsoft.CodeQuality.CSharp.Analyzers.Maintainability.CSharpAvoidUninstantiatedInternalClassesFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.VisualBasic.Analyzers.Maintainability.BasicAvoidUninstantiatedInternalClasses,
Microsoft.CodeQuality.VisualBasic.Analyzers.Maintainability.BasicAvoidUninstantiatedInternalClassesFixer>;
namespace Microsoft.CodeQuality.Analyzers.Maintainability.UnitTests
{
public class AvoidUninstantiatedInternalClassesTests
{
[Fact]
public async Task CA1812_CSharp_Diagnostic_UninstantiatedInternalClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal class C { }
",
GetCSharpResultAt(1, 16, "C"));
}
[Fact]
public async Task CA1812_Basic_Diagnostic_UninstantiatedInternalClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Class C
End Class",
GetBasicResultAt(1, 14, "C"));
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedInternalStructAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal struct CInternal { }");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_UninstantiatedInternalStructAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Structure CInternal
End Structure");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedPublicClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"public class C { }");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_UninstantiatedPublicClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Public Class C
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_InstantiatedInternalClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal class C { }
public class D
{
private readonly C _c = new C();
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_InstantiatedInternalClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Class C
End Class
Public Class D
Private _c As New C
End Class");
}
[Fact]
public async Task CA1812_CSharp_Diagnostic_UninstantiatedInternalClassNestedInPublicClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"public class C
{
internal class D { }
}",
GetCSharpResultAt(3, 20, "C.D"));
}
[Fact]
public async Task CA1812_Basic_Diagnostic_UninstantiatedInternalClassNestedInPublicClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Public Class C
Friend Class D
End Class
End Class",
GetBasicResultAt(2, 18, "C.D"));
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_InstantiatedInternalClassNestedInPublicClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"public class C
{
private readonly D _d = new D();
internal class D { }
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_InstantiatedInternalClassNestedInPublicClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Public Class C
Private ReadOnly _d = New D
Friend Class D
End Class
End Class");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_InternalModuleAsync()
{
// No static classes in VB.
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Module M
End Module");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_InternalAbstractClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal abstract class A { }");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_InternalAbstractClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend MustInherit Class A
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_InternalDelegateAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
namespace N
{
internal delegate void Del();
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_InternalDelegateAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Namespace N
Friend Delegate Sub Del()
End Namespace");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_InternalEnumAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"namespace N
{
internal enum E {} // C# enums don't care if there are any members.
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_InternalEnumAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Namespace N
Friend Enum E
None ' VB enums require at least one member.
End Enum
End Namespace");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_AttributeClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"using System;
internal class MyAttribute: Attribute {}
internal class MyOtherAttribute: MyAttribute {}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_AttributeClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Imports System
Friend Class MyAttribute
Inherits Attribute
End Class
Friend Class MyOtherAttribute
Inherits MyAttribute
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningVoidAsync()
{
await new VerifyCS.Test
{
TestState =
{
OutputKind = OutputKind.ConsoleApplication,
Sources =
{
@"internal class C
{
private static void Main() {}
}",
},
},
}.RunAsync();
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_TypeContainingAssemblyEntryPointReturningVoidAsync()
{
await new VerifyVB.Test
{
TestState =
{
OutputKind = OutputKind.ConsoleApplication,
Sources =
{
@"Friend Class C
Public Shared Sub Main()
End Sub
End Class",
},
},
}.RunAsync();
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningIntAsync()
{
await new VerifyCS.Test
{
TestState =
{
OutputKind = OutputKind.ConsoleApplication,
Sources =
{
@"internal class C
{
private static int Main() { return 1; }
}",
},
},
}.RunAsync();
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_TypeContainingAssemblyEntryPointReturningIntAsync()
{
await new VerifyVB.Test
{
TestState =
{
OutputKind = OutputKind.ConsoleApplication,
Sources =
{
@"Friend Class C
Public Shared Function Main() As Integer
Return 1
End Function
End Class",
},
},
}.RunAsync();
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningTaskAsync()
{
await new VerifyCS.Test
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp7_1,
TestState =
{
OutputKind = OutputKind.ConsoleApplication,
Sources =
{
@" using System.Threading.Tasks;
internal static class C
{
private static async Task Main() { await Task.Delay(1); }
}",
},
},
}.RunAsync();
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningTaskIntAsync()
{
await new VerifyCS.Test
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp7_1,
TestState =
{
OutputKind = OutputKind.ConsoleApplication,
Sources =
{
@" using System.Threading.Tasks;
internal static class C
{
private static async Task<int> Main() { await Task.Delay(1); return 1; }
}",
},
},
}.RunAsync();
}
[Fact]
public async Task CA1812_CSharp_Diagnostic_MainMethodIsNotStaticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal class C
{
private void Main() {}
}",
GetCSharpResultAt(1, 16, "C"));
}
[Fact]
public async Task CA1812_Basic_Diagnostic_MainMethodIsNotStaticAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Class C
Private Sub Main()
End Sub
End Class",
GetBasicResultAt(1, 14, "C"));
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_MainMethodIsDifferentlyCasedAsync()
{
await new VerifyVB.Test
{
TestState =
{
OutputKind = OutputKind.ConsoleApplication,
Sources =
{
@"Friend Class C
Private Shared Sub mAiN()
End Sub
End Class",
},
},
ExpectedDiagnostics =
{
// error BC30737: No accessible 'Main' method with an appropriate signature was found in 'TestProject'.
DiagnosticResult.CompilerError("BC30737"),
}
}.RunAsync();
}
// The following tests are just to ensure that the messages are formatted properly
// for types within namespaces.
[Fact]
public async Task CA1812_CSharp_Diagnostic_UninstantiatedInternalClassInNamespaceAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"namespace N
{
internal class C { }
}",
GetCSharpResultAt(3, 20, "C"));
}
[Fact]
public async Task CA1812_Basic_Diagnostic_UninstantiatedInternalClassInNamespaceAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Namespace N
Friend Class C
End Class
End Namespace",
GetBasicResultAt(2, 18, "C"));
}
[Fact]
public async Task CA1812_CSharp_Diagnostic_UninstantiatedInternalClassNestedInPublicClassInNamespaceAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"namespace N
{
public class C
{
internal class D { }
}
}",
GetCSharpResultAt(5, 24, "C.D"));
}
[Fact]
public async Task CA1812_Basic_Diagnostic_UninstantiatedInternalClassNestedInPublicClassInNamespaceAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Namespace N
Public Class C
Friend Class D
End Class
End Class
End Namespace",
GetBasicResultAt(3, 22, "C.D"));
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedInternalMef1ExportedClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"using System;
using System.ComponentModel.Composition;
namespace System.ComponentModel.Composition
{
public class ExportAttribute: Attribute
{
}
}
[Export]
internal class C
{
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_UninstantiatedInternalMef1ExportedClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Imports System
Imports System.ComponentModel.Composition
Namespace System.ComponentModel.Composition
Public Class ExportAttribute
Inherits Attribute
End Class
End Namespace
<Export>
Friend Class C
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedInternalMef2ExportedClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"using System;
using System.ComponentModel.Composition;
namespace System.ComponentModel.Composition
{
public class ExportAttribute: Attribute
{
}
}
[Export]
internal class C
{
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_UninstantiatedInternalMef2ExportedClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Imports System
Imports System.ComponentModel.Composition
Namespace System.ComponentModel.Composition
Public Class ExportAttribute
Inherits Attribute
End Class
End Namespace
<Export>
Friend Class C
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_ImplementsIConfigurationSectionHandlerAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"using System.Configuration;
using System.Xml;
internal class C : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
return null;
}
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_ImplementsIConfigurationSectionHandlerAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Imports System.Configuration
Imports System.Xml
Friend Class C
Implements IConfigurationSectionHandler
Private Function IConfigurationSectionHandler_Create(parent As Object, configContext As Object, section As XmlNode) As Object Implements IConfigurationSectionHandler.Create
Return Nothing
End Function
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_DerivesFromConfigurationSectionAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"using System.Configuration;
namespace System.Configuration
{
public class ConfigurationSection
{
}
}
internal class C : ConfigurationSection
{
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_DerivesFromConfigurationSectionAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Imports System.Configuration
Namespace System.Configuration
Public Class ConfigurationSection
End Class
End Namespace
Friend Class C
Inherits ConfigurationSection
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_DerivesFromSafeHandleAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"using System;
using System.Runtime.InteropServices;
internal class MySafeHandle : SafeHandle
{
protected MySafeHandle(IntPtr invalidHandleValue, bool ownsHandle)
: base(invalidHandleValue, ownsHandle)
{
}
public override bool IsInvalid => true;
protected override bool ReleaseHandle()
{
return true;
}
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_DerivesFromSafeHandleAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Imports System
Imports System.Runtime.InteropServices
Friend Class MySafeHandle
Inherits SafeHandle
Protected Sub New(invalidHandleValue As IntPtr, ownsHandle As Boolean)
MyBase.New(invalidHandleValue, ownsHandle)
End Sub
Public Overrides ReadOnly Property IsInvalid As Boolean
Get
Return True
End Get
End Property
Protected Overrides Function ReleaseHandle() As Boolean
Return True
End Function
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_DerivesFromTraceListenerAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"using System.Diagnostics;
internal class MyTraceListener : TraceListener
{
public override void Write(string message) { }
public override void WriteLine(string message) { }
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_DerivesFromTraceListenerAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Imports System.Diagnostics
Friend Class MyTraceListener
Inherits TraceListener
Public Overrides Sub Write(message As String)
End Sub
Public Overrides Sub WriteLine(message As String)
End Sub
End Class");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_InternalNestedTypeIsInstantiatedAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal class C
{
internal class C2
{
}
}
public class D
{
private readonly C.C2 _c2 = new C.C2();
}
");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_InternalNestedTypeIsInstantiatedAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Class C
Friend Class C2
End Class
End Class
Public Class D
Private _c2 As new C.C2
End Class");
}
[Fact]
public async Task CA1812_CSharp_Diagnostic_InternalNestedTypeIsNotInstantiatedAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal class C
{
internal class C2
{
}
}",
GetCSharpResultAt(3, 20, "C.C2"));
}
[Fact]
public async Task CA1812_Basic_Diagnostic_InternalNestedTypeIsNotInstantiatedAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Class C
Friend Class C2
End Class
End Class",
GetBasicResultAt(2, 18, "C.C2"));
}
[Fact]
public async Task CA1812_CSharp_Diagnostic_PrivateNestedTypeIsInstantiatedAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal class C
{
private readonly C2 _c2 = new C2();
private class C2
{
}
}",
GetCSharpResultAt(1, 16, "C"));
}
[Fact]
public async Task CA1812_Basic_Diagnostic_PrivateNestedTypeIsInstantiatedAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Class C
Private _c2 As New C2
Private Class C2
End Class
End Class",
GetBasicResultAt(1, 14, "C"));
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_StaticHolderClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"internal static class C
{
internal static void F() { }
}");
}
[Fact, WorkItem(1370, "https://github.com/dotnet/roslyn-analyzers/issues/1370")]
public async Task CA1812_CSharp_NoDiagnostic_ImplicitlyInstantiatedFromSubTypeConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"
internal class A
{
public A()
{
}
}
internal class B : A
{
public B()
{
}
}
internal class C<T>
{
}
internal class D : C<int>
{
static void M()
{
var x = new B();
var y = new D();
}
}");
}
[Fact, WorkItem(1370, "https://github.com/dotnet/roslyn-analyzers/issues/1370")]
public async Task CA1812_CSharp_NoDiagnostic_ExplicitlyInstantiatedFromSubTypeConstructorAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"
internal class A
{
public A(int x)
{
}
}
internal class B : A
{
public B(int x): base (x)
{
}
}
internal class C<T>
{
}
internal class D : C<int>
{
public D(): base()
{
}
static void M()
{
var x = new B(0);
var y = new D();
}
}");
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_StaticHolderClassAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Friend Module C
Friend Sub F()
End Sub
End Module");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_EmptyInternalStaticClassAsync()
{
await VerifyCS.VerifyAnalyzerAsync("internal static class S { }");
}
[Fact]
public async Task CA1812_CSharp_NoDiagnostic_UninstantiatedInternalClassInFriendlyAssemblyAsync()
{
await VerifyCS.VerifyAnalyzerAsync(
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""TestProject"")]
internal class C { }"
);
}
[Fact]
public async Task CA1812_Basic_NoDiagnostic_UninstantiatedInternalClassInFriendlyAssemblyAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleToAttribute(""TestProject"")>
Friend Class C
End Class"
);
}
[Fact, WorkItem(1370, "https://github.com/dotnet/roslyn-analyzers/issues/1370")]
public async Task CA1812_Basic_NoDiagnostic_ImplicitlyInstantiatedFromSubTypeConstructorAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"
Friend Class A
Public Sub New()
End Sub
End Class
Friend Class B
Inherits A
Public Sub New()
End Sub
End Class
Friend Class C(Of T)
End Class
Friend Class D
Inherits C(Of Integer)
Private Shared Sub M()
Dim x = New B()
Dim y = New D()
End Sub
End Class");
}
[Fact, WorkItem(1370, "https://github.com/dotnet/roslyn-analyzers/issues/1370")]
public async Task CA1812_Basic_NoDiagnostic_ExplicitlyInstantiatedFromSubTypeConstructorAsync()
{
await VerifyVB.VerifyAnalyzerAsync(
@"
Friend Class A
Public Sub New(ByVal x As Integer)
End Sub
End Class
Friend Class B
Inherits A
Public Sub New(ByVal x As Integer)
MyBase.New(x)
End Sub
End Class
Friend Class C(Of T)
End Class
Friend Class D
Inherits C(Of Integer)
Public Sub New()
MyBase.New()
End Sub
Private Shared Sub M()
Dim x = New B(0)
Dim y = New D()
End Sub
End Class");
}
[Fact, WorkItem(1154, "https://github.com/dotnet/roslyn-analyzers/issues/1154")]
public async Task CA1812_CSharp_GenericInternalClass_InstanciatedNoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Collections.Generic;
using System.Linq;
public static class X
{
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, Comparison<T> compare)
{
return source.OrderBy(new ComparisonComparer<T>(compare));
}
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, IComparer<T> comparer)
{
return source.OrderBy(t => t, comparer);
}
private class ComparisonComparer<T> : Comparer<T>
{
private readonly Comparison<T> _compare;
public ComparisonComparer(Comparison<T> compare)
{
_compare = compare;
}
public override int Compare(T x, T y)
{
return _compare(x, y);
}
}
}
");
}
[Fact, WorkItem(1154, "https://github.com/dotnet/roslyn-analyzers/issues/1154")]
public async Task CA1812_Basic_GenericInternalClass_InstanciatedNoDiagnosticAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices
Module M
<Extension()>
Public Function OrderBy(Of T)(ByVal source As IEnumerable(Of T), compare As Comparison(Of T)) As IEnumerable(Of T)
Return source.OrderBy(New ComparisonCompare(Of T)(compare))
End Function
<Extension()>
Public Function OrderBy(Of T)(ByVal source As IEnumerable(Of T), comparer As IComparer(Of T)) As IEnumerable(Of T)
Return source.OrderBy(Function(i) i, comparer)
End Function
Private Class ComparisonCompare(Of T)
Inherits Comparer(Of T)
Private _compare As Comparison(Of T)
Public Sub New(compare As Comparison(Of T))
_compare = compare
End Sub
Public Overrides Function Compare(x As T, y As T) As Integer
Throw New NotImplementedException()
End Function
End Class
End Module
");
}
[Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")]
public async Task CA1812_CSharp_NoDiagnostic_GenericMethodWithNewConstraintAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
internal class InstantiatedType
{
}
internal static class Factory
{
internal static T Create<T>()
where T : new()
{
return new T();
}
}
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine(Factory.Create<InstantiatedType>());
}
}");
}
[Fact, WorkItem(1447, "https://github.com/dotnet/roslyn-analyzers/issues/1447")]
public async Task CA1812_CSharp_NoDiagnostic_GenericMethodWithNewConstraintInvokedFromGenericMethodAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal class InstantiatedClass
{
public InstantiatedClass()
{
}
}
internal class InstantiatedClass2
{
public InstantiatedClass2()
{
}
}
internal class InstantiatedClass3
{
public InstantiatedClass3()
{
}
}
internal static class C
{
private static T Create<T>()
where T : new()
{
return new T();
}
public static void M<T>()
where T : InstantiatedClass, new()
{
Create<T>();
}
public static void M2<T, T2>()
where T : T2, new()
where T2 : InstantiatedClass2
{
Create<T>();
}
public static void M3<T, T2, T3>()
where T : T2, new()
where T2 : T3
where T3: InstantiatedClass3
{
Create<T>();
}
public static void M3()
{
M<InstantiatedClass>();
M2<InstantiatedClass2, InstantiatedClass2>();
M3<InstantiatedClass3, InstantiatedClass3, InstantiatedClass3>();
}
}");
}
[Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")]
public async Task CA1812_Basic_NoDiagnostic_GenericMethodWithNewConstraintAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Module Module1
Sub Main()
Console.WriteLine(Create(Of InstantiatedType)())
End Sub
Friend Class InstantiatedType
End Class
Friend Function Create(Of T As New)() As T
Return New T
End Function
End Module");
}
[Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")]
public async Task CA1812_CSharp_NoDiagnostic_GenericTypeWithNewConstraintAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal class InstantiatedType
{
}
internal class Factory<T> where T : new()
{
}
internal class Program
{
public static void Main(string[] args)
{
var factory = new Factory<InstantiatedType>();
}
}");
}
[Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")]
public async Task CA1812_Basic_NoDiagnostic_GenericTypeWithNewConstraintAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Module Module1
Sub Main()
Console.WriteLine(New Factory(Of InstantiatedType))
End Sub
Friend Class InstantiatedType
End Class
Friend Class Factory(Of T As New)
End Class
End Module");
}
[Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")]
public async Task CA1812_CSharp_Diagnostic_NestedGenericTypeWithNoNewConstraintAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Collections.Generic;
internal class InstantiatedType
{
}
internal class Factory<T> where T : new()
{
}
internal class Program
{
public static void Main(string[] args)
{
var list = new List<Factory<InstantiatedType>>();
}
}",
GetCSharpResultAt(4, 16, "InstantiatedType"),
GetCSharpResultAt(8, 16, "Factory<T>"));
}
[Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")]
public async Task CA1812_Basic_Diagnostic_NestedGenericTypeWithNoNewConstraintAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Collections.Generic
Module Library
Friend Class InstantiatedType
End Class
Friend Class Factory(Of T As New)
End Class
Sub Main()
Dim a = New List(Of Factory(Of InstantiatedType))
End Sub
End Module",
GetBasicResultAt(5, 18, "Library.InstantiatedType"),
GetBasicResultAt(8, 18, "Library.Factory(Of T)"));
}
[Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")]
public async Task CA1812_CSharp_NoDiagnostic_NestedGenericTypeWithNewConstraintAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Collections.Generic;
internal class InstantiatedType
{
}
internal class Factory1<T> where T : new()
{
}
internal class Factory2<T> where T : new()
{
}
internal class Program
{
public static void Main(string[] args)
{
var factory = new Factory1<Factory2<InstantiatedType>>();
}
}");
}
[Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")]
public async Task CA1812_Basic_NoDiagnostic_NestedGenericTypeWithNewConstraintAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Collections.Generic
Module Library
Friend Class InstantiatedType
End Class
Friend Class Factory1(Of T As New)
End Class
Friend Class Factory2(Of T As New)
End Class
Sub Main()
Dim a = New Factory1(Of Factory2(Of InstantiatedType))
End Sub
End Module");
}
[Fact, WorkItem(1739, "https://github.com/dotnet/roslyn-analyzers/issues/1739")]
public async Task CA1812_CSharp_NoDiagnostic_GenericTypeWithRecursiveConstraintAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public abstract class JobStateBase<TState>
where TState : JobStateBase<TState>, new()
{
public void SomeFunction ()
{
new JobStateChangeHandler<TState>();
}
}
public class JobStateChangeHandler<TState>
where TState : JobStateBase<TState>, new()
{
}
");
}
[Fact, WorkItem(2751, "https://github.com/dotnet/roslyn-analyzers/issues/2751")]
public async Task CA1812_CSharp_NoDiagnostic_TypeDeclaredInCoClassAttributeAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
[CoClass(typeof(CSomeClass))]
internal interface ISomeInterface {}
internal class CSomeClass {}
");
}
[Fact, WorkItem(2751, "https://github.com/dotnet/roslyn-analyzers/issues/2751")]
public async Task CA1812_CSharp_DontFailOnInvalidCoClassUsagesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System.Runtime.InteropServices;
[{|CS7036:CoClass|}]
internal interface ISomeInterface1 {}
[CoClass({|CS0119:CSomeClass|})]
internal interface ISomeInterface2 {}
[{|CS1729:CoClass(typeof(CSomeClass), null)|}]
internal interface ISomeInterface3 {}
[CoClass(typeof(ISomeInterface3))] // This isn't a class-type
internal interface ISomeInterface4 {}
internal class CSomeClass {}
",
// Test0.cs(16,16): warning CA1812: CSomeClass is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static members, make it static (Shared in Visual Basic).
GetCSharpResultAt(16, 16, "CSomeClass"));
}
[Theory]
[WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
[WorkItem(1708, "https://github.com/dotnet/roslyn-analyzers/issues/1708")]
[InlineData("System.ComponentModel.DesignerAttribute")]
[InlineData("System.Diagnostics.DebuggerTypeProxyAttribute")]
public async Task CA1812_DesignerAttributeTypeName_NoDiagnosticAsync(string attributeFullName)
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace SomeNamespace
{
internal class MyTextBoxDesigner { }
[" + attributeFullName + @"(""SomeNamespace.MyTextBoxDesigner, TestProject"")]
public class MyTextBox { }
}");
}
[Theory]
[WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
[WorkItem(1708, "https://github.com/dotnet/roslyn-analyzers/issues/1708")]
[InlineData("System.ComponentModel.DesignerAttribute")]
[InlineData("System.Diagnostics.DebuggerTypeProxyAttribute")]
public async Task CA1812_DesignerAttributeTypeNameWithFullAssemblyName_NoDiagnosticAsync(string attributeFullName)
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
namespace SomeNamespace
{
internal class MyTextBoxDesigner { }
[" + attributeFullName + @"(""SomeNamespace.MyTextBoxDesigner, TestProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=123"")]
public class MyTextBox { }
}");
}
[Theory]
[WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
[WorkItem(1708, "https://github.com/dotnet/roslyn-analyzers/issues/1708")]
[InlineData("System.ComponentModel.DesignerAttribute")]
[InlineData("System.Diagnostics.DebuggerTypeProxyAttribute")]
public async Task CA1812_DesignerAttributeGlobalTypeName_NoDiagnosticAsync(string attributeFullName)
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
internal class MyTextBoxDesigner { }
[" + attributeFullName + @"(""MyTextBoxDesigner, TestProject"")]
public class MyTextBox { }");
}
[Theory]
[WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
[WorkItem(1708, "https://github.com/dotnet/roslyn-analyzers/issues/1708")]
[InlineData("System.ComponentModel.DesignerAttribute")]
[InlineData("System.Diagnostics.DebuggerTypeProxyAttribute")]
public async Task CA1812_DesignerAttributeType_NoDiagnosticAsync(string attributeFullName)
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
namespace SomeNamespace
{
internal class MyTextBoxDesigner { }
[" + attributeFullName + @"(typeof(MyTextBoxDesigner))]
public class MyTextBox { }
}");
}
[Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
public async Task CA1812_DesignerAttributeTypeNameWithBaseTypeName_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
namespace SomeNamespace
{
public class SomeBaseType { }
internal class MyTextBoxDesigner { }
[Designer(""SomeNamespace.MyTextBoxDesigner, TestProject"", ""SomeNamespace.SomeBaseType"")]
public class MyTextBox { }
}");
}
[Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
public async Task CA1812_DesignerAttributeTypeNameWithBaseType_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
namespace SomeNamespace
{
public class SomeBaseType { }
internal class MyTextBoxDesigner { }
[Designer(""SomeNamespace.MyTextBoxDesigner, TestProject"", typeof(SomeBaseType))]
public class MyTextBox { }
}");
}
[Fact, WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
public async Task CA1812_DesignerAttributeTypeWithBaseType_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
namespace SomeNamespace
{
public class SomeBaseType { }
internal class MyTextBoxDesigner { }
[Designer(typeof(SomeNamespace.MyTextBoxDesigner), typeof(SomeBaseType))]
public class MyTextBox { }
}");
}
[Theory]
[WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
[WorkItem(1708, "https://github.com/dotnet/roslyn-analyzers/issues/1708")]
[InlineData("System.ComponentModel.DesignerAttribute")]
[InlineData("System.Diagnostics.DebuggerTypeProxyAttribute")]
public async Task CA1812_DesignerAttributeNestedTypeName_NoDiagnosticAsync(string attributeFullName)
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
namespace SomeNamespace
{
[" + attributeFullName + @"(""SomeNamespace.MyTextBox.MyTextBoxDesigner, TestProject"")]
public class MyTextBox
{
internal class MyTextBoxDesigner { }
}
}",
// False-Positive: when evaluating the string of the DesignerAttribute the type symbol doesn't exist yet
GetCSharpResultAt(10, 24, "MyTextBox.MyTextBoxDesigner"));
}
[Theory]
[WorkItem(2957, "https://github.com/dotnet/roslyn-analyzers/issues/2957")]
[WorkItem(1708, "https://github.com/dotnet/roslyn-analyzers/issues/1708")]
[InlineData("System.ComponentModel.DesignerAttribute")]
[InlineData("System.Diagnostics.DebuggerTypeProxyAttribute")]
public async Task CA1812_DesignerAttributeNestedType_NoDiagnosticAsync(string attributeFullName)
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.ComponentModel;
namespace SomeNamespace
{
[" + attributeFullName + @"(typeof(SomeNamespace.MyTextBox.MyTextBoxDesigner))]
public class MyTextBox
{
internal class MyTextBoxDesigner { }
}
}");
}
[Fact, WorkItem(3199, "https://github.com/dotnet/roslyn-analyzers/issues/3199")]
public async Task CA1812_AliasingTypeNewConstraint_NoDiagnosticAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
using System;
namespace SomeNamespace
{
public class MyAliasType<T>
where T : class, new()
{
public static void DoSomething() {}
}
internal class C {}
}",
@"
using MyAliasOfC = SomeNamespace.MyAliasType<SomeNamespace.C>;
using MyAliasOfMyAliasOfC = SomeNamespace.MyAliasType<SomeNamespace.MyAliasType<SomeNamespace.C>>;
public class CC
{
public void M()
{
MyAliasOfC.DoSomething();
MyAliasOfMyAliasOfC.DoSomething();
}
}
",
},
},
}.RunAsync();
}
[Fact, WorkItem(1878, "https://github.com/dotnet/roslyn-analyzers/issues/1878")]
public async Task CA1812_VisualBasic_StaticLikeClass_NoDiagnosticAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Friend NotInheritable Class C1
Private Sub New()
End Sub
Public Shared Function GetSomething(o As Object) As String
Return o.ToString()
End Function
End Class
Public Class Helpers
Private NotInheritable Class C2
Private Sub New()
End Sub
Public Shared Function GetSomething(o As Object) As String
Return o.ToString()
End Function
End Class
End Class
Friend NotInheritable Class C3
Private Const SomeConstant As String = ""Value""
Private Shared f As Integer
Private Sub New()
End Sub
Public Shared Sub M()
End Sub
Public Shared Property P As Integer
Public Shared Event ThresholdReached As EventHandler
End Class
Friend Class C4
Private Sub New()
End Sub
Public Shared Function GetSomething(o As Object) As String
Return o.ToString()
End Function
End Class
Friend NotInheritable Class C5
Public Sub New()
End Sub
Public Shared Function GetSomething(o As Object) As String
Return o.ToString()
End Function
End Class");
}
[Fact, WorkItem(1878, "https://github.com/dotnet/roslyn-analyzers/issues/1878")]
public async Task CA1812_VisualBasic_NotStaticLikeClass_DiagnosticAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Friend NotInheritable Class [|C1|]
Private Sub New()
End Sub
Public Function GetSomething(o As Object) As String
Return o.ToString()
End Function
End Class");
}
[Fact, WorkItem(4052, "https://github.com/dotnet/roslyn-analyzers/issues/4052")]
public async Task CA1812_CSharp_TopLevelStatements_NoDiagnosticAsync()
{
await new VerifyCS.Test()
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
TestState =
{
OutputKind = OutputKind.ConsoleApplication,
Sources =
{
@"int x = 0;",
},
},
}.RunAsync();
}
private static DiagnosticResult GetCSharpResultAt(int line, int column, string className)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(className);
private static DiagnosticResult GetBasicResultAt(int line, int column, string className)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(className);
}
}
| |
//
// Alert.cs
//
// Author:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2015 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Mono.Security.Interface
{
#region Enumerations
public enum AlertLevel : byte
{
Warning = 1,
Fatal = 2
}
public enum AlertDescription : byte
{
CloseNotify = 0,
UnexpectedMessage = 10,
BadRecordMAC = 20,
DecryptionFailed_RESERVED = 21,
RecordOverflow = 22,
DecompressionFailure = 30,
HandshakeFailure = 40,
NoCertificate_RESERVED = 41, // should be used in SSL3
BadCertificate = 42,
UnsupportedCertificate = 43,
CertificateRevoked = 44,
CertificateExpired = 45,
CertificateUnknown = 46,
IlegalParameter = 47,
UnknownCA = 48,
AccessDenied = 49,
DecodeError = 50,
DecryptError = 51,
ExportRestriction = 60,
ProtocolVersion = 70,
InsuficientSecurity = 71,
InternalError = 80,
UserCancelled = 90,
NoRenegotiation = 100,
UnsupportedExtension = 110
}
#endregion
public class Alert
{
#region Fields
private AlertLevel level;
private AlertDescription description;
#endregion
#region Properties
public AlertLevel Level
{
get { return this.level; }
}
public AlertDescription Description
{
get { return this.description; }
}
public string Message
{
get { return Alert.GetAlertMessage(this.description); }
}
public bool IsWarning
{
get { return this.level == AlertLevel.Warning ? true : false; }
}
/*
public bool IsFatal
{
get { return this.level == AlertLevel.Fatal ? true : false; }
}
*/
public bool IsCloseNotify
{
get
{
if (this.IsWarning &&
this.description == AlertDescription.CloseNotify)
{
return true;
}
return false;
}
}
#endregion
#region Constructors
public Alert(AlertDescription description)
{
this.description = description;
this.inferAlertLevel();
}
public Alert(
AlertLevel level,
AlertDescription description)
{
this.level = level;
this.description = description;
}
#endregion
#region Private Methods
private void inferAlertLevel()
{
switch (description)
{
case AlertDescription.CloseNotify:
case AlertDescription.NoRenegotiation:
case AlertDescription.UserCancelled:
this.level = AlertLevel.Warning;
break;
case AlertDescription.AccessDenied:
case AlertDescription.BadCertificate:
case AlertDescription.BadRecordMAC:
case AlertDescription.CertificateExpired:
case AlertDescription.CertificateRevoked:
case AlertDescription.CertificateUnknown:
case AlertDescription.DecodeError:
case AlertDescription.DecompressionFailure:
case AlertDescription.DecryptError:
case AlertDescription.DecryptionFailed_RESERVED:
case AlertDescription.ExportRestriction:
case AlertDescription.HandshakeFailure:
case AlertDescription.IlegalParameter:
case AlertDescription.InsuficientSecurity:
case AlertDescription.InternalError:
case AlertDescription.ProtocolVersion:
case AlertDescription.RecordOverflow:
case AlertDescription.UnexpectedMessage:
case AlertDescription.UnknownCA:
case AlertDescription.UnsupportedCertificate:
case AlertDescription.UnsupportedExtension:
default:
this.level = AlertLevel.Fatal;
break;
}
}
#endregion
public override string ToString ()
{
return string.Format ("[Alert: {0}:{1}]", Level, Description);
}
#region Static Methods
public static string GetAlertMessage(AlertDescription description)
{
#if (DEBUG)
switch (description)
{
case AlertDescription.AccessDenied:
return "An inappropriate message was received.";
case AlertDescription.BadCertificate:
return "TLSCiphertext decrypted in an invalid way.";
case AlertDescription.BadRecordMAC:
return "Record with an incorrect MAC.";
case AlertDescription.CertificateExpired:
return "Certificate has expired or is not currently valid";
case AlertDescription.CertificateRevoked:
return "Certificate was revoked by its signer.";
case AlertDescription.CertificateUnknown:
return "Certificate Unknown.";
case AlertDescription.CloseNotify:
return "Connection closed";
case AlertDescription.DecodeError:
return "A message could not be decoded because some field was out of the specified range or the length of the message was incorrect.";
case AlertDescription.DecompressionFailure:
return "The decompression function received improper input (e.g. data that would expand to excessive length).";
case AlertDescription.DecryptError:
return "TLSCiphertext decrypted in an invalid way: either it wasn`t an even multiple of the block length or its padding values, when checked, weren`t correct.";
case AlertDescription.DecryptionFailed_RESERVED:
return "Handshake cryptographic operation failed, including being unable to correctly verify a signature, decrypt a key exchange, or validate finished message.";
case AlertDescription.ExportRestriction:
return "Negotiation not in compliance with export restrictions was detected.";
case AlertDescription.HandshakeFailure:
return "Unable to negotiate an acceptable set of security parameters given the options available.";
case AlertDescription.IlegalParameter:
return "A field in the handshake was out of range or inconsistent with other fields.";
case AlertDescription.InsuficientSecurity:
return "Negotiation has failed specifically because the server requires ciphers more secure than those supported by the client.";
case AlertDescription.InternalError:
return "Internal error unrelated to the peer or the correctness of the protocol makes it impossible to continue.";
case AlertDescription.NoRenegotiation:
return "Invalid renegotiation.";
case AlertDescription.ProtocolVersion:
return "Unsupported protocol version.";
case AlertDescription.RecordOverflow:
return "Invalid length on TLSCiphertext record or TLSCompressed record.";
case AlertDescription.UnexpectedMessage:
return "Invalid message received.";
case AlertDescription.UnknownCA:
return "CA can't be identified as a trusted CA.";
case AlertDescription.UnsupportedCertificate:
return "Certificate was of an unsupported type.";
case AlertDescription.UserCancelled:
return "Handshake cancelled by user.";
case AlertDescription.UnsupportedExtension:
return "Unsupported extension.";
default:
return "";
}
#else
return "The authentication or decryption has failed.";
#endif
}
#endregion
}
}
| |
/*
* Copyright 2012-2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using System.Text;
namespace Aerospike.Client
{
/// <summary>
/// User privilege.
/// </summary>
public sealed class Privilege
{
/// <summary>
/// Privilege code.
/// </summary>
public PrivilegeCode code;
/// <summary>
/// Namespace scope. Apply permission to this namespace only.
/// If namespace is null, the privilege applies to all namespaces.
/// </summary>
public string ns;
/// <summary>
/// Set name scope. Apply permission to this set within namespace only.
/// If set is null, the privilege applies to all sets within namespace.
/// </summary>
public string setName;
/// <summary>
/// Can privilege be scoped with namespace and set.
/// </summary>
public bool CanScope()
{
return code >= PrivilegeCode.READ;
}
/// <summary>
/// Privilege code property.
/// </summary>
public PrivilegeCode Code
{
get {return code;}
set {code = value;}
}
/// <summary>
/// Privilege code property.
/// </summary>
public string CodeString
{
get { return PrivilegeCodeToString(); }
}
/// <summary>
/// Namespace property.
/// </summary>
public string Namespace
{
get { return ns; }
set { ns = value; }
}
/// <summary>
/// SetName property.
/// </summary>
public string SetName
{
get { return setName; }
set { setName = value; }
}
/// <summary>
/// Return privilege shallow clone.
/// </summary>
public Privilege Clone()
{
Privilege priv = new Privilege();
priv.code = this.code;
priv.ns = this.ns;
priv.setName = this.setName;
return priv;
}
/// <summary>
/// Return if privileges are equal.
/// </summary>
public override bool Equals(object obj)
{
Privilege other = (Privilege)obj;
if (this.code != other.code)
{
return false;
}
if (this.ns == null)
{
if (other.ns != null)
{
return false;
}
}
else if (other.ns == null)
{
return false;
}
else if (!this.ns.Equals(other.ns))
{
return false;
}
if (this.setName == null)
{
if (other.setName != null)
{
return false;
}
}
else if (other.setName == null)
{
return false;
}
else if (!this.setName.Equals(other.setName))
{
return false;
}
return true;
}
/// <summary>
/// Return privilege hashcode.
/// </summary>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Convert privilege to string.
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder(100);
sb.Append(PrivilegeCodeToString());
if (ns != null && ns.Length > 0)
{
sb.Append('.');
sb.Append(ns);
}
if (setName != null && setName.Length > 0)
{
sb.Append('.');
sb.Append(setName);
}
return sb.ToString();
}
/// <summary>
/// Convert privilege code to string.
/// </summary>
public string PrivilegeCodeToString()
{
switch (code)
{
case PrivilegeCode.SYS_ADMIN:
return Role.SysAdmin;
case PrivilegeCode.USER_ADMIN:
return Role.UserAdmin;
case PrivilegeCode.DATA_ADMIN:
return Role.DataAdmin;
case PrivilegeCode.READ:
return Role.Read;
case PrivilegeCode.READ_WRITE:
return Role.ReadWrite;
case PrivilegeCode.READ_WRITE_UDF:
return Role.ReadWriteUdf;
default:
throw new AerospikeException(ResultCode.PARAMETER_ERROR, "Invalid privilege code: " + code);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using FlubuCore.Context;
using FlubuCore.Infrastructure;
using FlubuCore.Scripting;
using FlubuCore.Tasks.Attributes;
using FlubuCore.Tasks.Solution.VSSolutionBrowsing;
using Microsoft.Build.Framework;
using Task = System.Threading.Tasks.Task;
namespace FlubuCore.Tasks
{
/// <summary>
/// A base abstract class from which tasks can be implemented.
/// </summary>
public abstract class TaskBase<TResult, TTask> : TaskCore, ITaskOfT<TResult, TTask>
where TTask : class, ITask
{
private static object _logLockObj = new object();
private readonly List<(Expression<Func<TTask, object>> Member, string ArgKey, string consoleText, bool includeParameterlessMethodByDefault, bool interactive)> _forMembers = new List<(Expression<Func<TTask, object>> Member, string ArgKey, string consoleText, bool includeParameterlessMethodByDefault, bool interactive)>();
private int _retriedTimes;
private string _taskName;
private bool _cleanUpOnCancel = false;
private Action<ITaskContext> _finallyAction;
private Action<ITaskContext, Exception> _onErrorAction;
private Func<ITaskContext, Exception, bool> _retryCondition;
private Func<ITaskContext, Exception, bool> _doNotFailCondition;
private Action<Exception> _doNotFailOnErrorAction;
private List<string> _sequentialLogs;
protected TaskExecutionMode TaskExecutionMode { get; private set; }
internal List<(string argumentKey, string help)> ArgumentHelp { get; } = new List<(string argumentKey, string help)>();
public override string TaskName
{
get
{
if (!string.IsNullOrEmpty(_taskName))
{
return _taskName;
}
var type = typeof(TTask);
return type.Name;
}
protected internal set => _taskName = value;
}
/// <summary>
/// Stopwatch for timings.
/// </summary>
internal Stopwatch TaskStopwatch { get; } = new Stopwatch();
protected abstract string Description { get; set; }
/// <summary>
/// Should the task fail if an error occurs.
/// </summary>
protected bool DoNotFail { get; private set; }
/// <summary>
/// Do retry if set to true.
/// </summary>
protected bool DoRetry { get; private set; }
/// <summary>
/// Delay in ms between retries.
/// </summary>
protected int RetryDelay { get; private set; }
/// <summary>
/// Task context. It will be set after the execute method.
/// </summary>
protected ITaskContext Context { get; private set; }
/// <summary>
/// Sets the tasks log level.
/// </summary>
protected LogLevel TaskLogLevel { get; private set; } = LogLevel.Info;
/// <summary>
/// Number of retries in case of an exception.
/// </summary>
protected int NumberOfRetries { get; private set; }
/// <summary>
/// Gets a value indicating whether the duration of the task should be logged after the task
/// has finished.
/// </summary>
/// <value><c>true</c> if duration should be logged; otherwise, <c>false</c>.</value>
protected virtual bool LogDuration { get; set; } = false;
/// <inheritdoc />
[DisableForMember]
public TTask DoNotFailOnError(Action<Exception> doNotFailOnErrorAction = null, Func<ITaskContext, Exception, bool> condition = null)
{
DoNotFail = true;
_doNotFailOnErrorAction = doNotFailOnErrorAction;
_doNotFailCondition = condition;
return this as TTask;
}
[DisableForMember]
public TTask Finally(Action<ITaskContext> finallyAction, bool cleanupOnCancel = false)
{
_finallyAction = finallyAction;
_cleanUpOnCancel = cleanupOnCancel;
return this as TTask;
}
[DisableForMember]
public TTask OnError(Action<ITaskContext, Exception> onErrorAction)
{
_onErrorAction = onErrorAction;
return this as TTask;
}
[DisableForMember]
public TTask When(Func<bool> condition, Action<TTask> taskAction)
{
var task = this as TTask;
var conditionMeet = condition?.Invoke() ?? true;
if (conditionMeet)
{
taskAction.Invoke(task);
}
return task;
}
/// <inheritdoc />
[Obsolete("Use `WithLogLevel(LogLevel.None)` instead")]
public TTask NoLog()
{
TaskLogLevel = LogLevel.None;
return this as TTask;
}
/// <inheritdoc />
public TTask WithLogLevel(LogLevel logLevel)
{
TaskLogLevel = logLevel;
return this as TTask;
}
[DisableForMember]
public TTask ForMember(Expression<Func<TTask, object>> taskMember, string argKey, string help = null, bool includeParameterlessMethodByDefault = true)
{
string key = argKey.TrimStart('-');
_forMembers.Add((taskMember, key, null, includeParameterlessMethodByDefault, false));
if (!string.IsNullOrEmpty(help))
{
ArgumentHelp.Add((argKey, help));
}
else
{
GetDefaultArgumentHelp(taskMember, argKey);
}
return this as TTask;
}
[DisableForMember]
public TTask Interactive(Expression<Func<TTask, object>> taskMember, string argKey = null, string consoleText = null, string argHelp = null)
{
string key = null;
if (argKey != null)
{
key = argKey.TrimStart('-');
}
else
{
key = GetDefaultArgKeyFromMethodName(taskMember, key);
}
if (!string.IsNullOrEmpty(argHelp))
{
ArgumentHelp.Add((key, argHelp));
}
else
{
GetDefaultArgumentHelp(taskMember, argKey);
}
if (consoleText == null)
{
consoleText = $"Enter value for parameter '{key}': ";
}
_forMembers.Add((taskMember, key, consoleText, false, true));
return this as TTask;
}
/// <inheritdoc />
/// <summary>
/// </summary>
/// <param name="numberOfRetries">Number of retries before task fails.</param>
/// <param name="delay">Delay time in miliseconds between retries.</param>
/// <param name="condition">Condition when retry will occur. If condition is null task is always retried. </param>
/// <returns></returns>
public TTask Retry(int numberOfRetries, int delay = 500, Func<ITaskContext, Exception, bool> condition = null)
{
DoRetry = true;
NumberOfRetries = numberOfRetries;
RetryDelay = delay;
_retryCondition = condition;
return this as TTask;
}
[DisableForMember]
public TTask SetDescription(string description)
{
Description = description;
return this as TTask;
}
public TTask LogTaskDuration()
{
LogDuration = true;
return this as TTask;
}
public TTask DoNotLogTaskExecutionInfo()
{
LogTaskExecutionInfo = false;
return this as TTask;
}
/// <inheritdoc />
[DisableForMember]
public void ExecuteVoid(ITaskContext context)
{
Execute(context);
}
/// <inheritdoc />
[DisableForMember]
public async Task ExecuteVoidAsync(ITaskContext context)
{
await ExecuteAsync(context);
}
/// <inheritdoc />
/// <summary>
/// Executes the task using the specified script execution environment.
/// </summary>
/// <remarks>
/// This method implements the basic reporting and error handling for
/// classes which inherit the <see>
/// <cref>TaskBase</cref>
/// </see>
/// class.
/// </remarks>
/// <param name="context">The script execution environment.</param>
[DisableForMember]
public TResult Execute(ITaskContext context)
{
Context = context ?? throw new ArgumentNullException(nameof(context));
ITaskContextInternal contextInternal = (ITaskContextInternal)context;
TaskExecutionMode = TaskExecutionMode.Sync;
_sequentialLogs = new List<string>();
TaskExecuted = true;
if (!IsTarget && LogTaskExecutionInfo)
{
contextInternal.DecreaseDepth();
LogSequentially($"Executing task {TaskName}", Color.DimGray);
contextInternal.IncreaseDepth();
}
if (_cleanUpOnCancel)
{
CleanUpStore.AddCleanupAction(_finallyAction);
}
TaskStopwatch.Start();
try
{
if (contextInternal.Args.DryRun)
{
return default(TResult);
}
InvokeForMembers(_forMembers, contextInternal.Args.DisableInteractive);
var result = DoExecute(contextInternal);
TaskStatus = TaskStatus.Succeeded;
return result;
}
catch (Exception ex)
{
TaskStatus = TaskStatus.Failed;
_onErrorAction?.Invoke(Context, ex);
var shouldRetry = _retryCondition == null || _retryCondition.Invoke(Context, ex);
if (!shouldRetry && DoNotFail)
{
var shouldFail = _doNotFailCondition != null && !_doNotFailCondition.Invoke(Context, ex);
if (shouldFail)
{
throw;
}
contextInternal.LogInfo(
$"Task didn't complete succesfully. Continuing with task execution as parameter DoNotFail was set on this task. Exception: {ex.Message}");
_doNotFailOnErrorAction?.Invoke(ex);
TaskStatus = TaskStatus.Succeeded;
return default(TResult);
}
if (!DoRetry)
{
if (DoNotFail)
{
var shouldFail = _doNotFailCondition != null && !_doNotFailCondition.Invoke(Context, ex);
if (shouldFail)
{
throw;
}
contextInternal.LogInfo(
$"Task didn't complete succesfully. Continuing with task execution as parameter DoNotFail was set on this task. Exception: {ex.Message}");
_doNotFailOnErrorAction?.Invoke(ex);
TaskStatus = TaskStatus.Succeeded;
return default(TResult);
}
throw;
}
else
{
if (!shouldRetry && !DoNotFail)
{
throw;
}
}
while (_retriedTimes < NumberOfRetries)
{
TaskStatus = TaskStatus.NotRan;
_retriedTimes++;
contextInternal.LogInfo($"Task failed: {ex.Message}");
DoLogInfo($"Retriying for {_retriedTimes} time(s). Number of all retries {NumberOfRetries}.");
Thread.Sleep(RetryDelay);
return Execute(context);
}
if (DoNotFail)
{
var shouldFail = _doNotFailCondition != null && !_doNotFailCondition.Invoke(Context, ex);
if (shouldFail)
{
throw;
}
contextInternal.LogInfo(
$"Task didn't complete succesfully. Continuing with task execution as parameter DoNotFail was set on this task. Exception: {ex.Message}");
_doNotFailOnErrorAction?.Invoke(ex);
TaskStatus = TaskStatus.Succeeded;
return default(TResult);
}
throw;
}
finally
{
if (!CleanUpStore.StoreAccessed)
{
if (_cleanUpOnCancel)
{
CleanUpStore.RemoveCleanupAction(_finallyAction);
}
_finallyAction?.Invoke(context);
TaskStopwatch.Stop();
LogFinishedStatus();
LogSequentialLogs(Context);
if (TaskStatus == TaskStatus.Failed && IsTarget)
{
contextInternal.DecreaseDepth();
}
}
}
}
/// <inheritdoc />
[DisableForMember]
public async Task<TResult> ExecuteAsync(ITaskContext context)
{
Context = context ?? throw new ArgumentNullException(nameof(context));
TaskExecutionMode = TaskExecutionMode.Async;
_sequentialLogs = new List<string>();
TaskExecuted = true;
ITaskContextInternal contextInternal = (ITaskContextInternal)context;
if (!IsTarget && LogTaskExecutionInfo)
{
contextInternal.DecreaseDepth();
LogSequentially($"Executing task '{TaskName}' asynchronous.", Color.DimGray);
contextInternal.IncreaseDepth();
}
TaskStopwatch.Start();
if (_cleanUpOnCancel)
{
CleanUpStore.AddCleanupAction(_finallyAction);
}
try
{
if (contextInternal.Args.DryRun)
{
return default(TResult);
}
InvokeForMembers(_forMembers, contextInternal.Args.DisableInteractive);
var result = await DoExecuteAsync(contextInternal);
TaskStatus = TaskStatus.Succeeded;
return result;
}
catch (Exception ex)
{
TaskStatus = TaskStatus.Failed;
_onErrorAction?.Invoke(Context, ex);
var shouldRetry = _retryCondition == null || _retryCondition.Invoke(Context, ex);
if (!shouldRetry && DoNotFail)
{
var shouldFail = _doNotFailCondition != null && !_doNotFailCondition.Invoke(Context, ex);
if (shouldFail)
{
throw;
}
DoLogInfo($"Task didn't complete succesfully. Continuing with task execution as parameter DoNotFail was set on this task. Exception: {ex.Message}");
_doNotFailOnErrorAction?.Invoke(ex);
TaskStatus = TaskStatus.Succeeded;
return default(TResult);
}
if (!DoRetry)
{
if (DoNotFail)
{
var shouldFail = _doNotFailCondition != null && !_doNotFailCondition.Invoke(Context, ex);
if (shouldFail)
{
throw;
}
DoLogInfo($"Task didn't complete succesfully. Continuing with task execution as parameter DoNotFail was set on this task. Exception: {ex.Message}");
_doNotFailOnErrorAction?.Invoke(ex);
TaskStatus = TaskStatus.Succeeded;
return default(TResult);
}
throw;
}
else
{
if (!shouldRetry && !DoNotFail)
{
throw;
}
}
while (_retriedTimes < NumberOfRetries)
{
_retriedTimes++;
contextInternal.LogInfo($"Task failed: {ex.Message}");
DoLogInfo($"Retriying for {_retriedTimes} time(s). Number of all retries {NumberOfRetries}.");
await Task.Delay(RetryDelay);
TaskStatus = TaskStatus.NotRan;
return await ExecuteAsync(context);
}
if (DoNotFail)
{
var shouldFail = _doNotFailCondition != null && !_doNotFailCondition.Invoke(Context, ex);
if (shouldFail)
{
throw;
}
DoLogInfo($"Task didn't complete succesfully. Continuing with task execution as parameter DoNotFail was set on this task. Exception: {ex.Message}");
_doNotFailOnErrorAction?.Invoke(ex);
TaskStatus = TaskStatus.Succeeded;
return default(TResult);
}
throw;
}
finally
{
if (!CleanUpStore.StoreAccessed)
{
if (_cleanUpOnCancel)
{
CleanUpStore.RemoveCleanupAction(_finallyAction);
}
_finallyAction?.Invoke(context);
}
TaskStopwatch.Stop();
LogFinishedStatus();
LogSequentialLogs(Context);
if (TaskStatus == TaskStatus.Failed && IsTarget)
{
contextInternal.DecreaseDepth();
}
}
}
internal void LogFinishedStatus()
{
var statusMessage = StatusMessage();
var duration = TaskStatus == TaskStatus.Succeeded || TaskStatus == TaskStatus.Failed
? $"(took {(int)TaskStopwatch.Elapsed.TotalSeconds} seconds)"
: string.Empty;
if (LogDuration)
{
DoLogInfo($"{TaskName} {statusMessage} {duration}", Color.DimGray);
}
}
protected internal override void LogTaskHelp(ITaskContext context)
{
context.LogInfo(" ");
context.LogInfo(string.Empty);
context.LogInfo($" {TaskName.Capitalize()}: {Description}");
if (ArgumentHelp == null || ArgumentHelp.Count <= 0)
{
return;
}
context.LogInfo(string.Empty);
context.LogInfo(" Task arguments:");
context.LogInfo(" ");
foreach (var argument in ArgumentHelp)
{
context.LogInfo($" -{argument.argumentKey} {argument.help}");
}
}
/// <summary>
/// Abstract method defining the actual work for a task.
/// </summary>
/// <remarks>This method has to be implemented by the inheriting task.</remarks>
/// <param name="context">The script execution environment.</param>
protected abstract TResult DoExecute(ITaskContextInternal context);
/// <summary>
/// Virtual method defining the actual work for a task.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
protected virtual async Task<TResult> DoExecuteAsync(ITaskContextInternal context)
{
return await Task.Run(() => DoExecute(context));
}
/// <summary>
/// Log info if task logging is not disabled.
/// </summary>
/// <param name="message"></param>
protected void DoLogInfo(string message)
{
if (TaskLogLevel < LogLevel.Info)
return;
LogSequentially(message);
}
/// <summary>
/// Log info if task logging is not disabled.
/// </summary>
/// <param name="message"></param>
protected void DoLogInfo(string message, Color foregroundColor)
{
if (TaskLogLevel < LogLevel.Info)
return;
LogSequentially(message, foregroundColor);
}
protected void LogSequentially(string message, Color foregroundColor)
{
if (SequentialLogging)
{
_sequentialLogs.Add(message);
}
else
{
Context.LogInfo(message, foregroundColor);
}
}
/// <summary>
/// Log error if task logging is not disabled.
/// </summary>
/// <param name="message"></param>
protected void DoLogError(string message)
{
if (TaskLogLevel < LogLevel.Error)
return;
LogErrorSequentially(message);
}
/// <summary>
/// Log error if task logging is not disabled.
/// </summary>
/// <param name="message"></param>
protected void DoLogError(string message, Color foregroundColor)
{
if (TaskLogLevel < LogLevel.Error)
return;
if (SequentialLogging)
{
_sequentialLogs.Add(message);
}
else
{
Context.LogError(message, foregroundColor);
}
}
protected void LogSequentially(string message)
{
if (SequentialLogging)
{
_sequentialLogs.Add(message);
}
else
{
Context.LogInfo(message);
}
}
protected void LogErrorSequentially(string message)
{
if (SequentialLogging)
{
_sequentialLogs.Add(message);
}
else
{
Context.LogError(message);
}
}
protected VSSolution GetRequiredVSSolution()
{
var solution = Context.Properties.TryGet<VSSolution>(BuildProps.Solution);
if (solution == null)
{
throw new KeyNotFoundException($"Task context property VsSolution must be set for task {TaskName}. Execute LoadSolutionTask before this task.");
}
return solution;
}
private void InvokeForMembers(List<(Expression<Func<TTask, object>> Member, string ArgKey, string consoleText, bool includeParameterlessMethodByDefault, bool interactive)> members, bool disableInteractive)
{
if (members.Count == 0)
{
return;
}
foreach (var member in members)
{
var memberExpression = GetMemberExpression(member.Member);
if (memberExpression != null)
{
PassArgumentValueToProperty(member, memberExpression, disableInteractive);
continue;
}
var methodCallExpression = member.Member.Body as MethodCallExpression;
if (methodCallExpression == null)
{
continue;
}
PassArgumentValueToMethodParameter(member, methodCallExpression, disableInteractive);
}
}
private void PassArgumentValueToMethodParameter((Expression<Func<TTask, object>> Member, string ArgKey, string consoleText, bool includeParameterlessMethodByDefault, bool interactive) forMember, MethodCallExpression methodCallExpression, bool disableInteractive)
{
var attribute = methodCallExpression.Method.GetCustomAttribute<DisableForMemberAttribute>();
if (attribute != null)
{
throw new TaskExecutionException($"ForMember is not allowed on method '{methodCallExpression.Method.Name}'.", 20);
}
if (!Context.ScriptArgs.ContainsKey(forMember.ArgKey) && (!forMember.interactive || disableInteractive))
{
if (methodCallExpression.Arguments.Count == 0 && !forMember.includeParameterlessMethodByDefault)
{
return;
}
forMember.Member.Compile().Invoke(this as TTask);
return;
}
string argumentValue = Context.ScriptArgs[forMember.ArgKey];
if (string.IsNullOrEmpty(argumentValue) && forMember.interactive)
{
if (!disableInteractive)
{
Console.Write(forMember.consoleText);
argumentValue = Console.ReadLine();
}
}
try
{
if (methodCallExpression.Arguments.Count == 0)
{
if (string.IsNullOrEmpty(argumentValue))
{
forMember.Member.Compile().Invoke(this as TTask);
return;
}
var succeded = bool.TryParse(argumentValue, out var boolValue);
if (succeded)
{
if (boolValue)
{
forMember.Member.Compile().Invoke(this as TTask);
}
}
else
{
if (forMember.includeParameterlessMethodByDefault)
{
forMember.Member.Compile().Invoke(this as TTask);
}
}
return;
}
MethodParameterModifier parameterModifier = new MethodParameterModifier();
var newExpression = (Expression<Func<TTask, object>>)parameterModifier.Modify(forMember.Member, new List<string> { argumentValue });
newExpression.Compile().Invoke(this as TTask);
}
catch (FormatException e)
{
var methodInfo = ((MethodCallExpression)forMember.Member.Body).Method;
var parameters = methodInfo.GetParameters().ToList();
if (parameters.Count == 1)
{
throw new TaskExecutionException(
$"Parameter '{parameters[0].ParameterType.Name} {parameters[0].Name}' in method '{methodInfo.Name}' can not be modified with value '{argumentValue}' from argument '-{forMember.ArgKey}'.",
21,
e);
}
}
}
private void PassArgumentValueToProperty(
(Expression<Func<TTask, object>> Member, string ArgKey, string consoleText, bool
includeParameterlessMethodByDefault, bool Interactive) forMember, MemberExpression memberExpression,
bool disableInteractive)
{
var attribute = memberExpression.Member.GetCustomAttribute<DisableForMemberAttribute>();
if (attribute != null)
{
throw new TaskExecutionException(
$"ForMember is not allowed on property '{memberExpression.Member.Name}'.", 20);
}
if (!Context.ScriptArgs.ContainsKey(forMember.ArgKey) && (!forMember.Interactive || disableInteractive))
{
return;
}
string value = Context.ScriptArgs[forMember.ArgKey];
if (string.IsNullOrEmpty(value) && forMember.Interactive)
{
if (!disableInteractive)
{
Console.Write(forMember.consoleText);
value = Console.ReadLine();
}
}
var propertyInfo = (PropertyInfo)memberExpression.Member;
try
{
object parsedValue = MethodParameterModifier.ParseValueByType(value, propertyInfo.PropertyType);
propertyInfo.SetValue(this, parsedValue, null);
}
catch (FormatException e)
{
throw new ScriptException(
$"Property '{propertyInfo.Name}' can not be modified with value '{value}' from argument '-{forMember.ArgKey}'.",
e);
}
catch (ArgumentException e)
{
throw new ScriptException(
$"Property '{propertyInfo.Name}' can not be modified with value '{value}' from argument '-{forMember.ArgKey}'.",
e);
}
}
internal MemberExpression GetMemberExpression(Expression<Func<TTask, object>> exp)
{
var member = exp.Body as MemberExpression;
var unary = exp.Body as UnaryExpression;
return member ?? (unary != null ? unary.Operand as MemberExpression : null);
}
internal MemberExpression GetMemberExpression(LambdaExpression exp)
{
var member = exp.Body as MemberExpression;
var unary = exp.Body as UnaryExpression;
return member ?? (unary != null ? unary.Operand as MemberExpression : null);
}
private void GetDefaultArgumentHelp(Expression<Func<TTask, object>> taskMember, string argKey)
{
if (taskMember.Body is MethodCallExpression methodExpression)
{
string defaultValue = methodExpression.Arguments.Count == 1
? $"Default value: '{methodExpression.Arguments[0]}'."
: null;
ArgumentHelp.Add((argKey,
$"Pass argument with key '{argKey}' to method '{methodExpression.Method.Name}'. {defaultValue}"));
}
var propertyExpression = GetMemberExpression(taskMember);
if (propertyExpression != null)
{
ArgumentHelp.Add((argKey,
$"Pass argument with key '{argKey}' to property '{propertyExpression.Member.Name}'."));
}
}
private string GetDefaultArgKeyFromMethodName(Expression<Func<TTask, object>> taskMember, string key)
{
if (taskMember.Body is MethodCallExpression methodExpression)
{
key = methodExpression.Method.Name;
}
var propertyExpression = GetMemberExpression(taskMember);
if (propertyExpression != null)
{
key = propertyExpression.Member.Name;
}
return key;
}
private void LogSequentialLogs(ITaskContext context)
{
if (_sequentialLogs == null || _sequentialLogs.Count == 0)
{
return;
}
lock (_logLockObj)
{
foreach (var log in _sequentialLogs)
{
context.LogInfo(log);
}
}
}
private string StatusMessage()
{
string statusMessage;
switch (TaskStatus)
{
case TaskStatus.Succeeded:
{
statusMessage = "succeeded";
break;
}
case TaskStatus.Failed:
{
statusMessage = "failed";
break;
}
case TaskStatus.Skipped:
{
statusMessage = "skipped";
break;
}
case TaskStatus.NotRan:
{
statusMessage = "not ran";
break;
}
default:
throw new NotSupportedException("Task status not supported.");
}
return statusMessage;
}
}
public abstract class TaskCore
{
public virtual string TaskName { get; protected internal set; }
public TaskStatus TaskStatus { get; protected set; } = TaskStatus.NotRan;
public bool SequentialLogging { get; set; }
public virtual bool IsTarget { get; } = false;
public bool LogTaskExecutionInfo { get; set; } = true;
protected internal bool TaskExecuted { get; set; }
protected internal abstract void LogTaskHelp(ITaskContext context);
}
}
| |
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Aliencube.HtmlHelper.Extended
{
/// <summary>
/// This represents the extension methods entity for the <c>HtmlHelper</c> class.
/// </summary>
public static class HtmlHelperImageActionLinkExtensions
{
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, null, null, null, null);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, object htmlAttributes, object imageAttributes)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, null, null, htmlAttributes, imageAttributes);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, object routeValues)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, null, routeValues, null, null);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, object routeValues, object htmlAttributes, object imageAttributes)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, null, routeValues, htmlAttributes, imageAttributes);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, IDictionary<string, object> htmlAttributes, IDictionary<string, object> imageAttributes)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, null, null, htmlAttributes, imageAttributes);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, IDictionary<string, object> routeValues)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, null, routeValues, null, null);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, IDictionary<string, object> routeValues, IDictionary<string, object> htmlAttributes, IDictionary<string, object> imageAttributes)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, null, routeValues, htmlAttributes, imageAttributes);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, controllerName, null, null, null);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName, object htmlAttributes, object imageAttributes)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, controllerName, null, htmlAttributes, imageAttributes);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName, object routeValues)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, controllerName, routeValues, null, null);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName, object routeValues, object htmlAttributes, object imageAttributes)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
var actionLink = htmlHelper.ActionLink(".", actionName, controllerName, routeValues, htmlAttributes);
var image = htmlHelper.Image(src, imageAttributes);
return new MvcHtmlString(actionLink.ToHtmlString().Replace(">.</a>", ">" + image.ToHtmlString() + "</a>"));
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName, IDictionary<string, object> htmlAttributes, IDictionary<string, object> imageAttributes)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, controllerName, null, htmlAttributes, imageAttributes);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName, IDictionary<string, object> routeValues)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
return ImageActionLink(htmlHelper, src, actionName, controllerName, routeValues, null, null);
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName, IDictionary<string, object> routeValues, IDictionary<string, object> htmlAttributes, IDictionary<string, object> imageAttributes)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
var actionLink = htmlHelper.ActionLink(".", actionName, controllerName, routeValues, htmlAttributes);
var image = htmlHelper.Image(src, imageAttributes);
return new MvcHtmlString(actionLink.ToHtmlString().Replace(">.</a>", ">" + image.ToHtmlString() + "</a>"));
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <param name="protocol">HTTP protocal.</param>
/// <param name="hostName">Hostname.</param>
/// <param name="fragment">URL fragment - anchor name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName, string protocol, string hostName, string fragment, object routeValues, object htmlAttributes, object imageAttributes = null)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
if (String.IsNullOrWhiteSpace(protocol))
{
throw new ArgumentNullException("protocol");
}
if (String.IsNullOrWhiteSpace(hostName))
{
throw new ArgumentNullException("hostName");
}
if (String.IsNullOrWhiteSpace(fragment))
{
throw new ArgumentNullException("fragment");
}
var actionLink = htmlHelper.ActionLink(".", actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes);
var image = htmlHelper.Image(src, imageAttributes);
return new MvcHtmlString(actionLink.ToHtmlString().Replace(">.</a>", ">" + image.ToHtmlString() + "</a>"));
}
/// <summary>
/// Renders the action link containing image.
/// </summary>
/// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param>
/// <param name="src">Image file location.</param>
/// <param name="actionName">MVC action name.</param>
/// <param name="controllerName">MVC controller name.</param>
/// <param name="protocol">HTTP protocal.</param>
/// <param name="hostName">Hostname.</param>
/// <param name="fragment">URL fragment - anchor name.</param>
/// <param name="routeValues">List of the route values.</param>
/// <param name="htmlAttributes">List of attributes used for the {a} tag.</param>
/// <param name="imageAttributes">List of attributes used for the {img} tag.</param>
/// <returns>Returns the action link containing image.</returns>
public static MvcHtmlString ImageActionLink(this System.Web.Mvc.HtmlHelper htmlHelper, string src, string actionName, string controllerName, string protocol, string hostName, string fragment, IDictionary<string, object> routeValues, IDictionary<string, object> htmlAttributes, IDictionary<string, object> imageAttributes = null)
{
if (String.IsNullOrWhiteSpace(src))
{
throw new ArgumentNullException("src");
}
if (String.IsNullOrWhiteSpace(actionName))
{
throw new ArgumentNullException("actionName");
}
if (String.IsNullOrWhiteSpace(protocol))
{
throw new ArgumentNullException("protocol");
}
if (String.IsNullOrWhiteSpace(hostName))
{
throw new ArgumentNullException("hostName");
}
if (String.IsNullOrWhiteSpace(fragment))
{
throw new ArgumentNullException("fragment");
}
var actionLink = htmlHelper.ActionLink(".", actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes);
var image = htmlHelper.Image(src, imageAttributes);
return new MvcHtmlString(actionLink.ToHtmlString().Replace(">.</a>", ">" + image.ToHtmlString() + "</a>"));
}
}
}
| |
/***************************************************************************
* MultiData.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id: MultiData.cs 644 2010-12-23 09:18:45Z asayre $
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections;
using System.IO;
namespace Server
{
public static class MultiData
{
private static MultiComponentList[] m_Components;
private static FileStream m_Index, m_Stream;
private static BinaryReader m_IndexReader, m_StreamReader;
public static MultiComponentList GetComponents( int multiID )
{
MultiComponentList mcl;
if ( multiID >= 0 && multiID < m_Components.Length )
{
mcl = m_Components[multiID];
if ( mcl == null )
m_Components[multiID] = mcl = Load( multiID );
}
else
{
mcl = MultiComponentList.Empty;
}
return mcl;
}
public static MultiComponentList Load( int multiID )
{
try
{
m_IndexReader.BaseStream.Seek( multiID * 12, SeekOrigin.Begin );
int lookup = m_IndexReader.ReadInt32();
int length = m_IndexReader.ReadInt32();
if ( lookup < 0 || length <= 0 )
return MultiComponentList.Empty;
m_StreamReader.BaseStream.Seek( lookup, SeekOrigin.Begin );
return new MultiComponentList( m_StreamReader, length / ( MultiComponentList.PostHSFormat ? 16 : 12 ) );
}
catch
{
return MultiComponentList.Empty;
}
}
static MultiData()
{
string idxPath = Core.FindDataFile( "multi.idx" );
string mulPath = Core.FindDataFile( "multi.mul" );
if ( File.Exists( idxPath ) && File.Exists( mulPath ) )
{
m_Index = new FileStream( idxPath, FileMode.Open, FileAccess.Read, FileShare.Read );
m_IndexReader = new BinaryReader( m_Index );
m_Stream = new FileStream( mulPath, FileMode.Open, FileAccess.Read, FileShare.Read );
m_StreamReader = new BinaryReader( m_Stream );
m_Components = new MultiComponentList[(int)(m_Index.Length / 12)];
string vdPath = Core.FindDataFile( "verdata.mul" );
if ( File.Exists( vdPath ) )
{
using ( FileStream fs = new FileStream( vdPath, FileMode.Open, FileAccess.Read, FileShare.Read ) )
{
BinaryReader bin = new BinaryReader( fs );
int count = bin.ReadInt32();
for ( int i = 0; i < count; ++i )
{
int file = bin.ReadInt32();
int index = bin.ReadInt32();
int lookup = bin.ReadInt32();
int length = bin.ReadInt32();
int extra = bin.ReadInt32();
if ( file == 14 && index >= 0 && index < m_Components.Length && lookup >= 0 && length > 0 )
{
bin.BaseStream.Seek( lookup, SeekOrigin.Begin );
m_Components[index] = new MultiComponentList( bin, length / 12 );
bin.BaseStream.Seek( 24 + (i * 20), SeekOrigin.Begin );
}
}
bin.Close();
}
}
}
else
{
Console.WriteLine( "Warning: Multi data files not found" );
m_Components = new MultiComponentList[0];
}
}
}
public struct MultiTileEntry
{
public ushort m_ItemID;
public short m_OffsetX, m_OffsetY, m_OffsetZ;
public int m_Flags;
public MultiTileEntry( ushort itemID, short xOffset, short yOffset, short zOffset, int flags )
{
m_ItemID = itemID;
m_OffsetX = xOffset;
m_OffsetY = yOffset;
m_OffsetZ = zOffset;
m_Flags = flags;
}
}
public sealed class MultiComponentList
{
public static bool PostHSFormat {
get { return _PostHSFormat; }
set { _PostHSFormat = value; }
}
private static bool _PostHSFormat = false;
private Point2D m_Min, m_Max, m_Center;
private int m_Width, m_Height;
private StaticTile[][][] m_Tiles;
private MultiTileEntry[] m_List;
public static readonly MultiComponentList Empty = new MultiComponentList();
public Point2D Min{ get{ return m_Min; } }
public Point2D Max{ get{ return m_Max; } }
public Point2D Center{ get{ return m_Center; } }
public int Width{ get{ return m_Width; } }
public int Height{ get{ return m_Height; } }
public StaticTile[][][] Tiles{ get{ return m_Tiles; } }
public MultiTileEntry[] List{ get{ return m_List; } }
public void Add( int itemID, int x, int y, int z )
{
int vx = x + m_Center.m_X;
int vy = y + m_Center.m_Y;
if ( vx >= 0 && vx < m_Width && vy >= 0 && vy < m_Height )
{
StaticTile[] oldTiles = m_Tiles[vx][vy];
for ( int i = oldTiles.Length - 1; i >= 0; --i )
{
ItemData data = TileData.ItemTable[itemID & TileData.MaxItemValue];
if ( oldTiles[i].Z == z && (oldTiles[i].Height > 0 == data.Height > 0 ) )
{
bool newIsRoof = ( data.Flags & TileFlag.Roof) != 0;
bool oldIsRoof = (TileData.ItemTable[oldTiles[i].ID & TileData.MaxItemValue].Flags & TileFlag.Roof ) != 0;
if ( newIsRoof == oldIsRoof )
Remove( oldTiles[i].ID, x, y, z );
}
}
oldTiles = m_Tiles[vx][vy];
StaticTile[] newTiles = new StaticTile[oldTiles.Length + 1];
for ( int i = 0; i < oldTiles.Length; ++i )
newTiles[i] = oldTiles[i];
newTiles[oldTiles.Length] = new StaticTile( (ushort)itemID, (sbyte)z );
m_Tiles[vx][vy] = newTiles;
MultiTileEntry[] oldList = m_List;
MultiTileEntry[] newList = new MultiTileEntry[oldList.Length + 1];
for ( int i = 0; i < oldList.Length; ++i )
newList[i] = oldList[i];
newList[oldList.Length] = new MultiTileEntry( (ushort)itemID, (short)x, (short)y, (short)z, 1 );
m_List = newList;
if ( x < m_Min.m_X )
m_Min.m_X = x;
if ( y < m_Min.m_Y )
m_Min.m_Y = y;
if ( x > m_Max.m_X )
m_Max.m_X = x;
if ( y > m_Max.m_Y )
m_Max.m_Y = y;
}
}
public void RemoveXYZH( int x, int y, int z, int minHeight )
{
int vx = x + m_Center.m_X;
int vy = y + m_Center.m_Y;
if ( vx >= 0 && vx < m_Width && vy >= 0 && vy < m_Height )
{
StaticTile[] oldTiles = m_Tiles[vx][vy];
for ( int i = 0; i < oldTiles.Length; ++i )
{
StaticTile tile = oldTiles[i];
if ( tile.Z == z && tile.Height >= minHeight )
{
StaticTile[] newTiles = new StaticTile[oldTiles.Length - 1];
for ( int j = 0; j < i; ++j )
newTiles[j] = oldTiles[j];
for ( int j = i + 1; j < oldTiles.Length; ++j )
newTiles[j - 1] = oldTiles[j];
m_Tiles[vx][vy] = newTiles;
break;
}
}
MultiTileEntry[] oldList = m_List;
for ( int i = 0; i < oldList.Length; ++i )
{
MultiTileEntry tile = oldList[i];
if ( tile.m_OffsetX == (short)x && tile.m_OffsetY == (short)y && tile.m_OffsetZ == (short)z && TileData.ItemTable[tile.m_ItemID & TileData.MaxItemValue].Height >= minHeight )
{
MultiTileEntry[] newList = new MultiTileEntry[oldList.Length - 1];
for ( int j = 0; j < i; ++j )
newList[j] = oldList[j];
for ( int j = i + 1; j < oldList.Length; ++j )
newList[j - 1] = oldList[j];
m_List = newList;
break;
}
}
}
}
public void Remove( int itemID, int x, int y, int z )
{
int vx = x + m_Center.m_X;
int vy = y + m_Center.m_Y;
if ( vx >= 0 && vx < m_Width && vy >= 0 && vy < m_Height )
{
StaticTile[] oldTiles = m_Tiles[vx][vy];
for ( int i = 0; i < oldTiles.Length; ++i )
{
StaticTile tile = oldTiles[i];
if ( tile.ID == itemID && tile.Z == z )
{
StaticTile[] newTiles = new StaticTile[oldTiles.Length - 1];
for ( int j = 0; j < i; ++j )
newTiles[j] = oldTiles[j];
for ( int j = i + 1; j < oldTiles.Length; ++j )
newTiles[j - 1] = oldTiles[j];
m_Tiles[vx][vy] = newTiles;
break;
}
}
MultiTileEntry[] oldList = m_List;
for ( int i = 0; i < oldList.Length; ++i )
{
MultiTileEntry tile = oldList[i];
if ( tile.m_ItemID == itemID && tile.m_OffsetX == (short)x && tile.m_OffsetY == (short)y && tile.m_OffsetZ == (short)z )
{
MultiTileEntry[] newList = new MultiTileEntry[oldList.Length - 1];
for ( int j = 0; j < i; ++j )
newList[j] = oldList[j];
for ( int j = i + 1; j < oldList.Length; ++j )
newList[j - 1] = oldList[j];
m_List = newList;
break;
}
}
}
}
public void Resize( int newWidth, int newHeight )
{
int oldWidth = m_Width, oldHeight = m_Height;
StaticTile[][][] oldTiles = m_Tiles;
int totalLength = 0;
StaticTile[][][] newTiles = new StaticTile[newWidth][][];
for ( int x = 0; x < newWidth; ++x )
{
newTiles[x] = new StaticTile[newHeight][];
for ( int y = 0; y < newHeight; ++y )
{
if ( x < oldWidth && y < oldHeight )
newTiles[x][y] = oldTiles[x][y];
else
newTiles[x][y] = new StaticTile[0];
totalLength += newTiles[x][y].Length;
}
}
m_Tiles = newTiles;
m_List = new MultiTileEntry[totalLength];
m_Width = newWidth;
m_Height = newHeight;
m_Min = Point2D.Zero;
m_Max = Point2D.Zero;
int index = 0;
for ( int x = 0; x < newWidth; ++x )
{
for ( int y = 0; y < newHeight; ++y )
{
StaticTile[] tiles = newTiles[x][y];
for ( int i = 0; i < tiles.Length; ++i )
{
StaticTile tile = tiles[i];
int vx = x - m_Center.X;
int vy = y - m_Center.Y;
if ( vx < m_Min.m_X )
m_Min.m_X = vx;
if ( vy < m_Min.m_Y )
m_Min.m_Y = vy;
if ( vx > m_Max.m_X )
m_Max.m_X = vx;
if ( vy > m_Max.m_Y )
m_Max.m_Y = vy;
m_List[index++] = new MultiTileEntry( (ushort)tile.ID, (short)vx, (short)vy, (short)tile.Z, 1 );
}
}
}
}
public MultiComponentList( MultiComponentList toCopy )
{
m_Min = toCopy.m_Min;
m_Max = toCopy.m_Max;
m_Center = toCopy.m_Center;
m_Width = toCopy.m_Width;
m_Height = toCopy.m_Height;
m_Tiles = new StaticTile[m_Width][][];
for ( int x = 0; x < m_Width; ++x )
{
m_Tiles[x] = new StaticTile[m_Height][];
for ( int y = 0; y < m_Height; ++y )
{
m_Tiles[x][y] = new StaticTile[toCopy.m_Tiles[x][y].Length];
for ( int i = 0; i < m_Tiles[x][y].Length; ++i )
m_Tiles[x][y][i] = toCopy.m_Tiles[x][y][i];
}
}
m_List = new MultiTileEntry[toCopy.m_List.Length];
for ( int i = 0; i < m_List.Length; ++i )
m_List[i] = toCopy.m_List[i];
}
public void Serialize( GenericWriter writer )
{
writer.Write( (int) 1 ); // version;
writer.Write( m_Min );
writer.Write( m_Max );
writer.Write( m_Center );
writer.Write( (int) m_Width );
writer.Write( (int) m_Height );
writer.Write( (int) m_List.Length );
for ( int i = 0; i < m_List.Length; ++i )
{
MultiTileEntry ent = m_List[i];
writer.Write( (ushort) ent.m_ItemID );
writer.Write( (short) ent.m_OffsetX );
writer.Write( (short) ent.m_OffsetY );
writer.Write( (short) ent.m_OffsetZ );
writer.Write( (int) ent.m_Flags );
}
}
public MultiComponentList( GenericReader reader )
{
int version = reader.ReadInt();
m_Min = reader.ReadPoint2D();
m_Max = reader.ReadPoint2D();
m_Center = reader.ReadPoint2D();
m_Width = reader.ReadInt();
m_Height = reader.ReadInt();
int length = reader.ReadInt();
MultiTileEntry[] allTiles = m_List = new MultiTileEntry[length];
if ( version == 0 ) {
for ( int i = 0; i < length; ++i )
{
int id = reader.ReadShort();
if ( id >= 0x4000 )
id -= 0x4000;
allTiles[i].m_ItemID = (ushort)id;
allTiles[i].m_OffsetX = reader.ReadShort();
allTiles[i].m_OffsetY = reader.ReadShort();
allTiles[i].m_OffsetZ = reader.ReadShort();
allTiles[i].m_Flags = reader.ReadInt();
}
} else {
for ( int i = 0; i < length; ++i )
{
allTiles[i].m_ItemID = reader.ReadUShort();
allTiles[i].m_OffsetX = reader.ReadShort();
allTiles[i].m_OffsetY = reader.ReadShort();
allTiles[i].m_OffsetZ = reader.ReadShort();
allTiles[i].m_Flags = reader.ReadInt();
}
}
TileList[][] tiles = new TileList[m_Width][];
m_Tiles = new StaticTile[m_Width][][];
for ( int x = 0; x < m_Width; ++x )
{
tiles[x] = new TileList[m_Height];
m_Tiles[x] = new StaticTile[m_Height][];
for ( int y = 0; y < m_Height; ++y )
tiles[x][y] = new TileList();
}
for ( int i = 0; i < allTiles.Length; ++i )
{
if ( i == 0 || allTiles[i].m_Flags != 0 )
{
int xOffset = allTiles[i].m_OffsetX + m_Center.m_X;
int yOffset = allTiles[i].m_OffsetY + m_Center.m_Y;
tiles[xOffset][yOffset].Add( (ushort)allTiles[i].m_ItemID, (sbyte)allTiles[i].m_OffsetZ );
}
}
for ( int x = 0; x < m_Width; ++x )
for ( int y = 0; y < m_Height; ++y )
m_Tiles[x][y] = tiles[x][y].ToArray();
}
public MultiComponentList( BinaryReader reader, int count )
{
MultiTileEntry[] allTiles = m_List = new MultiTileEntry[count];
for ( int i = 0; i < count; ++i )
{
allTiles[i].m_ItemID = reader.ReadUInt16();
allTiles[i].m_OffsetX = reader.ReadInt16();
allTiles[i].m_OffsetY = reader.ReadInt16();
allTiles[i].m_OffsetZ = reader.ReadInt16();
allTiles[i].m_Flags = reader.ReadInt32();
if ( _PostHSFormat )
reader.ReadInt32(); // ??
MultiTileEntry e = allTiles[i];
if ( i == 0 || e.m_Flags != 0 )
{
if ( e.m_OffsetX < m_Min.m_X )
m_Min.m_X = e.m_OffsetX;
if ( e.m_OffsetY < m_Min.m_Y )
m_Min.m_Y = e.m_OffsetY;
if ( e.m_OffsetX > m_Max.m_X )
m_Max.m_X = e.m_OffsetX;
if ( e.m_OffsetY > m_Max.m_Y )
m_Max.m_Y = e.m_OffsetY;
}
}
m_Center = new Point2D( -m_Min.m_X, -m_Min.m_Y );
m_Width = (m_Max.m_X - m_Min.m_X) + 1;
m_Height = (m_Max.m_Y - m_Min.m_Y) + 1;
TileList[][] tiles = new TileList[m_Width][];
m_Tiles = new StaticTile[m_Width][][];
for ( int x = 0; x < m_Width; ++x )
{
tiles[x] = new TileList[m_Height];
m_Tiles[x] = new StaticTile[m_Height][];
for ( int y = 0; y < m_Height; ++y )
tiles[x][y] = new TileList();
}
for ( int i = 0; i < allTiles.Length; ++i )
{
if ( i == 0 || allTiles[i].m_Flags != 0 )
{
int xOffset = allTiles[i].m_OffsetX + m_Center.m_X;
int yOffset = allTiles[i].m_OffsetY + m_Center.m_Y;
tiles[xOffset][yOffset].Add( (ushort)allTiles[i].m_ItemID, (sbyte)allTiles[i].m_OffsetZ );
}
}
for ( int x = 0; x < m_Width; ++x )
for ( int y = 0; y < m_Height; ++y )
m_Tiles[x][y] = tiles[x][y].ToArray();
}
private MultiComponentList()
{
m_Tiles = new StaticTile[0][][];
m_List = new MultiTileEntry[0];
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ScreenManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace GameStateManagement
{
/// <summary>
/// The screen manager is a component which manages one or more GameScreen
/// instances. It maintains a stack of screens, calls their Update and Draw
/// methods at the appropriate times, and automatically routes input to the
/// topmost active screen.
/// </summary>
public class ScreenManager : DrawableGameComponent
{
#region Fields
List<GameScreen> screens = new List<GameScreen>();
List<GameScreen> screensToUpdate = new List<GameScreen>();
InputState input = new InputState();
SpriteBatch spriteBatch;
SpriteFont font;
Texture2D blankTexture;
bool isInitialized;
bool traceEnabled;
#endregion
#region Properties
/// <summary>
/// A default SpriteBatch shared by all the screens. This saves
/// each screen having to bother creating their own local instance.
/// </summary>
public SpriteBatch SpriteBatch
{
get { return spriteBatch; }
}
/// <summary>
/// A default font shared by all the screens. This saves
/// each screen having to bother loading their own local copy.
/// </summary>
public SpriteFont Font
{
get { return font; }
}
/// <summary>
/// If true, the manager prints out a list of all the screens
/// each time it is updated. This can be useful for making sure
/// everything is being added and removed at the right times.
/// </summary>
public bool TraceEnabled
{
get { return traceEnabled; }
set { traceEnabled = value; }
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new screen manager component.
/// </summary>
public ScreenManager(Game game)
: base(game)
{
}
/// <summary>
/// Initializes the screen manager component.
/// </summary>
public override void Initialize()
{
base.Initialize();
isInitialized = true;
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
// Load content belonging to the screen manager.
ContentManager content = Game.Content;
spriteBatch = new SpriteBatch(GraphicsDevice);
font = content.Load<SpriteFont>("Fonts/menufont");
blankTexture = content.Load<Texture2D>("Images/blank");
// Tell each of the screens to load their content.
foreach (GameScreen screen in screens)
{
screen.LoadContent();
}
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
// Tell each of the screens to unload their content.
foreach (GameScreen screen in screens)
{
screen.UnloadContent();
}
}
#endregion
#region Update and Draw
/// <summary>
/// Allows each screen to run logic.
/// </summary>
public override void Update(GameTime gameTime)
{
// Read the keyboard and gamepad.
input.Update();
// Make a copy of the master screen list, to avoid confusion if
// the process of updating one screen adds or removes others.
screensToUpdate.Clear();
foreach (GameScreen screen in screens)
screensToUpdate.Add(screen);
bool otherScreenHasFocus = !Game.IsActive;
bool coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (screensToUpdate.Count > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
// Update the screen.
screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (screen.ScreenState == ScreenState.TransitionOn ||
screen.ScreenState == ScreenState.Active)
{
// If this is the first active screen we came across,
// give it a chance to handle input.
if (!otherScreenHasFocus)
{
screen.HandleInput(input);
otherScreenHasFocus = true;
}
// If this is an active non-popup, inform any subsequent
// screens that they are covered by it.
if (!screen.IsPopup)
coveredByOtherScreen = true;
}
}
// Print debug trace?
if (traceEnabled)
TraceScreens();
}
/// <summary>
/// Prints a list of all the screens, for debugging.
/// </summary>
void TraceScreens()
{
List<string> screenNames = new List<string>();
foreach (GameScreen screen in screens)
screenNames.Add(screen.GetType().Name);
#if WINDOWS && DEBUG
Trace.WriteLine(string.Join(", ", screenNames.ToArray()));
#endif
}
/// <summary>
/// Tells each screen to draw itself.
/// </summary>
public override void Draw(GameTime gameTime)
{
foreach (GameScreen screen in screens)
{
if (screen.ScreenState == ScreenState.Hidden)
continue;
screen.Draw(gameTime);
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public void AddScreen(GameScreen screen)
{
screen.ScreenManager = this;
screen.IsExiting = false;
// If we have a graphics device, tell the screen to load content.
if (isInitialized)
{
screen.LoadContent();
}
screens.Add(screen);
}
/// <summary>
/// Removes a screen from the screen manager. You should normally
/// use GameScreen.ExitScreen instead of calling this directly, so
/// the screen can gradually transition off rather than just being
/// instantly removed.
/// </summary>
public void RemoveScreen(GameScreen screen)
{
// If we have a graphics device, tell the screen to unload content.
if (isInitialized)
{
screen.UnloadContent();
}
screens.Remove(screen);
screensToUpdate.Remove(screen);
}
/// <summary>
/// Expose an array holding all the screens. We return a copy rather
/// than the real master list, because screens should only ever be added
/// or removed using the AddScreen and RemoveScreen methods.
/// </summary>
public GameScreen[] GetScreens()
{
return screens.ToArray();
}
/// <summary>
/// Helper draws a translucent black fullscreen sprite, used for fading
/// screens in and out, and for darkening the background behind popups.
/// </summary>
public void FadeBackBufferToBlack(int alpha)
{
Viewport viewport = GraphicsDevice.Viewport;
spriteBatch.Begin();
spriteBatch.Draw(blankTexture,
new Rectangle(0, 0, viewport.Width, viewport.Height),
new Color(0, 0, 0, (byte)alpha));
spriteBatch.End();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using Xunit;
namespace System.Collections.Tests
{
public class Hashtable_CtorTests
{
[Fact]
public void TestCtorDefault()
{
Hashtable hash = null;
int nAttempts = 100;
int[] iIntArray = new int[nAttempts];
//
// [] Constructor: Create Hashtable using default settings.
//
hash = new Hashtable();
Assert.NotNull(hash);
// Verify that the hash tabe is empty.
Assert.Equal(hash.Count, 0);
}
[Fact]
public void TestCtorDictionarySingle()
{
// No exception
var hash = new Hashtable(new Hashtable(), 1f);
// No exception
hash = new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()), 1f), 1f), 1f), 1f);
// []test to see if elements really get copied from old dictionary to new hashtable
Hashtable tempHash = new Hashtable();
// this for assumes that MinValue is a negative!
for (long i = long.MinValue; i < long.MinValue + 100; i++)
{
tempHash.Add(i, i);
}
hash = new Hashtable(tempHash, 1f);
// make sure that new hashtable has the elements in it that old hashtable had
for (long i = long.MinValue; i < long.MinValue + 100; i++)
{
Assert.True(hash.ContainsKey(i));
Assert.True(hash.ContainsValue(i));
}
//[]make sure that there are no connections with the old and the new hashtable
tempHash.Clear();
for (long i = long.MinValue; i < long.MinValue + 100; i++)
{
Assert.True(hash.ContainsKey(i));
Assert.True(hash.ContainsValue(i));
}
}
[Fact]
public void TestCtorDictionarySingleNegative()
{
// variables used for tests
Hashtable hash = null;
Assert.Throws<ArgumentNullException>(() =>
{
hash = new Hashtable(null, 1);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(new Hashtable(), Int32.MinValue);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(new Hashtable(), Single.NaN);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(new Hashtable(), 100.1f);
}
);
}
[Fact]
public void TestCtorDictionary()
{
Hashtable hash = null;
Hashtable hash2 = null;
Int32 i4a;
//
// [] Constructor: null
//
Assert.Throws<ArgumentNullException>(() =>
{
hash = new Hashtable((IDictionary)null);
}
);
//
// []Constructor: empty
//
hash2 = new Hashtable(); //empty dictionary
// No exception
hash = new Hashtable(hash2);
//
// []Constructor: dictionary with 100 entries...
//
hash2 = new Hashtable();
for (int i = 0; i < 100; i++)
{
hash2.Add("key_" + i, "val_" + i);
}
// No exception
hash = new Hashtable(hash2);
//Confirming the values
Hashtable hash3 = new Hashtable(200);
for (int ii = 0; ii < 100; ii++)
{
i4a = ii;
hash3.Add("key_" + ii, i4a);
}
hash = new Hashtable(hash3);
Assert.Equal(100, hash.Count);
for (int ii = 0; ii < 100; ii++)
{
Assert.Equal(ii, (int)hash3["key_" + ii]);
Assert.True(hash3.ContainsKey("key_" + ii));
}
Assert.False(hash3.ContainsKey("key_100"));
}
[Fact]
public void TestCtorIntSingle()
{
// variables used for tests
Hashtable hash = null;
// [] should get ArgumentException if trying to have large num of entries
Assert.Throws<ArgumentException>(() =>
{
hash = new Hashtable(int.MaxValue, .1f);
}
);
// []should not get any exceptions for valid values - we also check that the HT works here
hash = new Hashtable(100, .1f);
int iNumberOfElements = 100;
for (int i = 0; i < iNumberOfElements; i++)
{
hash.Add("Key_" + i, "Value_" + i);
}
//Count
Assert.Equal(hash.Count, iNumberOfElements);
DictionaryEntry[] strValueArr = new DictionaryEntry[hash.Count];
hash.CopyTo(strValueArr, 0);
Hashtable hsh3 = new Hashtable();
for (int i = 0; i < iNumberOfElements; i++)
{
Assert.True(hash.Contains("Key_" + i), "Error, Expected value not returned, " + hash.Contains("Key_" + i));
Assert.True(hash.ContainsKey("Key_" + i), "Error, Expected value not returned, " + hash.ContainsKey("Key_" + i));
Assert.True(hash.ContainsValue("Value_" + i), "Error, Expected value not returned, " + hash.ContainsValue("Value_" + i));
//we still need a way to make sure that there are all these unique values here -see below code for that
Assert.True(hash.ContainsValue(((DictionaryEntry)strValueArr[i]).Value), "Error, Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value);
hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null);
}
}
[Fact]
public void TestCtorIntSingleNegative()
{
Hashtable hash = null;
// []should get ArgumentOutOfRangeException if capacity range is not correct
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(5, .01f);
}
);
// should get ArgumentOutOfRangeException if range is not correct
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(5, 100.1f);
}
);
// should get OutOfMemoryException if Dictionary is null
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(int.MaxValue, 100.1f);
}
);
// []ArgumentOutOfRangeException if capacity is less than zero.
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(int.MinValue, 10.1f);
}
);
}
[Fact]
public void TestCtorIntCapacity()
{
//--------------------------------------------------------------------------
// Variable definitions.
//--------------------------------------------------------------------------
Hashtable hash = null;
int nCapacity = 100;
//
// [] Constructor: Create Hashtable using a capacity value.
//
hash = new Hashtable(nCapacity);
Assert.NotNull(hash);
// Verify that the hash tabe is empty.
Assert.Equal(0, hash.Count);
//
// [] Constructor: Create Hashtablewith zero capacity value - valid.
//
hash = new Hashtable(0);
//
// []Constructor: Create Hashtable using a invalid capacity value.
//
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(-1);
}
);
Assert.Throws<ArgumentException>(() => { hash = new Hashtable(Int32.MaxValue); });
}
[Fact]
public void TestCtorIntFloat()
{
//--------------------------------------------------------------------------
// Variable definitions.
//--------------------------------------------------------------------------
Hashtable hash = null;
int nCapacity = 100;
float fltLoadFactor = (float).5; // Note: default load factor is .73
//
// []Constructor: Create Hashtable using a capacity and load factor.
//
hash = new Hashtable(nCapacity, fltLoadFactor);
Assert.NotNull(hash);
// Verify that the hash tabe is empty.
Assert.Equal(0, hash.Count);
//
// [] Constructor: Create Hashtable using a zero capacity and some load factor.
//
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(-1, fltLoadFactor);
});
//
// [] Constructor: Create Hashtable using a invalid capacity and valid load factor.
//
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(nCapacity, .09f); // min lf allowed is .01
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(nCapacity, 1.1f);
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(-1, -1f);
});
Assert.Throws<OutOfMemoryException>(() =>
{
hash = new Hashtable((int)100000000, .5f);
});
}
[Fact]
public void DebuggerAttributeTests()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new Hashtable() { { "a", 1 }, { "b", 2 } });
}
}
}
| |
using System;
using System.Collections;
using Server;
using Server.Multis;
using Server.Items;
using Server.Mobiles;
namespace Knives.TownHouses
{
public enum Intu{ Neither, No, Yes }
[Flipable( 0xC0B, 0xC0C )]
public class TownHouseSign : Item
{
private static ArrayList s_TownHouseSigns = new ArrayList();
public static ArrayList AllSigns{ get{ return s_TownHouseSigns; } }
private Point3D c_BanLoc, c_SignLoc;
private int c_Locks, c_Secures, c_Price, c_MinZ, c_MaxZ, c_MinTotalSkill, c_MaxTotalSkill, c_ItemsPrice, c_RTOPayments;
private bool c_YoungOnly, c_RecurRent, c_Relock, c_KeepItems, c_LeaveItems, c_RentToOwn, c_Free, c_ForcePrivate, c_ForcePublic, c_NoTrade, c_NoBanning;
private string c_Skill;
private double c_SkillReq;
private ArrayList c_Blocks, c_DecoreItemInfos, c_PreviewItems;
private TownHouse c_House;
private Timer c_DemolishTimer, c_RentTimer, c_PreviewTimer;
private DateTime c_DemolishTime, c_RentTime;
private TimeSpan c_RentByTime, c_OriginalRentTime;
private Intu c_Murderers;
public Point3D BanLoc
{
get{ return c_BanLoc; }
set
{
c_BanLoc = value;
InvalidateProperties();
if ( Owned )
c_House.Region.GoLocation = value;
}
}
public Point3D SignLoc
{
get{ return c_SignLoc; }
set
{
c_SignLoc = value;
InvalidateProperties();
if ( Owned )
{
c_House.Sign.Location = value;
c_House.Hanger.Location = value;
}
}
}
public int Locks
{
get{ return c_Locks; }
set
{
c_Locks = value;
InvalidateProperties();
if ( Owned )
c_House.MaxLockDowns = value;
}
}
public int Secures
{
get{ return c_Secures; }
set
{
c_Secures = value;
InvalidateProperties();
if ( Owned )
c_House.MaxSecures = value;
}
}
public int Price
{
get{ return c_Price; }
set
{
c_Price = value;
InvalidateProperties();
}
}
public int MinZ
{
get{ return c_MinZ; }
set
{
if ( value > c_MaxZ )
c_MaxZ = value+1;
c_MinZ = value;
if (Owned)
RUOVersion.UpdateRegion(this);
}
}
public int MaxZ
{
get{ return c_MaxZ; }
set
{
if ( value < c_MinZ )
value = c_MinZ;
c_MaxZ = value;
if (Owned)
RUOVersion.UpdateRegion(this);
}
}
public int MinTotalSkill
{
get{ return c_MinTotalSkill; }
set
{
if ( value > c_MaxTotalSkill )
value = c_MaxTotalSkill;
c_MinTotalSkill = value;
ValidateOwnership();
InvalidateProperties();
}
}
public int MaxTotalSkill
{
get{ return c_MaxTotalSkill; }
set
{
if ( value < c_MinTotalSkill )
value = c_MinTotalSkill;
c_MaxTotalSkill = value;
ValidateOwnership();
InvalidateProperties();
}
}
public bool YoungOnly
{
get{ return c_YoungOnly; }
set
{
c_YoungOnly = value;
if ( c_YoungOnly )
c_Murderers = Intu.Neither;
ValidateOwnership();
InvalidateProperties();
}
}
public TimeSpan RentByTime
{
get{ return c_RentByTime; }
set
{
c_RentByTime = value;
c_OriginalRentTime = value;
if ( value == TimeSpan.Zero )
ClearRentTimer();
else
{
ClearRentTimer();
BeginRentTimer( value );
}
InvalidateProperties();
}
}
public bool RecurRent
{
get{ return c_RecurRent; }
set
{
c_RecurRent = value;
if ( !value )
c_RentToOwn = value;
InvalidateProperties();
}
}
public bool KeepItems
{
get{ return c_KeepItems; }
set
{
c_LeaveItems = false;
c_KeepItems = value;
InvalidateProperties();
}
}
public bool Free
{
get{ return c_Free; }
set
{
c_Free = value;
c_Price = 1;
InvalidateProperties();
}
}
public Intu Murderers
{
get{ return c_Murderers; }
set
{
c_Murderers = value;
ValidateOwnership();
InvalidateProperties();
}
}
public bool ForcePrivate
{
get { return c_ForcePrivate; }
set
{
c_ForcePrivate = value;
if (value)
{
c_ForcePublic = false;
if (c_House != null)
c_House.Public = false;
}
}
}
public bool ForcePublic
{
get { return c_ForcePublic; }
set
{
c_ForcePublic = value;
if (value)
{
c_ForcePrivate = false;
if (c_House != null)
c_House.Public = true;
}
}
}
public bool NoBanning
{
get { return c_NoBanning; }
set
{
c_NoBanning = value;
if (value && c_House != null)
c_House.Bans.Clear();
}
}
public ArrayList Blocks { get { return c_Blocks; } set { c_Blocks = value; } }
public string Skill { get { return c_Skill; } set { c_Skill = value; ValidateOwnership(); InvalidateProperties(); } }
public double SkillReq { get { return c_SkillReq; } set { c_SkillReq = value; ValidateOwnership(); InvalidateProperties(); } }
public bool LeaveItems{ get{ return c_LeaveItems; } set{ c_LeaveItems = value; InvalidateProperties(); } }
public bool RentToOwn{ get{ return c_RentToOwn; } set{ c_RentToOwn = value; InvalidateProperties(); } }
public bool Relock { get { return c_Relock; } set { c_Relock = value; } }
public bool NoTrade { get { return c_NoTrade; } set { c_NoTrade = value; } }
public int ItemsPrice { get { return c_ItemsPrice; } set { c_ItemsPrice = value; InvalidateProperties(); } }
public TownHouse House{ get{ return c_House; } set{ c_House = value; } }
public Timer DemolishTimer{ get{ return c_DemolishTimer; } }
public DateTime DemolishTime{ get{ return c_DemolishTime; } }
public bool Owned{ get{ return c_House != null && !c_House.Deleted; } }
public int Floors{ get{ return (c_MaxZ-c_MinZ)/20+1; } }
public bool BlocksReady{ get{ return Blocks.Count != 0; } }
public bool FloorsReady{ get{ return ( BlocksReady && MinZ != short.MinValue ); } }
public bool SignReady{ get{ return ( FloorsReady && SignLoc != Point3D.Zero ); } }
public bool BanReady{ get{ return ( SignReady && BanLoc != Point3D.Zero ); } }
public bool LocSecReady{ get{ return ( BanReady && Locks != 0 && Secures != 0 ); } }
public bool ItemsReady{ get{ return LocSecReady; } }
public bool LengthReady{ get{ return ItemsReady; } }
public bool PriceReady{ get{ return ( LengthReady && Price != 0 ); } }
public string PriceType
{
get
{
if ( c_RentByTime == TimeSpan.Zero )
return "Sale";
if ( c_RentByTime == TimeSpan.FromDays( 1 ) )
return "Daily";
if ( c_RentByTime == TimeSpan.FromDays( 7 ) )
return "Weekly";
if ( c_RentByTime == TimeSpan.FromDays( 30 ) )
return "Monthly";
return "Sale";
}
}
public string PriceTypeShort
{
get
{
if ( c_RentByTime == TimeSpan.Zero )
return "Sale";
if ( c_RentByTime == TimeSpan.FromDays( 1 ) )
return "Day";
if ( c_RentByTime == TimeSpan.FromDays( 7 ) )
return "Week";
if ( c_RentByTime == TimeSpan.FromDays( 30 ) )
return "Month";
return "Sale";
}
}
[Constructable]
public TownHouseSign() : base( 0xC0B )
{
Name = "This building is for sale or rent!";
Movable = false;
c_BanLoc = Point3D.Zero;
c_SignLoc = Point3D.Zero;
c_Skill = "";
c_Blocks = new ArrayList();
c_DecoreItemInfos = new ArrayList();
c_PreviewItems = new ArrayList();
c_DemolishTime = DateTime.Now;
c_RentTime = DateTime.Now;
c_RentByTime = TimeSpan.Zero;
c_RecurRent = true;
c_MinZ = short.MinValue;
c_MaxZ = short.MaxValue;
s_TownHouseSigns.Add( this );
}
private void SearchForHouse()
{
foreach( TownHouse house in TownHouse.AllTownHouses )
if (house.ForSaleSign == this )
c_House = house;
}
public void UpdateBlocks()
{
if ( !Owned )
return;
if (c_Blocks.Count == 0)
UnconvertDoors();
RUOVersion.UpdateRegion(this);
ConvertItems(false);
c_House.InitSectorDefinition();
}
public void ShowAreaPreview( Mobile m )
{
ClearPreview();
Point2D point = Point2D.Zero;
ArrayList blocks = new ArrayList();
foreach( Rectangle2D rect in c_Blocks )
for( int x = rect.Start.X; x < rect.End.X; ++x )
for( int y = rect.Start.Y; y < rect.End.Y; ++y )
{
point = new Point2D( x, y );
if ( !blocks.Contains( point ) )
blocks.Add( point );
}
if (blocks.Count > 500)
{
m.SendMessage("Due to size of the area, skipping the preview.");
return;
}
Item item = null;
int avgz = 0;
foreach( Point2D p in blocks )
{
avgz = Map.GetAverageZ(p.X, p.Y);
item = new Item( 0x1766 );
item.Name = "Area Preview";
item.Movable = false;
item.Location = new Point3D( p.X, p.Y, (avgz <= m.Z ? m.Z+2 : avgz+2 ) );
item.Map = Map;
c_PreviewItems.Add( item );
}
c_PreviewTimer = Timer.DelayCall( TimeSpan.FromSeconds( 100 ), new TimerCallback( ClearPreview ) );
}
public void ShowSignPreview()
{
ClearPreview();
Item sign = new Item( 0xBD2 );
sign.Name = "Sign Preview";
sign.Movable = false;
sign.Location = SignLoc;
sign.Map = Map;
c_PreviewItems.Add( sign );
sign = new Item( 0xB98 );
sign.Name = "Sign Preview";
sign.Movable = false;
sign.Location = SignLoc;
sign.Map = Map;
c_PreviewItems.Add( sign );
c_PreviewTimer = Timer.DelayCall( TimeSpan.FromSeconds( 100 ), new TimerCallback( ClearPreview ) );
}
public void ShowBanPreview()
{
ClearPreview();
Item ban = new Item( 0x17EE );
ban.Name = "Ban Loc Preview";
ban.Movable = false;
ban.Location = BanLoc;
ban.Map = Map;
c_PreviewItems.Add( ban );
c_PreviewTimer = Timer.DelayCall( TimeSpan.FromSeconds( 100 ), new TimerCallback( ClearPreview ) );
}
public void ShowFloorsPreview(Mobile m)
{
ClearPreview();
Item item = new Item(0x7BD);
item.Name = "Bottom Floor Preview";
item.Movable = false;
item.Location = m.Location;
item.Z = c_MinZ;
item.Map = Map;
c_PreviewItems.Add(item);
item = new Item(0x7BD);
item.Name = "Top Floor Preview";
item.Movable = false;
item.Location = m.Location;
item.Z = c_MaxZ;
item.Map = Map;
c_PreviewItems.Add(item);
c_PreviewTimer = Timer.DelayCall(TimeSpan.FromSeconds(100), new TimerCallback(ClearPreview));
}
public void ClearPreview()
{
foreach( Item item in new ArrayList( c_PreviewItems ) )
{
c_PreviewItems.Remove( item );
item.Delete();
}
if ( c_PreviewTimer != null )
c_PreviewTimer.Stop();
c_PreviewTimer = null;
}
public void Purchase( Mobile m )
{
Purchase( m, false );
}
public void Purchase( Mobile m, bool sellitems )
{
try
{
if (Owned)
{
m.SendMessage("Someone already owns this house!");
return;
}
if (!PriceReady)
{
m.SendMessage("The setup for this house is not yet complete.");
return;
}
int price = c_Price + (sellitems ? c_ItemsPrice : 0);
if (c_Free)
price = 0;
if (m.AccessLevel == AccessLevel.Player && !Server.Mobiles.Banker.Withdraw(m, price))
{
m.SendMessage("You cannot afford this house.");
return;
}
if (m.AccessLevel == AccessLevel.Player)
m.SendLocalizedMessage(1060398, price.ToString()); // ~1_AMOUNT~ gold has been withdrawn from your bank box.
Visible = false;
int minX = ((Rectangle2D)c_Blocks[0]).Start.X;
int minY = ((Rectangle2D)c_Blocks[0]).Start.Y;
int maxX = ((Rectangle2D)c_Blocks[0]).End.X;
int maxY = ((Rectangle2D)c_Blocks[0]).End.Y;
foreach (Rectangle2D rect in c_Blocks)
{
if (rect.Start.X < minX)
minX = rect.Start.X;
if (rect.Start.Y < minY)
minY = rect.Start.Y;
if (rect.End.X > maxX)
maxX = rect.End.X;
if (rect.End.Y > maxY)
maxY = rect.End.Y;
}
c_House = new TownHouse(m, this, c_Locks, c_Secures);
c_House.Components.Resize( maxX-minX, maxY-minY );
c_House.Components.Add( 0x520, c_House.Components.Width-1, c_House.Components.Height-1, -5 );
c_House.Location = new Point3D(minX, minY, Map.GetAverageZ(minX, minY));
c_House.Map = Map;
c_House.Region.GoLocation = c_BanLoc;
c_House.Sign.Location = c_SignLoc;
c_House.Hanger = new Item(0xB98);
c_House.Hanger.Location = c_SignLoc;
c_House.Hanger.Map = Map;
c_House.Hanger.Movable = false;
if (c_ForcePublic)
c_House.Public = true;
c_House.Price = (RentByTime == TimeSpan.FromDays(0) ? c_Price : 1);
RUOVersion.UpdateRegion(this);
if (c_House.Price == 0)
c_House.Price = 1;
if (c_RentByTime != TimeSpan.Zero)
BeginRentTimer(c_RentByTime);
c_RTOPayments = 1;
HideOtherSigns();
c_DecoreItemInfos = new ArrayList();
ConvertItems(sellitems);
}
catch(Exception e)
{
Errors.Report(String.Format("An error occurred during home purchasing. More information available on the console."));
Console.WriteLine(e.Message);
Console.WriteLine(e.Source);
Console.WriteLine(e.StackTrace);
}
}
private void HideOtherSigns()
{
foreach( Item item in c_House.Sign.GetItemsInRange( 0 ) )
if ( !(item is HouseSign) )
if ( item.ItemID == 0xB95
|| item.ItemID == 0xB96
|| item.ItemID == 0xC43
|| item.ItemID == 0xC44
|| ( item.ItemID > 0xBA3 && item.ItemID < 0xC0E ) )
item.Visible = false;
}
public virtual void ConvertItems( bool keep )
{
if ( c_House == null )
return;
ArrayList items = new ArrayList();
foreach(Rectangle2D rect in c_Blocks)
foreach (Item item in Map.GetItemsInBounds(rect))
if (c_House.Region.Contains(item.Location) && item.RootParent == null && !items.Contains(item))
items.Add(item);
foreach (Item item in new ArrayList(items))
{
if (item is HouseSign
|| item is BaseMulti
|| item is BaseAddon
|| item is AddonComponent
|| item == c_House.Hanger
|| !item.Visible
|| item.IsLockedDown
|| item.IsSecure
|| item.Movable
|| c_PreviewItems.Contains(item))
continue;
if (item is BaseDoor)
ConvertDoor((BaseDoor)item);
else if (!c_LeaveItems)
{
c_DecoreItemInfos.Add(new DecoreItemInfo(item.GetType().ToString(), item.Name, item.ItemID, item.Hue, item.Location, item.Map));
if (!c_KeepItems || !keep)
item.Delete();
else
{
item.Movable = true;
c_House.LockDown(c_House.Owner, item, false);
}
}
}
}
protected void ConvertDoor( BaseDoor door )
{
if ( !Owned )
return;
if ( door is Server.Gumps.ISecurable )
{
door.Locked = false;
c_House.Doors.Add( door );
return;
}
door.Open = false;
GenericHouseDoor newdoor = new GenericHouseDoor( (DoorFacing)0, door.ClosedID, door.OpenedSound, door.ClosedSound );
newdoor.Offset = door.Offset;
newdoor.ClosedID = door.ClosedID;
newdoor.OpenedID = door.OpenedID;
newdoor.Location = door.Location;
newdoor.Map = door.Map;
door.Delete();
foreach( Item inneritem in newdoor.GetItemsInRange( 1 ) )
if ( inneritem is BaseDoor && inneritem != newdoor && inneritem.Z == newdoor.Z )
{
((BaseDoor)inneritem).Link = newdoor;
newdoor.Link = (BaseDoor)inneritem;
}
c_House.Doors.Add(newdoor);
}
public virtual void UnconvertDoors()
{
if ( c_House == null )
return;
BaseDoor newdoor = null;
foreach (BaseDoor door in new ArrayList(c_House.Doors))
{
door.Open = false;
if ( c_Relock )
door.Locked = true;
newdoor = new StrongWoodDoor( (DoorFacing)0 );
newdoor.ItemID = door.ItemID;
newdoor.ClosedID = door.ClosedID;
newdoor.OpenedID = door.OpenedID;
newdoor.OpenedSound = door.OpenedSound;
newdoor.ClosedSound = door.ClosedSound;
newdoor.Offset = door.Offset;
newdoor.Location = door.Location;
newdoor.Map = door.Map;
door.Delete();
foreach( Item inneritem in newdoor.GetItemsInRange( 1 ) )
if ( inneritem is BaseDoor && inneritem != newdoor && inneritem.Z == newdoor.Z )
{
( (BaseDoor)inneritem ).Link = newdoor;
newdoor.Link = (BaseDoor)inneritem;
}
c_House.Doors.Remove( door );
}
}
public void RecreateItems()
{
Item item = null;
foreach( DecoreItemInfo info in c_DecoreItemInfos )
{
item = null;
if ( info.TypeString.ToLower().IndexOf( "static" ) != -1 )
item = new Static( info.ItemID );
else
{
try{
item = Activator.CreateInstance( ScriptCompiler.FindTypeByFullName( info.TypeString ) ) as Item;
}catch{ continue; }
}
if ( item == null )
continue;
item.ItemID = info.ItemID;
item.Name = info.Name;
item.Hue = info.Hue;
item.Location = info.Location;
item.Map = info.Map;
item.Movable = false;
}
}
public virtual void ClearHouse()
{
UnconvertDoors();
ClearDemolishTimer();
ClearRentTimer();
PackUpItems();
RecreateItems();
c_House = null;
Visible = true;
if ( c_RentToOwn )
c_RentByTime = c_OriginalRentTime;
}
public virtual void ValidateOwnership()
{
if ( !Owned )
return;
if ( c_House.Owner == null )
{
c_House.Delete();
return;
}
if ( c_House.Owner.AccessLevel != AccessLevel.Player )
return;
if ( !CanBuyHouse( c_House.Owner ) && c_DemolishTimer == null )
BeginDemolishTimer();
else
ClearDemolishTimer();
}
public int CalcVolume()
{
int floors = 1;
if ( c_MaxZ - c_MinZ < 100 )
floors = 1 + Math.Abs( (c_MaxZ - c_MinZ)/20 );
Point3D point = Point3D.Zero;
ArrayList blocks = new ArrayList();
foreach( Rectangle2D rect in c_Blocks )
for( int x = rect.Start.X; x < rect.End.X; ++x )
for( int y = rect.Start.Y; y < rect.End.Y; ++y )
for( int z = 0; z < floors; z++ )
{
point = new Point3D( x, y, z );
if ( !blocks.Contains( point ) )
blocks.Add( point );
}
return blocks.Count;
}
private void StartTimers()
{
if (c_DemolishTime > DateTime.Now)
BeginDemolishTimer(c_DemolishTime - DateTime.Now);
else if (c_RentByTime != TimeSpan.Zero)
BeginRentTimer(c_RentByTime);
}
#region Demolish
public void ClearDemolishTimer()
{
if ( c_DemolishTimer == null )
return;
c_DemolishTimer.Stop();
c_DemolishTimer = null;
c_DemolishTime = DateTime.Now;
if ( !c_House.Deleted && Owned )
c_House.Owner.SendMessage( "Demolition canceled." );
}
public void CheckDemolishTimer()
{
if ( c_DemolishTimer == null || !Owned )
return;
DemolishAlert();
}
protected void BeginDemolishTimer()
{
BeginDemolishTimer( TimeSpan.FromHours( 24 ) );
}
protected void BeginDemolishTimer( TimeSpan time )
{
if ( !Owned )
return;
c_DemolishTime = DateTime.Now + time;
c_DemolishTimer = Timer.DelayCall( time, new TimerCallback( PackUpHouse ) );
DemolishAlert();
}
protected virtual void DemolishAlert()
{
c_House.Owner.SendMessage( "You no longer meet the requirements for your town house, which will be demolished automatically in {0}:{1}:{2}.", (c_DemolishTime-DateTime.Now).Hours, (c_DemolishTime-DateTime.Now).Minutes, (c_DemolishTime-DateTime.Now).Seconds );
}
protected void PackUpHouse()
{
if ( !Owned || c_House.Deleted )
return;
PackUpItems();
c_House.Owner.BankBox.DropItem( new BankCheck( c_House.Price ) );
c_House.Delete();
}
protected void PackUpItems()
{
if ( c_House == null )
return;
Container bag = new Bag();
bag.Name = "Town House Belongings";
foreach( Item item in new ArrayList( c_House.LockDowns ) )
{
item.IsLockedDown = false;
item.Movable = true;
c_House.LockDowns.Remove( item );
bag.DropItem( item );
}
foreach( SecureInfo info in new ArrayList( c_House.Secures ) )
{
info.Item.IsLockedDown = false;
info.Item.IsSecure = false;
info.Item.Movable = true;
info.Item.SetLastMoved();
c_House.Secures.Remove( info );
bag.DropItem( info.Item );
}
foreach(Rectangle2D rect in c_Blocks)
foreach (Item item in Map.GetItemsInBounds(rect))
{
if (item is HouseSign
|| item is BaseDoor
|| item is BaseMulti
|| item is BaseAddon
|| item is AddonComponent
|| !item.Visible
|| item.IsLockedDown
|| item.IsSecure
|| !item.Movable
|| item.Map != c_House.Map
|| !c_House.Region.Contains(item.Location))
continue;
bag.DropItem(item);
}
if ( bag.Items.Count == 0 )
{
bag.Delete();
return;
}
c_House.Owner.BankBox.DropItem( bag );
}
#endregion
#region Rent
public void ClearRentTimer()
{
if ( c_RentTimer != null )
{
c_RentTimer.Stop();
c_RentTimer = null;
}
c_RentTime = DateTime.Now;
}
private void BeginRentTimer()
{
BeginRentTimer( TimeSpan.FromDays( 1 ) );
}
private void BeginRentTimer( TimeSpan time )
{
if ( !Owned )
return;
c_RentTimer = Timer.DelayCall( time, new TimerCallback( RentDue ) );
c_RentTime = DateTime.Now + time;
}
public void CheckRentTimer()
{
if ( c_RentTimer == null || !Owned )
return;
c_House.Owner.SendMessage( "This rent cycle ends in {0} days, {1}:{2}:{3}.", (c_RentTime-DateTime.Now).Days, (c_RentTime-DateTime.Now).Hours, (c_RentTime-DateTime.Now).Minutes, (c_RentTime-DateTime.Now).Seconds );
}
private void RentDue()
{
if ( !Owned || c_House.Owner == null )
return;
if ( !c_RecurRent )
{
c_House.Owner.SendMessage( "Your town house rental contract has expired, and the bank has once again taken possession." );
PackUpHouse();
return;
}
if ( !c_Free && c_House.Owner.AccessLevel == AccessLevel.Player && !Server.Mobiles.Banker.Withdraw( c_House.Owner, c_Price ) )
{
c_House.Owner.SendMessage( "Since you can not afford the rent, the bank has reclaimed your town house." );
PackUpHouse();
return;
}
if ( !c_Free )
c_House.Owner.SendMessage( "The bank has withdrawn {0} gold rent for your town house.", c_Price );
OnRentPaid();
if ( c_RentToOwn )
{
c_RTOPayments++;
bool complete = false;
if ( c_RentByTime == TimeSpan.FromDays( 1 ) && c_RTOPayments >= 60 )
{
complete = true;
c_House.Price = c_Price*60;
}
if ( c_RentByTime == TimeSpan.FromDays( 7 ) && c_RTOPayments >= 9 )
{
complete = true;
c_House.Price = c_Price*9;
}
if ( c_RentByTime == TimeSpan.FromDays( 30 ) && c_RTOPayments >= 2 )
{
complete = true;
c_House.Price = c_Price*2;
}
if ( complete )
{
c_House.Owner.SendMessage( "You now own your rental home." );
c_RentByTime = TimeSpan.FromDays( 0 );
return;
}
}
BeginRentTimer( c_RentByTime );
}
protected virtual void OnRentPaid()
{
}
public void NextPriceType()
{
if ( c_RentByTime == TimeSpan.Zero )
RentByTime = TimeSpan.FromDays( 1 );
else if ( c_RentByTime == TimeSpan.FromDays( 1 ) )
RentByTime = TimeSpan.FromDays( 7 );
else if ( c_RentByTime == TimeSpan.FromDays( 7 ) )
RentByTime = TimeSpan.FromDays( 30 );
else
RentByTime = TimeSpan.Zero;
}
public void PrevPriceType()
{
if ( c_RentByTime == TimeSpan.Zero )
RentByTime = TimeSpan.FromDays( 30 );
else if ( c_RentByTime == TimeSpan.FromDays( 30 ) )
RentByTime = TimeSpan.FromDays( 7 );
else if ( c_RentByTime == TimeSpan.FromDays( 7 ) )
RentByTime = TimeSpan.FromDays( 1 );
else
RentByTime = TimeSpan.Zero;
}
#endregion
public bool CanBuyHouse( Mobile m )
{
if ( c_Skill != "" )
{
try
{
SkillName index = (SkillName)Enum.Parse( typeof( SkillName ), c_Skill, true );
if ( m.Skills[index].Value < c_SkillReq )
return false;
}
catch
{
return false;
}
}
if ( c_MinTotalSkill != 0 && m.SkillsTotal/10 < c_MinTotalSkill )
return false;
if ( c_MaxTotalSkill != 0 && m.SkillsTotal/10 > c_MaxTotalSkill )
return false;
if ( c_YoungOnly && m.Player && !((PlayerMobile)m).Young )
return false;
if ( c_Murderers == Intu.Yes && m.Kills < 5 )
return false;
if ( c_Murderers == Intu.No && m.Kills >= 5 )
return false;
return true;
}
public override void OnDoubleClick( Mobile m )
{
if ( m.AccessLevel != AccessLevel.Player )
new TownHouseSetupGump( m, this );
else if ( !Visible )
return;
else if ( CanBuyHouse( m ))// && !BaseHouse.HasAccountHouse( m ) )
new TownHouseConfirmGump( m, this );
else
m.SendMessage( "You cannot purchase this house." );
}
public override void Delete()
{
if ( c_House == null || c_House.Deleted )
base.Delete();
else
PublicOverheadMessage( Server.Network.MessageType.Regular, 0x0, true, "You cannot delete this while the home is owned." );
if ( this.Deleted )
s_TownHouseSigns.Remove( this );
}
public override void GetProperties( ObjectPropertyList list )
{
base.GetProperties( list );
if ( c_Free )
list.Add( 1060658, "Price\tFree" );
else if ( c_RentByTime == TimeSpan.Zero )
list.Add( 1060658, "Price\t{0}{1}", c_Price, c_KeepItems ? " (+" + c_ItemsPrice + " for the items)" : "" );
else if ( c_RecurRent )
list.Add( 1060658, "{0}\t{1}\r{2}", PriceType + (c_RentToOwn ? " Rent-to-Own" : " Recurring"), c_Price, c_KeepItems ? " (+" + c_ItemsPrice + " for the items)" : "" );
else
list.Add( 1060658, "One {0}\t{1}{2}", PriceTypeShort, c_Price, c_KeepItems ? " (+" + c_ItemsPrice + " for the items)" : "" );
list.Add( 1060659, "Lockdowns\t{0}", c_Locks );
list.Add( 1060660, "Secures\t{0}", c_Secures );
if ( c_SkillReq != 0.0 )
list.Add( 1060661, "Requires\t{0}", c_SkillReq + " in " + c_Skill );
if ( c_MinTotalSkill != 0 )
list.Add( 1060662, "Requires more than\t{0} total skills", c_MinTotalSkill );
if ( c_MaxTotalSkill != 0 )
list.Add( 1060663, "Requires less than\t{0} total skills", c_MaxTotalSkill );
if ( c_YoungOnly )
list.Add( 1063483, "Must be\tYoung" );
else if ( c_Murderers == Intu.Yes )
list.Add( 1063483, "Must be\ta murderer" );
else if ( c_Murderers == Intu.No )
list.Add( 1063483, "Must be\tinnocent" );
}
public TownHouseSign( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( 13 );
// Version 13
writer.Write(c_ForcePrivate);
writer.Write(c_ForcePublic);
writer.Write(c_NoTrade);
// Version 12
writer.Write( c_Free );
// Version 11
writer.Write( (int)c_Murderers );
// Version 10
writer.Write( c_LeaveItems );
// Version 9
writer.Write( c_RentToOwn );
writer.Write( c_OriginalRentTime );
writer.Write( c_RTOPayments );
// Version 7
writer.WriteItemList( c_PreviewItems, true );
// Version 6
writer.Write( c_ItemsPrice );
writer.Write( c_KeepItems );
// Version 5
writer.Write( c_DecoreItemInfos.Count );
foreach( DecoreItemInfo info in c_DecoreItemInfos )
info.Save( writer );
writer.Write( c_Relock );
// Version 4
writer.Write( c_RecurRent );
writer.Write( c_RentByTime );
writer.Write( c_RentTime );
writer.Write( c_DemolishTime );
writer.Write( c_YoungOnly );
writer.Write( c_MinTotalSkill );
writer.Write( c_MaxTotalSkill );
// Version 3
writer.Write( c_MinZ );
writer.Write( c_MaxZ );
// Version 2
writer.Write( c_House );
// Version 1
writer.Write( c_Price );
writer.Write( c_Locks );
writer.Write( c_Secures );
writer.Write( c_BanLoc );
writer.Write( c_SignLoc );
writer.Write( c_Skill );
writer.Write( c_SkillReq );
writer.Write( c_Blocks.Count );
foreach( Rectangle2D rect in c_Blocks )
writer.Write( rect );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
if (version >= 13)
{
c_ForcePrivate = reader.ReadBool();
c_ForcePublic = reader.ReadBool();
c_NoTrade = reader.ReadBool();
}
if (version >= 12)
c_Free = reader.ReadBool();
if ( version >= 11 )
c_Murderers = (Intu)reader.ReadInt();
if ( version >= 10 )
c_LeaveItems = reader.ReadBool();
if ( version >= 9 )
{
c_RentToOwn = reader.ReadBool();
c_OriginalRentTime = reader.ReadTimeSpan();
c_RTOPayments = reader.ReadInt();
}
c_PreviewItems = new ArrayList();
if ( version >= 7 )
c_PreviewItems = reader.ReadItemList();
if ( version >= 6 )
{
c_ItemsPrice = reader.ReadInt();
c_KeepItems = reader.ReadBool();
}
c_DecoreItemInfos = new ArrayList();
if ( version >= 5 )
{
int decorecount = reader.ReadInt();
DecoreItemInfo info;
for( int i = 0; i < decorecount; ++i )
{
info = new DecoreItemInfo();
info.Load( reader );
c_DecoreItemInfos.Add( info );
}
c_Relock = reader.ReadBool();
}
if ( version >= 4 )
{
c_RecurRent = reader.ReadBool();
c_RentByTime = reader.ReadTimeSpan();
c_RentTime = reader.ReadDateTime();
c_DemolishTime = reader.ReadDateTime();
c_YoungOnly = reader.ReadBool();
c_MinTotalSkill = reader.ReadInt();
c_MaxTotalSkill = reader.ReadInt();
}
if ( version >= 3 )
{
c_MinZ = reader.ReadInt();
c_MaxZ = reader.ReadInt();
}
if ( version >= 2 )
c_House = (TownHouse)reader.ReadItem();
c_Price = reader.ReadInt();
c_Locks = reader.ReadInt();
c_Secures = reader.ReadInt();
c_BanLoc = reader.ReadPoint3D();
c_SignLoc = reader.ReadPoint3D();
c_Skill = reader.ReadString();
c_SkillReq = reader.ReadDouble();
c_Blocks = new ArrayList();
int count = reader.ReadInt();
for ( int i = 0; i < count; ++i )
c_Blocks.Add( reader.ReadRect2D() );
if ( c_RentTime > DateTime.Now )
BeginRentTimer( c_RentTime-DateTime.Now );
Timer.DelayCall(TimeSpan.Zero, new TimerCallback(StartTimers));
ClearPreview();
s_TownHouseSigns.Add( this );
}
}
}
| |
/**
* Couchbase Lite for .NET
*
* Original iOS version by Jens Alfke
* Android Port by Marty Schoch, Traun Leyden
* C# Port by Zack Gramana
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
* Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite
{
/// <summary>An unsaved Couchbase Lite Document Revision.</summary>
/// <remarks>An unsaved Couchbase Lite Document Revision.</remarks>
public sealed class UnsavedRevision : Revision
{
private IDictionary<string, object> properties;
/// <summary>Constructor</summary>
/// <exclude></exclude>
[InterfaceAudience.Private]
protected internal UnsavedRevision(Document document, SavedRevision parentRevision
) : base(document)
{
if (parentRevision == null)
{
parentRevID = null;
}
else
{
parentRevID = parentRevision.GetId();
}
IDictionary<string, object> parentRevisionProperties;
if (parentRevision == null)
{
parentRevisionProperties = null;
}
else
{
parentRevisionProperties = parentRevision.GetProperties();
}
if (parentRevisionProperties == null)
{
properties = new Dictionary<string, object>();
properties.Put("_id", document.GetId());
if (parentRevID != null)
{
properties.Put("_rev", parentRevID);
}
}
else
{
properties = new Dictionary<string, object>(parentRevisionProperties);
}
}
/// <summary>Set whether this revision is a deletion or not (eg, marks doc as deleted)
/// </summary>
[InterfaceAudience.Public]
public void SetIsDeletion(bool isDeletion)
{
if (isDeletion == true)
{
properties.Put("_deleted", true);
}
else
{
Sharpen.Collections.Remove(properties, "_deleted");
}
}
/// <summary>Get the id of the owning document.</summary>
/// <remarks>Get the id of the owning document. In the case of an unsaved revision, may return null.
/// </remarks>
/// <returns></returns>
[InterfaceAudience.Public]
public override string GetId()
{
return null;
}
/// <summary>Set the properties for this revision</summary>
[InterfaceAudience.Public]
public void SetProperties(IDictionary<string, object> properties)
{
this.properties = properties;
}
/// <summary>Saves the new revision to the database.</summary>
/// <remarks>
/// Saves the new revision to the database.
/// This will throw an exception with a 412 error if its parent (the revision it was created from)
/// is not the current revision of the document.
/// Afterwards you should use the returned Revision instead of this object.
/// </remarks>
/// <returns>A new Revision representing the saved form of the revision.</returns>
/// <exception cref="CouchbaseLiteException">CouchbaseLiteException</exception>
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[InterfaceAudience.Public]
public SavedRevision Save()
{
bool allowConflict = false;
return document.PutProperties(properties, parentRevID, allowConflict);
}
/// <summary>
/// A special variant of -save: that always adds the revision, even if its parent is not the
/// current revision of the document.
/// </summary>
/// <remarks>
/// A special variant of -save: that always adds the revision, even if its parent is not the
/// current revision of the document.
/// This can be used to resolve conflicts, or to create them. If you're not certain that's what you
/// want to do, you should use the regular -save: method instead.
/// </remarks>
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[InterfaceAudience.Public]
public SavedRevision Save(bool allowConflict)
{
return document.PutProperties(properties, parentRevID, allowConflict);
}
/// <summary>Deletes any existing attachment with the given name.</summary>
/// <remarks>
/// Deletes any existing attachment with the given name.
/// The attachment will be deleted from the database when the revision is saved.
/// </remarks>
/// <param name="name">The attachment name.</param>
[InterfaceAudience.Public]
public void RemoveAttachment(string name)
{
AddAttachment(null, name);
}
/// <summary>Sets the userProperties of the Revision.</summary>
/// <remarks>
/// Sets the userProperties of the Revision.
/// Set replaces all properties except for those with keys prefixed with '_'.
/// </remarks>
[InterfaceAudience.Public]
public void SetUserProperties(IDictionary<string, object> userProperties)
{
IDictionary<string, object> newProps = new Dictionary<string, object>();
newProps.PutAll(userProperties);
foreach (string key in properties.Keys)
{
if (key.StartsWith("_"))
{
newProps.Put(key, properties.Get(key));
}
}
// Preserve metadata properties
properties = newProps;
}
/// <summary>Sets the attachment with the given name.</summary>
/// <remarks>Sets the attachment with the given name. The Attachment data will be written to the Database when the Revision is saved.
/// </remarks>
/// <param name="name">The name of the Attachment to set.</param>
/// <param name="contentType">The content-type of the Attachment.</param>
/// <param name="contentStream">The Attachment content. The InputStream will be closed after it is no longer needed.
/// </param>
[InterfaceAudience.Public]
public void SetAttachment(string name, string contentType, InputStream contentStream
)
{
Attachment attachment = new Attachment(contentStream, contentType);
AddAttachment(attachment, name);
}
/// <summary>Sets the attachment with the given name.</summary>
/// <remarks>Sets the attachment with the given name. The Attachment data will be written to the Database when the Revision is saved.
/// </remarks>
/// <param name="name">The name of the Attachment to set.</param>
/// <param name="contentType">The content-type of the Attachment.</param>
/// <param name="contentStreamURL">The URL that contains the Attachment content.</param>
[InterfaceAudience.Public]
public void SetAttachment(string name, string contentType, Uri contentStreamURL)
{
try
{
InputStream inputStream = contentStreamURL.OpenStream();
SetAttachment(name, contentType, inputStream);
}
catch (IOException e)
{
Log.E(Database.Tag, "Error opening stream for url: " + contentStreamURL);
throw new RuntimeException(e);
}
}
[InterfaceAudience.Public]
public override IDictionary<string, object> GetProperties()
{
return properties;
}
[InterfaceAudience.Public]
public override SavedRevision GetParent()
{
if (parentRevID == null || parentRevID.Length == 0)
{
return null;
}
return document.GetRevision(parentRevID);
}
[InterfaceAudience.Public]
public override string GetParentId()
{
return parentRevID;
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[InterfaceAudience.Public]
public override IList<SavedRevision> GetRevisionHistory()
{
// (Don't include self in the array, because this revision doesn't really exist yet)
SavedRevision parent = GetParent();
return parent != null ? parent.GetRevisionHistory() : new AList<SavedRevision>();
}
/// <summary>Creates or updates an attachment.</summary>
/// <remarks>
/// Creates or updates an attachment.
/// The attachment data will be written to the database when the revision is saved.
/// </remarks>
/// <param name="attachment">A newly-created Attachment (not yet associated with any revision)
/// </param>
/// <param name="name">The attachment name.</param>
[InterfaceAudience.Private]
internal void AddAttachment(Attachment attachment, string name)
{
IDictionary<string, object> attachments = (IDictionary<string, object>)properties
.Get("_attachments");
if (attachments == null)
{
attachments = new Dictionary<string, object>();
}
attachments.Put(name, attachment);
properties.Put("_attachments", attachments);
if (attachment != null)
{
attachment.SetName(name);
attachment.SetRevision(this);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Cleangorod.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlTypesAssembly.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner willa
// @backupOwner [....]
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common.Utils;
using System.Data.Spatial;
using System.Data.SqlClient.Internal;
using System.Diagnostics;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Data.SqlClient
{
internal static class Expressions
{
internal static Expression Null<TNullType>()
{
return Expression.Constant(null, typeof(TNullType));
}
internal static Expression Null(Type nullType)
{
return Expression.Constant(null, nullType);
}
internal static Expression<Func<TArg, TResult>> Lambda<TArg, TResult>(string argumentName, Func<ParameterExpression, Expression> createLambdaBodyGivenParameter)
{
ParameterExpression argParam = Expression.Parameter(typeof(TArg), argumentName);
Expression lambdaBody = createLambdaBodyGivenParameter(argParam);
return Expression.Lambda<Func<TArg, TResult>>(lambdaBody, argParam);
}
internal static Expression Call(this Expression exp, string methodName)
{
return Expression.Call(exp, methodName, Type.EmptyTypes);
}
internal static Expression ConvertTo(this Expression exp, Type convertToType)
{
return Expression.Convert(exp, convertToType);
}
internal static Expression ConvertTo<TConvertToType>(this Expression exp)
{
return Expression.Convert(exp, typeof(TConvertToType));
}
internal sealed class ConditionalExpressionBuilder
{
private readonly Expression condition;
private readonly Expression ifTrueThen;
internal ConditionalExpressionBuilder(Expression conditionExpression, Expression ifTrueExpression)
{
this.condition = conditionExpression;
this.ifTrueThen = ifTrueExpression;
}
internal Expression Else(Expression resultIfFalse)
{
return Expression.Condition(this.condition, ifTrueThen, resultIfFalse);
}
}
internal static ConditionalExpressionBuilder IfTrueThen(this Expression conditionExp, Expression resultIfTrue)
{
return new ConditionalExpressionBuilder(conditionExp, resultIfTrue);
}
internal static Expression Property<TPropertyType>(this Expression exp, string propertyName)
{
PropertyInfo prop = exp.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
Debug.Assert(prop != null, "Type '" + exp.Type.FullName + "' does not declare a public instance property with the name '" + propertyName + "'");
return Expression.Property(exp, prop);
}
}
/// <summary>
/// SqlTypesAssembly allows for late binding to the capabilities of a specific version of the Microsoft.SqlServer.Types assembly
/// </summary>
internal sealed class SqlTypesAssembly
{
private static readonly System.Collections.ObjectModel.ReadOnlyCollection<string> preferredSqlTypesAssemblies = new List<string>()
{
"Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91",
"Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91",
}.AsReadOnly();
private static SqlTypesAssembly BindToLatest()
{
Assembly sqlTypesAssembly = null;
foreach (string assemblyFullName in preferredSqlTypesAssemblies)
{
AssemblyName asmName = new AssemblyName(assemblyFullName);
try
{
sqlTypesAssembly = Assembly.Load(asmName);
break;
}
catch (FileNotFoundException)
{
}
catch (FileLoadException)
{
}
}
if (sqlTypesAssembly != null)
{
return new SqlTypesAssembly(sqlTypesAssembly);
}
return null;
}
internal static bool TryGetSqlTypesAssembly(Assembly assembly, out SqlTypesAssembly sqlAssembly)
{
if (IsKnownAssembly(assembly))
{
sqlAssembly = new SqlTypesAssembly(assembly);
return true;
}
sqlAssembly = null;
return false;
}
private static bool IsKnownAssembly(Assembly assembly)
{
foreach (string knownAssemblyFullName in preferredSqlTypesAssemblies)
{
if (EntityUtil.AssemblyNamesMatch(assembly.FullName, new AssemblyName(knownAssemblyFullName)))
{
return true;
}
}
return false;
}
private static Singleton<SqlTypesAssembly> latestVersion = new Singleton<SqlTypesAssembly>(BindToLatest);
/// <summary>
/// Returns the highest available version of the Microsoft.SqlServer.Types assembly that could be located using Assembly.Load; may return <c>null</c> if no version of the assembly could be found.
/// </summary>
internal static SqlTypesAssembly Latest { get { return latestVersion.Value; } }
private SqlTypesAssembly(Assembly sqlSpatialAssembly)
{
// Retrieve SQL Server spatial types and static constructor methods
Type sqlGeog = sqlSpatialAssembly.GetType("Microsoft.SqlServer.Types.SqlGeography", throwOnError: true);
Type sqlGeom = sqlSpatialAssembly.GetType("Microsoft.SqlServer.Types.SqlGeometry", throwOnError: true);
Debug.Assert(sqlGeog != null, "SqlGeography type was not properly retrieved?");
Debug.Assert(sqlGeom != null, "SqlGeometry type was not properly retrieved?");
this.SqlGeographyType = sqlGeog;
this.sqlGeographyFromWKTString = CreateStaticConstructorDelegate<string>(sqlGeog, "STGeomFromText");
this.sqlGeographyFromWKBByteArray = CreateStaticConstructorDelegate<byte[]>(sqlGeog, "STGeomFromWKB");
this.sqlGeographyFromGMLReader = CreateStaticConstructorDelegate<System.Xml.XmlReader>(sqlGeog, "GeomFromGml");
this.SqlGeometryType = sqlGeom;
this.sqlGeometryFromWKTString = CreateStaticConstructorDelegate<string>(sqlGeom, "STGeomFromText");
this.sqlGeometryFromWKBByteArray = CreateStaticConstructorDelegate<byte[]>(sqlGeom, "STGeomFromWKB");
this.sqlGeometryFromGMLReader = CreateStaticConstructorDelegate<System.Xml.XmlReader>(sqlGeom, "GeomFromGml");
// Retrieve SQL Server specific primitive types
MethodInfo asTextMethod = this.SqlGeometryType.GetMethod("STAsText", BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null);
this.SqlCharsType = asTextMethod.ReturnType;
this.SqlStringType = this.SqlCharsType.Assembly.GetType("System.Data.SqlTypes.SqlString", throwOnError: true);
this.SqlBooleanType = this.SqlCharsType.Assembly.GetType("System.Data.SqlTypes.SqlBoolean", throwOnError: true);
this.SqlBytesType = this.SqlCharsType.Assembly.GetType("System.Data.SqlTypes.SqlBytes", throwOnError: true);
this.SqlDoubleType = this.SqlCharsType.Assembly.GetType("System.Data.SqlTypes.SqlDouble", throwOnError: true);
this.SqlInt32Type = this.SqlCharsType.Assembly.GetType("System.Data.SqlTypes.SqlInt32", throwOnError: true);
this.SqlXmlType = this.SqlCharsType.Assembly.GetType("System.Data.SqlTypes.SqlXml", throwOnError: true);
// Create type conversion delegates to SQL Server types
this.sqlBytesFromByteArray = Expressions.Lambda<byte[], object>("binaryValue", bytesVal => BuildConvertToSqlBytes(bytesVal, this.SqlBytesType)).Compile();
this.sqlStringFromString = Expressions.Lambda<string, object>("stringValue", stringVal => BuildConvertToSqlString(stringVal, this.SqlStringType)).Compile();
this.sqlCharsFromString = Expressions.Lambda<string, object>("stringValue", stringVal => BuildConvertToSqlChars(stringVal, this.SqlCharsType)).Compile();
this.sqlXmlFromXmlReader = Expressions.Lambda<System.Xml.XmlReader, object>("readerVaue", readerVal => BuildConvertToSqlXml(readerVal, this.SqlXmlType)).Compile();
// Create type conversion delegates from SQL Server types; all arguments are typed as 'object' and require Expression.Convert before use of members of the SQL Server type.
// Explicit cast from SqlBoolean to bool
this.sqlBooleanToBoolean = Expressions.Lambda<object, bool>("sqlBooleanValue", sqlBoolVal => sqlBoolVal.ConvertTo(this.SqlBooleanType).ConvertTo<bool>()).Compile();
// Explicit cast from SqlBoolean to bool? for non-Null values; otherwise null
this.sqlBooleanToNullableBoolean = Expressions.Lambda<object, bool?>("sqlBooleanValue", sqlBoolVal =>
sqlBoolVal.ConvertTo(this.SqlBooleanType).Property<bool>("IsNull")
.IfTrueThen(Expressions.Null<bool?>())
.Else(sqlBoolVal.ConvertTo(this.SqlBooleanType).ConvertTo<bool>().ConvertTo<bool?>())).Compile();
// SqlBytes has instance byte[] property 'Value'
this.sqlBytesToByteArray = Expressions.Lambda<object, byte[]>("sqlBytesValue", sqlBytesVal => sqlBytesVal.ConvertTo(this.SqlBytesType).Property<byte[]>("Value")).Compile();
// SqlChars -> SqlString, SqlString has instance string property 'Value'
this.sqlCharsToString = Expressions.Lambda<object, string>("sqlCharsValue", sqlCharsVal => sqlCharsVal.ConvertTo(this.SqlCharsType).Call("ToSqlString").Property<string>("Value")).Compile();
// Explicit cast from SqlString to string
this.sqlStringToString = Expressions.Lambda<object, string>("sqlStringValue", sqlStringVal => sqlStringVal.ConvertTo(this.SqlStringType).Property<string>("Value")).Compile();
// Explicit cast from SqlDouble to double
this.sqlDoubleToDouble = Expressions.Lambda<object, double>("sqlDoubleValue", sqlDoubleVal => sqlDoubleVal.ConvertTo(this.SqlDoubleType).ConvertTo<double>()).Compile();
// Explicit cast from SqlDouble to double? for non-Null values; otherwise null
this.sqlDoubleToNullableDouble = Expressions.Lambda<object, double?>("sqlDoubleValue", sqlDoubleVal =>
sqlDoubleVal.ConvertTo(this.SqlDoubleType).Property<bool>("IsNull")
.IfTrueThen(Expressions.Null<double?>())
.Else(sqlDoubleVal.ConvertTo(this.SqlDoubleType).ConvertTo<double>().ConvertTo<double?>())).Compile();
// Explicit cast from SqlInt32 to int
this.sqlInt32ToInt = Expressions.Lambda<object, int>("sqlInt32Value", sqlInt32Val => sqlInt32Val.ConvertTo(this.SqlInt32Type).ConvertTo<int>()).Compile();
// Explicit cast from SqlInt32 to int? for non-Null values; otherwise null
this.sqlInt32ToNullableInt = Expressions.Lambda<object, int?>("sqlInt32Value", sqlInt32Val =>
sqlInt32Val.ConvertTo(this.SqlInt32Type).Property<bool>("IsNull")
.IfTrueThen(Expressions.Null<int?>())
.Else(sqlInt32Val.ConvertTo(this.SqlInt32Type).ConvertTo<int>().ConvertTo<int?>())).Compile();
// SqlXml has instance string property 'Value'
this.sqlXmlToString = Expressions.Lambda<object, string>("sqlXmlValue", sqlXmlVal => sqlXmlVal.ConvertTo(this.SqlXmlType).Property<string>("Value")).Compile();
this.isSqlGeographyNull = Expressions.Lambda<object, bool>("sqlGeographyValue", sqlGeographyValue => sqlGeographyValue.ConvertTo(this.SqlGeographyType).Property<bool>("IsNull")).Compile();
this.isSqlGeometryNull = Expressions.Lambda<object, bool>("sqlGeometryValue", sqlGeometryValue => sqlGeometryValue.ConvertTo(this.SqlGeometryType).Property<bool>("IsNull")).Compile();
this.geographyAsTextZMAsSqlChars = Expressions.Lambda<object, object>("sqlGeographyValue", sqlGeographyValue => sqlGeographyValue.ConvertTo(this.SqlGeographyType).Call("AsTextZM")).Compile();
this.geometryAsTextZMAsSqlChars = Expressions.Lambda<object, object>("sqlGeometryValue", sqlGeometryValue => sqlGeometryValue.ConvertTo(this.SqlGeometryType).Call("AsTextZM")).Compile();
}
#region 'Public' API
#region Primitive Types and Type Conversions
internal Type SqlBooleanType { get; private set; }
internal Type SqlBytesType { get; private set; }
internal Type SqlCharsType { get; private set; }
internal Type SqlStringType { get; private set; }
internal Type SqlDoubleType { get; private set; }
internal Type SqlInt32Type { get; private set; }
internal Type SqlXmlType { get; private set; }
private readonly Func<object, bool> sqlBooleanToBoolean;
internal bool SqlBooleanToBoolean(object sqlBooleanValue)
{
return this.sqlBooleanToBoolean(sqlBooleanValue);
}
private readonly Func<object, bool?> sqlBooleanToNullableBoolean;
internal bool? SqlBooleanToNullableBoolean(object sqlBooleanValue)
{
if (sqlBooleanToBoolean == null)
{
return null;
}
return this.sqlBooleanToNullableBoolean(sqlBooleanValue);
}
private readonly Func<byte[], object> sqlBytesFromByteArray;
internal object SqlBytesFromByteArray(byte[] binaryValue)
{
return sqlBytesFromByteArray(binaryValue);
}
private readonly Func<object, byte[]> sqlBytesToByteArray;
internal byte[] SqlBytesToByteArray(object sqlBytesValue)
{
if (sqlBytesValue == null)
{
return null;
}
return this.sqlBytesToByteArray(sqlBytesValue);
}
private readonly Func<string, object> sqlStringFromString;
internal object SqlStringFromString(string stringValue)
{
return sqlStringFromString(stringValue);
}
private readonly Func<string, object> sqlCharsFromString;
internal object SqlCharsFromString(string stringValue)
{
return sqlCharsFromString(stringValue);
}
private readonly Func<object, string> sqlCharsToString;
internal string SqlCharsToString(object sqlCharsValue)
{
if (sqlCharsValue == null)
{
return null;
}
return this.sqlCharsToString(sqlCharsValue);
}
private readonly Func<object, string> sqlStringToString;
internal string SqlStringToString(object sqlStringValue)
{
if (sqlStringValue == null)
{
return null;
}
return this.sqlStringToString(sqlStringValue);
}
private readonly Func<object, double> sqlDoubleToDouble;
internal double SqlDoubleToDouble(object sqlDoubleValue)
{
return this.sqlDoubleToDouble(sqlDoubleValue);
}
private readonly Func<object, double?> sqlDoubleToNullableDouble;
internal double? SqlDoubleToNullableDouble(object sqlDoubleValue)
{
if (sqlDoubleValue == null)
{
return null;
}
return this.sqlDoubleToNullableDouble(sqlDoubleValue);
}
private readonly Func<object, int> sqlInt32ToInt;
internal int SqlInt32ToInt(object sqlInt32Value)
{
return this.sqlInt32ToInt(sqlInt32Value);
}
private readonly Func<object, int?> sqlInt32ToNullableInt;
internal int? SqlInt32ToNullableInt(object sqlInt32Value)
{
if (sqlInt32Value == null)
{
return null;
}
return this.sqlInt32ToNullableInt(sqlInt32Value);
}
private readonly Func<System.Xml.XmlReader, object> sqlXmlFromXmlReader;
internal object SqlXmlFromString(string stringValue)
{
System.Xml.XmlReader xmlReader = XmlReaderFromString(stringValue);
return sqlXmlFromXmlReader(xmlReader);
}
private readonly Func<object, string> sqlXmlToString;
internal string SqlXmlToString(object sqlXmlValue)
{
if (sqlXmlValue == null)
{
return null;
}
return sqlXmlToString(sqlXmlValue);
}
private readonly Func<object, bool> isSqlGeographyNull;
internal bool IsSqlGeographyNull(object sqlGeographyValue)
{
if (sqlGeographyValue == null)
{
return true;
}
return isSqlGeographyNull(sqlGeographyValue);
}
private readonly Func<object, bool> isSqlGeometryNull;
internal bool IsSqlGeometryNull(object sqlGeometryValue)
{
if (sqlGeometryValue == null)
{
return true;
}
return isSqlGeometryNull(sqlGeometryValue);
}
private readonly Func<object, object> geographyAsTextZMAsSqlChars;
internal string GeographyAsTextZM(DbGeography geographyValue)
{
if (geographyValue == null)
{
return null;
}
object sqlGeographyValue = ConvertToSqlTypesGeography(geographyValue);
object chars = this.geographyAsTextZMAsSqlChars(sqlGeographyValue);
return this.SqlCharsToString(chars);
}
private readonly Func<object, object> geometryAsTextZMAsSqlChars;
internal string GeometryAsTextZM(DbGeometry geometryValue)
{
if (geometryValue == null)
{
return null;
}
object sqlGeometryValue = ConvertToSqlTypesGeometry(geometryValue);
object chars = this.geometryAsTextZMAsSqlChars(sqlGeometryValue);
return this.SqlCharsToString(chars);
}
#endregion
#region Spatial Types and Spatial Factory Methods
internal Type SqlGeographyType { get; private set; }
internal Type SqlGeometryType { get; private set; }
internal object ConvertToSqlTypesGeography(DbGeography geographyValue)
{
geographyValue.CheckNull("geographyValue");
object result = GetSqlTypesSpatialValue(geographyValue.AsSpatialValue(), SqlGeographyType);
return result;
}
internal object SqlTypesGeographyFromBinary(byte[] wellKnownBinary, int srid)
{
Debug.Assert(wellKnownBinary != null, "Validate WKB before calling SqlTypesGeographyFromBinary");
return sqlGeographyFromWKBByteArray(wellKnownBinary, srid);
}
internal object SqlTypesGeographyFromText(string wellKnownText, int srid)
{
Debug.Assert(wellKnownText != null, "Validate WKT before calling SqlTypesGeographyFromText");
return sqlGeographyFromWKTString(wellKnownText, srid);
}
internal object ConvertToSqlTypesGeometry(DbGeometry geometryValue)
{
geometryValue.CheckNull("geometryValue");
object result = GetSqlTypesSpatialValue(geometryValue.AsSpatialValue(), SqlGeometryType);
return result;
}
internal object SqlTypesGeometryFromBinary(byte[] wellKnownBinary, int srid)
{
Debug.Assert(wellKnownBinary != null, "Validate WKB before calling SqlTypesGeometryFromBinary");
return sqlGeometryFromWKBByteArray(wellKnownBinary, srid);
}
internal object SqlTypesGeometryFromText(string wellKnownText, int srid)
{
Debug.Assert(wellKnownText != null, "Validate WKT before calling SqlTypesGeometryFromText");
return sqlGeometryFromWKTString(wellKnownText, srid);
}
#endregion
#endregion
private object GetSqlTypesSpatialValue(IDbSpatialValue spatialValue, Type requiredProviderValueType)
{
Debug.Assert(spatialValue != null, "Ensure spatial value is non-null before calling GetSqlTypesSpatialValue");
// If the specified value was created by this spatial services implementation, its underlying Microsoft.SqlServer.Types.SqlGeography value is available via the ProviderValue property.
object providerValue = spatialValue.ProviderValue;
if (providerValue != null && providerValue.GetType() == requiredProviderValueType)
{
return providerValue;
}
// Otherwise, attempt to retrieve a Well Known Binary, Well Known Text or GML (in descending order of preference) representation of the value that can be used to create an appropriate Microsoft.SqlServer.Types.SqlGeography/SqlGeometry value
int? srid = spatialValue.CoordinateSystemId;
if (srid.HasValue)
{
// Well Known Binary (WKB)
byte[] binaryValue = spatialValue.WellKnownBinary;
if (binaryValue != null)
{
return (spatialValue.IsGeography ? sqlGeographyFromWKBByteArray(binaryValue, srid.Value) : sqlGeometryFromWKBByteArray(binaryValue, srid.Value));
}
// Well Known Text (WKT)
string textValue = spatialValue.WellKnownText;
if (textValue != null)
{
return (spatialValue.IsGeography ? sqlGeographyFromWKTString(textValue, srid.Value) : sqlGeometryFromWKTString(textValue, srid.Value));
}
// Geography Markup Language (GML), as a string
string gmlValue = spatialValue.GmlString;
if (gmlValue != null)
{
var xmlReader = XmlReaderFromString(gmlValue);
return (spatialValue.IsGeography ? sqlGeographyFromGMLReader(xmlReader, srid.Value) : sqlGeometryFromGMLReader(xmlReader, srid.Value));
}
}
throw spatialValue.NotSqlCompatible();
}
private static System.Xml.XmlReader XmlReaderFromString(string stringValue)
{
return System.Xml.XmlReader.Create(new System.IO.StringReader(stringValue));
}
private readonly Func<string, int, object> sqlGeographyFromWKTString;
private readonly Func<byte[], int, object> sqlGeographyFromWKBByteArray;
private readonly Func<System.Xml.XmlReader, int, object> sqlGeographyFromGMLReader;
private readonly Func<string, int, object> sqlGeometryFromWKTString;
private readonly Func<byte[], int, object> sqlGeometryFromWKBByteArray;
private readonly Func<System.Xml.XmlReader, int, object> sqlGeometryFromGMLReader;
#region Expression Compilation Helpers
private static Func<TArg, int, object> CreateStaticConstructorDelegate<TArg>(Type spatialType, string methodName)
{
Debug.Assert(spatialType != null, "Ensure spatialType is non-null before calling CreateStaticConstructorDelegate");
var dataParam = Expression.Parameter(typeof(TArg));
var sridParam = Expression.Parameter(typeof(int));
var staticCtorMethod = spatialType.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static);
Debug.Assert(staticCtorMethod != null, "Could not find method '" + methodName + "' on type '" + spatialType.FullName + "'");
Debug.Assert(staticCtorMethod.GetParameters().Length == 2 && staticCtorMethod.GetParameters()[1].ParameterType == typeof(int), "Static constructor method on '" + spatialType.FullName + "' does not match static constructor pattern?");
Expression sqlData = BuildConvertToSqlType(dataParam, staticCtorMethod.GetParameters()[0].ParameterType);
var ex = Expression.Lambda<Func<TArg, int, object>>(Expression.Call(null, staticCtorMethod, sqlData, sridParam), dataParam, sridParam);
var result = ex.Compile();
return result;
}
private static Expression BuildConvertToSqlType(Expression toConvert, Type convertTo)
{
if (toConvert.Type == typeof(byte[]))
{
return BuildConvertToSqlBytes(toConvert, convertTo);
}
else if (toConvert.Type == typeof(string))
{
if (convertTo.Name == "SqlString")
{
return BuildConvertToSqlString(toConvert, convertTo);
}
else
{
return BuildConvertToSqlChars(toConvert, convertTo);
}
}
else
{
Debug.Assert(toConvert.Type == typeof(System.Xml.XmlReader), "Argument to static constructor method was not byte[], string or XmlReader?");
if (toConvert.Type == typeof(System.Xml.XmlReader))
{
return BuildConvertToSqlXml(toConvert, convertTo);
}
}
return toConvert;
}
private static Expression BuildConvertToSqlBytes(Expression toConvert, Type sqlBytesType)
{
// dataParam:byte[] => new SqlBytes(dataParam)
Debug.Assert(sqlBytesType.Name == "SqlBytes", "byte[] argument used with non-SqlBytes static constructor method?");
ConstructorInfo byteArrayCtor = sqlBytesType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { toConvert.Type }, null);
Debug.Assert(byteArrayCtor != null, "SqlXml(System.IO.Stream) constructor not found?");
Expression result = Expression.New(byteArrayCtor, toConvert);
return result;
}
private static Expression BuildConvertToSqlChars(Expression toConvert, Type sqlCharsType)
{
// dataParam:String => new SqlChars(new SqlString(dataParam))
Debug.Assert(sqlCharsType.Name == "SqlChars", "String argument used with non-SqlChars static constructor method?");
Type sqlString = sqlCharsType.Assembly.GetType("System.Data.SqlTypes.SqlString", throwOnError: true);
ConstructorInfo sqlCharsFromSqlStringCtor = sqlCharsType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { sqlString }, null);
Debug.Assert(sqlCharsFromSqlStringCtor != null, "SqlXml(System.IO.Stream) constructor not found?");
ConstructorInfo sqlStringFromStringCtor = sqlString.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(string) }, null);
Expression result = Expression.New(sqlCharsFromSqlStringCtor, Expression.New(sqlStringFromStringCtor, toConvert));
return result;
}
private static Expression BuildConvertToSqlString(Expression toConvert, Type sqlStringType)
{
// dataParam:String => new SqlString(dataParam)
Debug.Assert(sqlStringType.Name == "SqlString", "String argument used with non-SqlString static constructor method?");
ConstructorInfo sqlStringFromStringCtor = sqlStringType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(string) }, null);
Debug.Assert(sqlStringFromStringCtor != null);
Expression result = Expression.Convert(Expression.New(sqlStringFromStringCtor, toConvert), typeof(object));
return result;
}
private static Expression BuildConvertToSqlXml(Expression toConvert, Type sqlXmlType)
{
// dataParam:Stream => new SqlXml(dataParam)
Debug.Assert(sqlXmlType.Name == "SqlXml", "Stream argument used with non-SqlXml static constructor method?");
ConstructorInfo readerCtor = sqlXmlType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { toConvert.Type }, null);
Debug.Assert(readerCtor != null, "SqlXml(System.Xml.XmlReader) constructor not found?");
Expression result = Expression.New(readerCtor, toConvert);
return result;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.SymbolTree;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Roslyn.Utilities;
using System.IO;
namespace Microsoft.CodeAnalysis.IncrementalCaches
{
/// <summary>
/// Features like add-using want to be able to quickly search symbol indices for projects and
/// metadata. However, creating those indices can be expensive. As such, we don't want to
/// construct them during the add-using process itself. Instead, we expose this type as an
/// Incremental-Analyzer to walk our projects/metadata in the background to keep the indices
/// up to date.
///
/// We also then export this type as a service that can give back the index for a project or
/// metadata dll on request. If the index has been produced then it will be returned and
/// can be used by add-using. Otherwise, nothing is returned and no results will be found.
///
/// This means that as the project is being indexed, partial results may be returned. However
/// once it is fully indexed, then total results will be returned.
/// </summary>
[Shared]
[ExportIncrementalAnalyzerProvider(nameof(SymbolTreeInfoIncrementalAnalyzerProvider), new[] { WorkspaceKind.Host })]
[ExportWorkspaceServiceFactory(typeof(ISymbolTreeInfoCacheService))]
internal class SymbolTreeInfoIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider, IWorkspaceServiceFactory
{
private struct ProjectInfo
{
public readonly VersionStamp VersionStamp;
public readonly SymbolTreeInfo SymbolTreeInfo;
public ProjectInfo(VersionStamp versionStamp, SymbolTreeInfo info)
{
VersionStamp = versionStamp;
SymbolTreeInfo = info;
}
}
private struct MetadataInfo
{
public readonly DateTime TimeStamp;
/// <summary>
/// Note: can be <code>null</code> if were unable to create a SymbolTreeInfo
/// (for example, if the metadata was bogus and we couldn't read it in).
/// </summary>
public readonly SymbolTreeInfo SymbolTreeInfo;
/// <summary>
/// Note: the Incremental-Analyzer infrastructure guarantees that it will call all the methods
/// on <see cref="IncrementalAnalyzer"/> in a serial fashion. As that is the only type that
/// reads/writes these <see cref="MetadataInfo"/> objects, we don't need to lock this.
/// </summary>
public readonly HashSet<ProjectId> ReferencingProjects;
public MetadataInfo(DateTime timeStamp, SymbolTreeInfo info, HashSet<ProjectId> referencingProjects)
{
TimeStamp = timeStamp;
SymbolTreeInfo = info;
ReferencingProjects = referencingProjects;
}
}
// Concurrent dictionaries so they can be read from the SymbolTreeInfoCacheService while
// they are being populated/updated by the IncrementalAnalyzer.
private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo = new ConcurrentDictionary<ProjectId, ProjectInfo>();
private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo = new ConcurrentDictionary<string, MetadataInfo>();
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
{
var cacheService = workspace.Services.GetService<IWorkspaceCacheService>();
if (cacheService != null)
{
cacheService.CacheFlushRequested += OnCacheFlushRequested;
}
return new IncrementalAnalyzer(_projectToInfo, _metadataPathToInfo);
}
private void OnCacheFlushRequested(object sender, EventArgs e)
{
// If we hear about low memory conditions, flush our caches. This will degrade the
// experience a bit (as we will no longer offer to Add-Using for p2p refs/metadata),
// but will be better than OOM'ing. These caches will be regenerated in the future
// when the incremental analyzer reanalyzers the projects in teh workspace.
_projectToInfo.Clear();
_metadataPathToInfo.Clear();
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
return new SymbolTreeInfoCacheService(_projectToInfo, _metadataPathToInfo);
}
private static string GetReferenceKey(PortableExecutableReference reference)
{
return reference.FilePath ?? reference.Display;
}
private static bool TryGetLastWriteTime(string path, out DateTime time)
{
var succeeded = false;
time = IOUtilities.PerformIO(
() =>
{
var result = File.GetLastWriteTimeUtc(path);
succeeded = true;
return result;
},
default(DateTime));
return succeeded;
}
private class SymbolTreeInfoCacheService : ISymbolTreeInfoCacheService
{
private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo;
private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo;
public SymbolTreeInfoCacheService(
ConcurrentDictionary<ProjectId, ProjectInfo> projectToInfo,
ConcurrentDictionary<string, MetadataInfo> metadataPathToInfo)
{
_projectToInfo = projectToInfo;
_metadataPathToInfo = metadataPathToInfo;
}
public async Task<SymbolTreeInfo> TryGetMetadataSymbolTreeInfoAsync(
Solution solution,
PortableExecutableReference reference,
CancellationToken cancellationToken)
{
var key = GetReferenceKey(reference);
if (key != null)
{
MetadataInfo metadataInfo;
if (_metadataPathToInfo.TryGetValue(key, out metadataInfo))
{
DateTime writeTime;
if (TryGetLastWriteTime(key, out writeTime) && writeTime == metadataInfo.TimeStamp)
{
return metadataInfo.SymbolTreeInfo;
}
}
}
// If we didn't have it in our cache, see if we can load it from disk.
// Note: pass 'loadOnly' so we only attempt to load from disk, not to actually
// try to create the metadata.
var info = await SymbolTreeInfo.TryGetInfoForMetadataReferenceAsync(
solution, reference, loadOnly: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return info;
}
public async Task<SymbolTreeInfo> TryGetSourceSymbolTreeInfoAsync(
Project project, CancellationToken cancellationToken)
{
ProjectInfo projectInfo;
if (_projectToInfo.TryGetValue(project.Id, out projectInfo))
{
var version = await project.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
if (version == projectInfo.VersionStamp)
{
return projectInfo.SymbolTreeInfo;
}
}
return null;
}
}
private class IncrementalAnalyzer : IncrementalAnalyzerBase
{
private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo;
private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo;
public IncrementalAnalyzer(
ConcurrentDictionary<ProjectId, ProjectInfo> projectToInfo,
ConcurrentDictionary<string, MetadataInfo> metadataPathToInfo)
{
_projectToInfo = projectToInfo;
_metadataPathToInfo = metadataPathToInfo;
}
public override Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
{
if (!document.SupportsSyntaxTree)
{
// Not a language we can produce indices for (i.e. TypeScript). Bail immediately.
return SpecializedTasks.EmptyTask;
}
if (bodyOpt != null)
{
// This was a method level edit. This can't change the symbol tree info
// for this project. Bail immediately.
return SpecializedTasks.EmptyTask;
}
return UpdateSymbolTreeInfoAsync(document.Project, cancellationToken);
}
public override Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken)
{
return UpdateSymbolTreeInfoAsync(project, cancellationToken);
}
private async Task UpdateSymbolTreeInfoAsync(Project project, CancellationToken cancellationToken)
{
if (!project.SupportsCompilation)
{
return;
}
// Check the semantic version of this project. The semantic version will change
// if any of the source files changed, or if the project version itself changed.
// (The latter happens when something happens to the project like metadata
// changing on disk).
var version = await project.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
ProjectInfo projectInfo;
if (!_projectToInfo.TryGetValue(project.Id, out projectInfo) || projectInfo.VersionStamp != version)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
// Update the symbol tree infos for metadata and source in parallel.
var referencesTask = UpdateReferencesAync(project, compilation, cancellationToken);
var projectTask = SymbolTreeInfo.GetInfoForSourceAssemblyAsync(project, cancellationToken);
await Task.WhenAll(referencesTask, projectTask).ConfigureAwait(false);
// Mark that we're up to date with this project. Future calls with the same
// semantic version can bail out immediately.
projectInfo = new ProjectInfo(version, await projectTask.ConfigureAwait(false));
_projectToInfo.AddOrUpdate(project.Id, projectInfo, (_1, _2) => projectInfo);
}
}
private Task UpdateReferencesAync(Project project, Compilation compilation, CancellationToken cancellationToken)
{
// Process all metadata references in parallel.
var tasks = project.MetadataReferences.OfType<PortableExecutableReference>()
.Select(r => UpdateReferenceAsync(project, compilation, r, cancellationToken))
.ToArray();
return Task.WhenAll(tasks);
}
private async Task UpdateReferenceAsync(
Project project, Compilation compilation, PortableExecutableReference reference, CancellationToken cancellationToken)
{
var key = GetReferenceKey(reference);
if (key == null)
{
return;
}
DateTime lastWriteTime;
if (!TryGetLastWriteTime(key, out lastWriteTime))
{
// Couldn't get the write time. Just ignore this reference.
return;
}
MetadataInfo metadataInfo;
if (!_metadataPathToInfo.TryGetValue(key, out metadataInfo) || metadataInfo.TimeStamp == lastWriteTime)
{
var info = await SymbolTreeInfo.TryGetInfoForMetadataReferenceAsync(
project.Solution, reference, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false);
// Note, getting the info may fail (for example, bogus metadata). That's ok.
// We still want to cache that result so that don't try to continuously produce
// this info over and over again.
metadataInfo = new MetadataInfo(lastWriteTime, info, metadataInfo.ReferencingProjects ?? new HashSet<ProjectId>());
_metadataPathToInfo.AddOrUpdate(key, metadataInfo, (_1, _2) => metadataInfo);
}
// Keep track that this dll is referenced by this project.
metadataInfo.ReferencingProjects.Add(project.Id);
}
public override void RemoveProject(ProjectId projectId)
{
ProjectInfo info;
_projectToInfo.TryRemove(projectId, out info);
RemoveMetadataReferences(projectId);
}
private void RemoveMetadataReferences(ProjectId projectId)
{
foreach (var kvp in _metadataPathToInfo.ToArray())
{
if (kvp.Value.ReferencingProjects.Remove(projectId))
{
if (kvp.Value.ReferencingProjects.Count == 0)
{
// This metadata dll isn't referenced by any project. We can just dump it.
MetadataInfo unneeded;
_metadataPathToInfo.TryRemove(kvp.Key, out unneeded);
}
}
}
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace tk2dEditor
{
class BrushDictData
{
public tk2dTileMapEditorBrush brush;
public int brushHash;
public Mesh mesh;
public Material[] materials;
public Rect rect;
}
public class BrushRenderer
{
tk2dTileMap tileMap;
tk2dSpriteCollectionData spriteCollection;
Dictionary<tk2dTileMapEditorBrush, BrushDictData> brushLookupDict = new Dictionary<tk2dTileMapEditorBrush, BrushDictData>();
public BrushRenderer(tk2dTileMap tileMap)
{
this.tileMap = tileMap;
this.spriteCollection = tileMap.SpriteCollectionInst;
}
public void Destroy()
{
foreach (var v in brushLookupDict.Values)
{
Mesh.DestroyImmediate(v.mesh);
v.mesh = null;
}
}
// Build a mesh for a list of given sprites
void BuildMeshForBrush(tk2dTileMapEditorBrush brush, BrushDictData dictData, int tilesPerRow)
{
List<Vector3> vertices = new List<Vector3>();
List<Vector2> uvs = new List<Vector2>();
Dictionary<Material, List<int>> triangles = new Dictionary<Material, List<int>>();
// bounds of tile
Vector3 spriteBounds = spriteCollection.FirstValidDefinition.untrimmedBoundsData[1];
Vector3 tileSize = brush.overrideWithSpriteBounds?
spriteBounds:
tileMap.data.tileSize;
float layerOffset = 0.001f;
Vector3 boundsMin = new Vector3(1.0e32f, 1.0e32f, 1.0e32f);
Vector3 boundsMax = new Vector3(-1.0e32f, -1.0e32f, -1.0e32f);
float tileOffsetX = 0, tileOffsetY = 0;
if (!brush.overrideWithSpriteBounds)
tileMap.data.GetTileOffset(out tileOffsetX, out tileOffsetY);
if (brush.type == tk2dTileMapEditorBrush.Type.MultiSelect)
{
int tileX = 0;
int tileY = brush.multiSelectTiles.Length / tilesPerRow;
if ((brush.multiSelectTiles.Length % tilesPerRow) == 0) tileY -=1;
foreach (var uncheckedSpriteId in brush.multiSelectTiles)
{
float xOffset = (tileY & 1) * tileOffsetX;
// The origin of the tile in mesh space
Vector3 tileOrigin = new Vector3((tileX + xOffset) * tileSize.x, tileY * tileSize.y, 0.0f);
//if (brush.overrideWithSpriteBounds)
{
boundsMin = Vector3.Min(boundsMin, tileOrigin);
boundsMax = Vector3.Max(boundsMax, tileOrigin + tileSize);
}
if (uncheckedSpriteId != -1)
{
int indexRoot = vertices.Count;
int spriteId = Mathf.Clamp(uncheckedSpriteId, 0, spriteCollection.Count - 1);
tk2dSpriteDefinition sprite = spriteCollection.spriteDefinitions[spriteId];
for (int j = 0; j < sprite.positions.Length; ++j)
{
// Sprite vertex, centered around origin
Vector3 centeredSpriteVertex = sprite.positions[j] - sprite.untrimmedBoundsData[0];
// Offset so origin is at bottom left
Vector3 v = centeredSpriteVertex + sprite.untrimmedBoundsData[1] * 0.5f;
boundsMin = Vector3.Min(boundsMin, tileOrigin + v);
boundsMax = Vector3.Max(boundsMax, tileOrigin + v);
vertices.Add(tileOrigin + v);
uvs.Add(sprite.uvs[j]);
}
if (!triangles.ContainsKey(sprite.material))
triangles.Add(sprite.material, new List<int>());
for (int j = 0; j < sprite.indices.Length; ++j)
{
triangles[sprite.material].Add(indexRoot + sprite.indices[j]);
}
}
tileX += 1;
if (tileX == tilesPerRow)
{
tileX = 0;
tileY -= 1;
}
}
}
else
{
// the brush is centered around origin, x to the right, y up
foreach (var tile in brush.tiles)
{
float xOffset = (tile.y & 1) * tileOffsetX;
// The origin of the tile in mesh space
Vector3 tileOrigin = new Vector3((tile.x + xOffset) * tileSize.x, tile.y * tileSize.y, tile.layer * layerOffset);
//if (brush.overrideWithSpriteBounds)
{
boundsMin = Vector3.Min(boundsMin, tileOrigin);
boundsMax = Vector3.Max(boundsMax, tileOrigin + tileSize);
}
if (tile.spriteId == -1)
continue;
int indexRoot = vertices.Count;
tile.spriteId = (ushort)Mathf.Clamp(tile.spriteId, 0, spriteCollection.Count - 1);
var sprite = spriteCollection.spriteDefinitions[tile.spriteId];
for (int j = 0; j < sprite.positions.Length; ++j)
{
// Sprite vertex, centered around origin
Vector3 centeredSpriteVertex = sprite.positions[j] - sprite.untrimmedBoundsData[0];
// Offset so origin is at bottom left
Vector3 v = centeredSpriteVertex + sprite.untrimmedBoundsData[1] * 0.5f;
boundsMin = Vector3.Min(boundsMin, tileOrigin + v);
boundsMax = Vector3.Max(boundsMax, tileOrigin + v);
vertices.Add(tileOrigin + v);
uvs.Add(sprite.uvs[j]);
}
if (!triangles.ContainsKey(sprite.material))
triangles.Add(sprite.material, new List<int>());
for (int j = 0; j < sprite.indices.Length; ++j)
{
triangles[sprite.material].Add(indexRoot + sprite.indices[j]);
}
}
}
if (dictData.mesh == null)
{
dictData.mesh = new Mesh();
dictData.mesh.hideFlags = HideFlags.DontSave;
}
Mesh mesh = dictData.mesh;
mesh.Clear();
mesh.vertices = vertices.ToArray();
Color[] colors = new Color[vertices.Count];
for (int i = 0; i < vertices.Count; ++i)
colors[i] = Color.white;
mesh.colors = colors;
mesh.uv = uvs.ToArray();
mesh.subMeshCount = triangles.Keys.Count;
int subMeshId = 0;
foreach (Material mtl in triangles.Keys)
{
mesh.SetTriangles(triangles[mtl].ToArray(), subMeshId);
subMeshId++;
}
dictData.brush = brush;
dictData.brushHash = brush.brushHash;
dictData.mesh = mesh;
dictData.materials = (new List<Material>(triangles.Keys)).ToArray();
dictData.rect = new Rect(boundsMin.x, boundsMin.y, boundsMax.x - boundsMin.x, boundsMax.y - boundsMin.y);
}
BrushDictData GetDictDataForBrush(tk2dTileMapEditorBrush brush, int tilesPerRow)
{
BrushDictData dictEntry;
if (brushLookupDict.TryGetValue(brush, out dictEntry))
{
if (brush.brushHash != dictEntry.brushHash)
{
BuildMeshForBrush(brush, dictEntry, tilesPerRow);
}
return dictEntry;
}
else
{
dictEntry = new BrushDictData();
BuildMeshForBrush(brush, dictEntry, tilesPerRow);
brushLookupDict[brush] = dictEntry;
return dictEntry;
}
}
float lastScale;
public float LastScale { get { return lastScale; } }
public Rect DrawBrush(tk2dTileMap tileMap, tk2dTileMapEditorBrush brush, float scale, bool forceUnitSpacing, int tilesPerRow)
{
var dictData = GetDictDataForBrush(brush, tilesPerRow);
Mesh atlasViewMesh = dictData.mesh;
Rect atlasViewRect = BrushToScreenRect(dictData.rect);
float width = atlasViewRect.width * scale;
float height = atlasViewRect.height * scale;
float maxScreenWidth = Screen.width - 16;
if (width > maxScreenWidth)
{
height = height * maxScreenWidth / width;
width = maxScreenWidth;
}
Rect rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false));
scale = width / atlasViewRect.width;
lastScale = scale;
if (Event.current.type == EventType.Repaint)
{
Matrix4x4 mat = new Matrix4x4();
var spriteDef = tileMap.SpriteCollectionInst.spriteDefinitions[0];
mat.SetTRS(new Vector3(rect.x,
rect.y + height, 0), Quaternion.identity, new Vector3(scale / spriteDef.texelSize.x, -scale / spriteDef.texelSize.y, 1));
for (int i = 0; i < dictData.materials.Length; ++i)
{
dictData.materials[i].SetPass(0);
Graphics.DrawMeshNow(atlasViewMesh, mat * GUI.matrix, i);
}
}
return rect;
}
public Vector3 TexelSize
{
get
{
return spriteCollection.spriteDefinitions[0].texelSize;
}
}
public Rect BrushToScreenRect(Rect rect)
{
Vector3 texelSize = TexelSize;
int w = (int)(rect.width / texelSize.x);
int h = (int)(rect.height / texelSize.y);
return new Rect(0, 0, w, h);
}
public Rect TileSizePixels
{
get
{
Vector3 texelSize = TexelSize;
Vector3 tileSize = spriteCollection.spriteDefinitions[0].untrimmedBoundsData[1];
return new Rect(0, 0, tileSize.x / texelSize.x, tileSize.y / texelSize.y);
}
}
}
}
| |
/*
* DateTimeConverter.cs
*
* Copyright ?2007 Michael Schwarz (http://www.ajaxpro.info).
* All Rights Reserved.
*
* 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.
*/
/*
* MS 06-04-25 removed unnecessarily used cast
* MS 06-05-23 using local variables instead of "new Type()" for get De-/SerializableTypes
* MS 06-07-09 added new Date and new Date(Date.UTC parsing
* MS 06-09-22 added UniversalSortableDateTimePattern parsing
* added new oldStyle/renderDateTimeAsString configruation to enable string output of DateTime
* changed JSONLIB stand-alone library will return DateTimes as UniversalSortableDateTimePattern
* MS 06-09-26 improved performance using StringBuilder
* MS 06-09-29 added new oldStyle/noUtcTime configuration
* fixed using rednerDateTimeAsString serialization
* MS 08-03-21 using ASP.NET AJAX format for dates (new default)
*
*/
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace AjaxPro
{
/// <summary>
/// Provides methods to serialize and deserialize a DateTime object.
/// </summary>
public class DateTimeConverter : IJavaScriptConverter
{
private Regex r = new Regex(@"(\d{4}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,3})", RegexOptions.Compiled);
private double UtcOffsetMinutes = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes;
/// <summary>
/// Initializes a new instance of the <see cref="DateTimeConverter"/> class.
/// </summary>
public DateTimeConverter()
: base()
{
m_serializableTypes = new Type[] { typeof(DateTime) };
m_deserializableTypes = new Type[] { typeof(DateTime) };
}
/// <summary>
/// Converts an IJavaScriptObject into an NET object.
/// </summary>
/// <param name="o">The IJavaScriptObject object to convert.</param>
/// <param name="t"></param>
/// <returns>Returns a .NET object.</returns>
public override object Deserialize(IJavaScriptObject o, Type t)
{
JavaScriptObject ht = o as JavaScriptObject;
if (o is JavaScriptSource)
{
// new Date(Date.UTC(2006,6,9,5,36,18,875))
string s = o.ToString();
if (s.StartsWith("new Date(Date.UTC(") && s.EndsWith("))"))
{
s = s.Substring(18, s.Length - 20);
//Regex r = new Regex(@"(\d{4}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,3})", RegexOptions.Compiled);
//Match m = r.Match(s);
//if (m.Groups.Count != 8)
// throw new NotSupportedException();
//int Year = int.Parse(m.Groups[1].Value);
//int Month = int.Parse(m.Groups[2].Value) + 1;
//int Day = int.Parse(m.Groups[3].Value);
//int Hour = int.Parse(m.Groups[4].Value);
//int Minute = int.Parse(m.Groups[5].Value);
//int Second = int.Parse(m.Groups[6].Value);
//int Millisecond = int.Parse(m.Groups[7].Value);
//DateTime d = new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
string[] p = s.Split(',');
return new DateTime(int.Parse(p[0]), int.Parse(p[1]) + 1, int.Parse(p[2]), int.Parse(p[3]), int.Parse(p[4]), int.Parse(p[5]), int.Parse(p[6])).AddMinutes(UtcOffsetMinutes);
}
else if (s.StartsWith("new Date(") && s.EndsWith(")"))
{
long nanosecs = long.Parse(s.Substring(9, s.Length - 10)) * 10000;
#if(NET20)
nanosecs += new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
DateTime d1 = new DateTime(nanosecs, DateTimeKind.Utc);
#else
nanosecs += new DateTime(1970, 1, 1, 0, 0, 0, 0).Ticks;
DateTime d1 = new DateTime(nanosecs);
#endif
return (Utility.Settings.OldStyle.Contains("noUtcTime") ? d1 : d1.AddMinutes(UtcOffsetMinutes)); // TimeZone.CurrentTimeZone.GetUtcOffset(d1).TotalMinutes);
}
}
else if (o is JavaScriptString)
{
string d = o.ToString();
#if(NET20)
if (d.StartsWith("/Date(") && d.EndsWith(")/"))
// if (d.Length >= 9 && d.Substring(0, 6) == "/Date(" && d.Substring(d.Length -2) == ")/")
{
DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, new System.Globalization.GregorianCalendar(), System.DateTimeKind.Utc);
return new DateTime(
long.Parse(d.Substring(6, d.Length - 6 - 2)) * TimeSpan.TicksPerMillisecond, DateTimeKind.Utc).AddTicks(Epoch.Ticks);
}
DateTime d2;
if (DateTime.TryParseExact(o.ToString(),
System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out d2
) == true)
{
return (Utility.Settings.OldStyle.Contains("noUtcTime") ? d2 : d2.AddMinutes(UtcOffsetMinutes)); // TimeZone.CurrentTimeZone.GetUtcOffset(d2).TotalMinutes);
}
#else
try
{
DateTime d4 = DateTime.ParseExact(o.ToString(),
System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces
);
return (Utility.Settings.OldStyle.Contains("noUtcTime") ? d4 : d4.AddMinutes(UtcOffsetMinutes)); // TimeZone.CurrentTimeZone.GetUtcOffset(d4).TotalMinutes);
}
catch(FormatException)
{
}
#endif
}
if (ht == null)
throw new NotSupportedException();
int Year2 = (int)JavaScriptDeserializer.Deserialize(ht["Year"], typeof(int));
int Month2 = (int)JavaScriptDeserializer.Deserialize(ht["Month"], typeof(int));
int Day2 = (int)JavaScriptDeserializer.Deserialize(ht["Day"], typeof(int));
int Hour2 = (int)JavaScriptDeserializer.Deserialize(ht["Hour"], typeof(int));
int Minute2 = (int)JavaScriptDeserializer.Deserialize(ht["Minute"], typeof(int));
int Second2 = (int)JavaScriptDeserializer.Deserialize(ht["Second"], typeof(int));
int Millisecond2 = (int)JavaScriptDeserializer.Deserialize(ht["Millisecond"], typeof(int));
DateTime d5 = new DateTime(Year2, Month2, Day2, Hour2, Minute2, Second2, Millisecond2);
return (Utility.Settings.OldStyle.Contains("noUtcTime") ? d5 : d5.AddMinutes(UtcOffsetMinutes)); // TimeZone.CurrentTimeZone.GetUtcOffset(d3).TotalMinutes);
}
/// <summary>
/// Converts a .NET object into a JSON string.
/// </summary>
/// <param name="o">The object to convert.</param>
/// <returns>Returns a JSON string.</returns>
public override string Serialize(object o)
{
StringBuilder sb = new StringBuilder();
Serialize(o, sb);
return sb.ToString();
}
/// <summary>
/// Serializes the specified o.
/// </summary>
/// <param name="o">The o.</param>
/// <param name="sb">The sb.</param>
public override void Serialize(object o, StringBuilder sb)
{
if (!(o is DateTime))
throw new NotSupportedException();
DateTime dt = (DateTime)o;
bool noUtcTime = Utility.Settings.OldStyle.Contains("noUtcTime");
if (!noUtcTime)
dt = dt.ToUniversalTime();
#if(NET20)
if (!AjaxPro.Utility.Settings.OldStyle.Contains("renderNotASPAJAXDateTime"))
{
DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, new System.Globalization.GregorianCalendar(), System.DateTimeKind.Utc);
sb.Append("\"\\/Date(" + ((dt.Ticks - Epoch.Ticks) / TimeSpan.TicksPerMillisecond) + ")\\/\"");
return;
}
#endif
#if(JSONLIB)
JavaScriptUtil.QuoteString(dt.ToString(System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern), sb);
#else
if (AjaxPro.Utility.Settings.OldStyle.Contains("renderDateTimeAsString"))
{
JavaScriptUtil.QuoteString(dt.ToString(System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern), sb);
return;
}
if (!noUtcTime)
sb.AppendFormat("new Date(Date.UTC({0},{1},{2},{3},{4},{5},{6}))",
dt.Year,
dt.Month - 1,
dt.Day,
dt.Hour,
dt.Minute,
dt.Second,
dt.Millisecond);
else
sb.AppendFormat("new Date({0},{1},{2},{3},{4},{5},{6})",
dt.Year,
dt.Month - 1,
dt.Day,
dt.Hour,
dt.Minute,
dt.Second,
dt.Millisecond);
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using PushDataVSMVCTutorial.Areas.HelpPage.Models;
namespace PushDataVSMVCTutorial.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using LinqToDB.Async;
namespace LinqToDB
{
using Methods = LinqToDB.Reflection.Methods.LinqToDB.MultiInsert;
public static class MultiInsertExtensions
{
#region Public fluent API
/// <summary>
/// Inserts records from source query into multiple target tables.
/// </summary>
/// <remarks>Only supported by Oracle data provider.</remarks>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <param name="source">Source query, that returns data for insert operation.</param>
[Pure, LinqTunnel]
public static IMultiInsertSource<TSource> MultiInsert<TSource>(this IQueryable<TSource> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
var query = source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
Methods.Begin.MakeGenericMethod(typeof(TSource)),
source.Expression));
return new MultiInsertQuery<TSource>(query);
}
/// <summary>
/// Unconditionally insert into target table.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <typeparam name="TTarget">Target table record type.</typeparam>
/// <param name="source">Source query, that returns data for insert operation.</param>
/// <param name="target">Target table to insert into.</param>
/// <param name="setter">Update expression. Uses record from source query as parameter. Expression supports only target table record new expression with field initializers.</param>
[Pure, LinqTunnel]
public static IMultiInsertInto<TSource> Into<TSource, TTarget>(
this IMultiInsertInto<TSource> source,
ITable<TTarget> target,
[InstantHandle] Expression<Func<TSource, TTarget>> setter)
where TTarget : notnull
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (target == null) throw new ArgumentNullException(nameof(target));
if (setter == null) throw new ArgumentNullException(nameof(setter));
var query = ((MultiInsertQuery<TSource>)source).Query;
query = query.Provider.CreateQuery<TSource>(
Expression.Call(
null,
Methods.Into.MakeGenericMethod(typeof(TSource), typeof(TTarget)),
query.Expression,
target.Expression,
Expression.Quote(setter)));
return new MultiInsertQuery<TSource>(query);
}
/// <summary>
/// Conditionally insert into target table.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <typeparam name="TTarget">Target table record type.</typeparam>
/// <param name="source">Source query, that returns data for insert operation.</param>
/// <param name="condition">Predicate indicating when to insert into target table.</param>
/// <param name="target">Target table to insert into.</param>
/// <param name="setter">Update expression. Uses record from source query as parameter. Expression supports only target table record new expression with field initializers.</param>
[Pure, LinqTunnel]
public static IMultiInsertWhen<TSource> When<TSource, TTarget>(
this IMultiInsertWhen<TSource> source,
[InstantHandle] Expression<Func<TSource, bool>> condition,
ITable<TTarget> target,
[InstantHandle] Expression<Func<TSource, TTarget>> setter)
where TTarget : notnull
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (condition == null) throw new ArgumentNullException(nameof(condition));
if (target == null) throw new ArgumentNullException(nameof(target));
if (setter == null) throw new ArgumentNullException(nameof(setter));
var query = ((MultiInsertQuery<TSource>)source).Query;
query = query.Provider.CreateQuery<TSource>(
Expression.Call(
null,
Methods.When.MakeGenericMethod(typeof(TSource), typeof(TTarget)),
query.Expression,
Expression.Quote(condition),
target.Expression,
Expression.Quote(setter)));
return new MultiInsertQuery<TSource>(query);
}
/// <summary>
/// Insert into target table when previous conditions don't match.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <typeparam name="TTarget">Target table record type.</typeparam>
/// <param name="source">Source query, that returns data for insert operation.</param>
/// <param name="target">Target table to insert into.</param>
/// <param name="setter">Update expression. Uses record from source query as parameter. Expression supports only target table record new expression with field initializers.</param>
[Pure, LinqTunnel]
public static IMultiInsertElse<TSource> Else<TSource, TTarget>(
this IMultiInsertWhen<TSource> source,
ITable<TTarget> target,
[InstantHandle] Expression<Func<TSource, TTarget>> setter)
where TTarget : notnull
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (target == null) throw new ArgumentNullException(nameof(target));
if (setter == null) throw new ArgumentNullException(nameof(setter));
var query = ((MultiInsertQuery<TSource>)source).Query;
query = query.Provider.CreateQuery<TSource>(
Expression.Call(
null,
Methods.Else.MakeGenericMethod(typeof(TSource), typeof(TTarget)),
query.Expression,
target.Expression,
Expression.Quote(setter)));
return new MultiInsertQuery<TSource>(query);
}
/// <summary>
/// Inserts source data into every configured table.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <param name="insert">Multi-table insert to perform.</param>
/// <returns>Number of inserted rows.</returns>
public static int Insert<TSource>(this IMultiInsertInto<TSource> insert)
{
if (insert == null) throw new ArgumentNullException(nameof(insert));
IQueryable query = ((MultiInsertQuery<TSource>)insert).Query;
query = LinqExtensions.ProcessSourceQueryable?.Invoke(query) ?? query;
return query.Provider.Execute<int>(
Expression.Call(
null,
Methods.Insert.MakeGenericMethod(typeof(TSource)),
query.Expression));
}
/// <summary>
/// Asynchronously inserts source data into every configured table.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <param name="insert">Multi-table insert to perform.</param>
/// <param name="token">Cancellation token for async operation.</param>
/// <returns>Number of inserted rows.</returns>
public static Task<int> InsertAsync<TSource>(this IMultiInsertInto<TSource> insert, CancellationToken token = default)
{
if (insert == null) throw new ArgumentNullException(nameof(insert));
IQueryable query = ((MultiInsertQuery<TSource>)insert).Query;
query = LinqExtensions.ProcessSourceQueryable?.Invoke(query) ?? query;
var expr = Expression.Call(
null,
Methods.Insert.MakeGenericMethod(typeof(TSource)),
query.Expression);
if (query is IQueryProviderAsync queryAsync)
return queryAsync.ExecuteAsync<int>(expr, token);
return TaskEx.Run(() => query.Provider.Execute<int>(expr), token);
}
/// <summary>
/// Inserts source data into every matching condition.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <param name="insert">Multi-table insert to perform.</param>
/// <returns>Number of inserted rows.</returns>
public static int InsertAll<TSource>(this IMultiInsertElse<TSource> insert)
{
if (insert == null) throw new ArgumentNullException(nameof(insert));
IQueryable query = ((MultiInsertQuery<TSource>)insert).Query;
query = LinqExtensions.ProcessSourceQueryable?.Invoke(query) ?? query;
return query.Provider.Execute<int>(
Expression.Call(
null,
Methods.InsertAll.MakeGenericMethod(typeof(TSource)),
query.Expression));
}
/// <summary>
/// Asynchronously inserts source data into every matching condition.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <param name="insert">Multi-table insert to perform.</param>
/// <param name="token">Cancellation token for async operation.</param>
/// <returns>Number of inserted rows.</returns>
public static Task<int> InsertAllAsync<TSource>(this IMultiInsertElse<TSource> insert, CancellationToken token = default)
{
if (insert == null) throw new ArgumentNullException(nameof(insert));
IQueryable query = ((MultiInsertQuery<TSource>)insert).Query;
query = LinqExtensions.ProcessSourceQueryable?.Invoke(query) ?? query;
var expr = Expression.Call(
null,
Methods.InsertAll.MakeGenericMethod(typeof(TSource)),
query.Expression);
if (query is IQueryProviderAsync queryAsync)
return queryAsync.ExecuteAsync<int>(expr, token);
return TaskEx.Run(() => query.Provider.Execute<int>(expr), token);
}
/// <summary>
/// Inserts source data into the first matching condition.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <param name="insert">Multi-table insert to perform.</param>
/// <returns>Number of inserted rows.</returns>
public static int InsertFirst<TSource>(this IMultiInsertElse<TSource> insert)
{
if (insert == null) throw new ArgumentNullException(nameof(insert));
IQueryable query = ((MultiInsertQuery<TSource>)insert).Query;
query = LinqExtensions.ProcessSourceQueryable?.Invoke(query) ?? query;
return query.Provider.Execute<int>(
Expression.Call(
null,
Methods.InsertFirst.MakeGenericMethod(typeof(TSource)),
query.Expression));
}
/// <summary>
/// Asynchronously inserts source data into the first matching condition.
/// </summary>
/// <typeparam name="TSource">Source query record type.</typeparam>
/// <param name="insert">Multi-table insert to perform.</param>
/// <param name="token">Cancellation token for async operation.</param>
/// <returns>Number of inserted rows.</returns>
public static Task<int> InsertFirstAsync<TSource>(this IMultiInsertElse<TSource> insert, CancellationToken token = default)
{
if (insert == null) throw new ArgumentNullException(nameof(insert));
IQueryable query = ((MultiInsertQuery<TSource>)insert).Query;
query = LinqExtensions.ProcessSourceQueryable?.Invoke(query) ?? query;
var expr = Expression.Call(
null,
Methods.InsertFirst.MakeGenericMethod(typeof(TSource)),
query.Expression);
if (query is IQueryProviderAsync queryAsync)
return queryAsync.ExecuteAsync<int>(expr, token);
return TaskEx.Run(() => query.Provider.Execute<int>(expr), token);
}
#endregion
#region Fluent state
public interface IMultiInsertSource<TSource>
: IMultiInsertInto<TSource>
, IMultiInsertWhen<TSource>
{ }
public interface IMultiInsertInto<TSource>
{ }
public interface IMultiInsertWhen<TSource> : IMultiInsertElse<TSource>
{ }
public interface IMultiInsertElse<TSource>
{ }
private class MultiInsertQuery<TSource> : IMultiInsertSource<TSource>
{
public readonly IQueryable<TSource> Query;
public MultiInsertQuery(IQueryable<TSource> query)
{
this.Query = query;
}
}
#endregion
}
}
| |
using NUnit.Framework;
using Sendwithus;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
namespace SendwithusTest
{
/// <summary>
/// Unit testing class for the Customer API calls
/// </summary>
[TestFixture]
public class CustomerTest
{
public const string DEFAULT_CUSTOMER_EMAIL_ADDRESS = "sendwithus.test@gmail.com";
public const string NEW_CUSTOMER_EMAIL_ADDRESS = "sendwithus.test+new@gmail.com";
private const string INVALID_CUSTOMER_EMAIL_ADDRESS = "invalid_email_address";
private const string DEFAULT_CUSTOMER_LOCALE = "de-DE";
private const Int64 LOG_CREATED_AFTER_TIME = 1234567890;
private const Int64 LOG_CREATED_BEFORE_TIME = 9876543210;
/// <summary>
/// Sets the API
/// </summary>
[SetUp]
public void InitializeUnitTesting()
{
// Set the API key
SendwithusClient.ApiKey = "CSHARP_CUSTOMER_TEST_API_KEY";
}
/// <summary>
/// Tests the API call GET /customers/customer@example.com
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestGetCustomerAsync()
{
// Make the API call
Trace.WriteLine(String.Format("GET /customers/{0}", DEFAULT_CUSTOMER_EMAIL_ADDRESS));
try
{
var customerResponse = await Customer.GetCustomerAsync(DEFAULT_CUSTOMER_EMAIL_ADDRESS);
// Validate the response
SendwithusClientTest.ValidateResponse(customerResponse);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call GET /customers/customer@example.com with an invalid email address
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestGetCustomerWithInvalidEmailAddressAsync()
{
// Make the API call
Trace.WriteLine(String.Format("GET /customers/{0}", INVALID_CUSTOMER_EMAIL_ADDRESS));
try
{
var customerResponse = await Customer.GetCustomerAsync(INVALID_CUSTOMER_EMAIL_ADDRESS);
Assert.Fail("Failed to throw exception");
}
catch (AggregateException exception)
{
// Make sure the response was HTTP 400 Bad Request
SendwithusClientTest.ValidateException(exception, HttpStatusCode.BadRequest);
}
}
/// <summary>
/// Tests the API call POST /customers with the minimum parameters
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestCreateOrUpdateCustomerWithMinimumParametersAsync()
{
Trace.WriteLine("POST /customers");
// Build the new customer and send the create customer request
try
{
// Build the customer
var customer = new Customer(NEW_CUSTOMER_EMAIL_ADDRESS);
// Make the API call
var genericApiCallStatus = await Customer.CreateOrUpdateCustomerAsync(customer);
// Validate the response
SendwithusClientTest.ValidateResponse(genericApiCallStatus);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call POST /customers with all parameters
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestCreateOrUpdateCustomerWithAllParametersAsync()
{
Trace.WriteLine("POST /customers");
// Build the new customer and send the create customer request
try
{
var genericApiCallStatus = await BuildAndSendCreateCustomerRequest();
// Validate the response
SendwithusClientTest.ValidateResponse(genericApiCallStatus);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call DELETE /customers/(:email)
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestDeleteCustomerAsync()
{
Trace.WriteLine(String.Format("DELETE /customers", NEW_CUSTOMER_EMAIL_ADDRESS));
// Make the API call
try
{
var genericApiCallStatus = await Customer.DeleteCustomerAsync(NEW_CUSTOMER_EMAIL_ADDRESS);
// Validate the response
SendwithusClientTest.ValidateResponse(genericApiCallStatus);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call GET /customers/matt@sendwithus.com/logs?count={count}&created_lt={timestamp}&created_gt={timestamp} with no parameters
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestGetCustomerEmailLogsWithNoParametersAsync()
{
// Make the API call
Trace.WriteLine(String.Format("GET /customers/{0}/logs", DEFAULT_CUSTOMER_EMAIL_ADDRESS));
try
{
var customerEmailLogsResponse = await Customer.GetCustomerEmailLogsAsync(DEFAULT_CUSTOMER_EMAIL_ADDRESS);
// Validate the response
SendwithusClientTest.ValidateResponse(customerEmailLogsResponse);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Tests the API call GET /customers/matt@sendwithus.com/logs?count={count}&created_lt={timestamp}&created_gt={timestamp} with all parameters
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestGetCustomerEmailLogsWithAllParametersAsync()
{
Trace.WriteLine(String.Format("GET /customers/{0}/logs", DEFAULT_CUSTOMER_EMAIL_ADDRESS));
// Build the query parameters
var queryParameters = new Dictionary<string, object>();
queryParameters.Add("count", 2);
queryParameters.Add("created_lt", LOG_CREATED_BEFORE_TIME);
queryParameters.Add("created_gt", LOG_CREATED_AFTER_TIME);
// Make the API call
try
{
var customerEmailLogsResponse = await Customer.GetCustomerEmailLogsAsync(DEFAULT_CUSTOMER_EMAIL_ADDRESS, queryParameters);
// Validate the response
SendwithusClientTest.ValidateResponse(customerEmailLogsResponse);
}
catch (AggregateException exception)
{
Assert.Fail(exception.ToString());
}
}
/// <summary>
/// Builds a new customer and sends the create customer API request
/// </summary>
/// <returns>The API response to the Create Customer call</returns>
public static async Task<GenericApiCallStatus> BuildAndSendCreateCustomerRequest()
{
// Build the customer
var customer = new Customer(NEW_CUSTOMER_EMAIL_ADDRESS);
customer.data.Add("first_name", "Matt");
customer.data.Add("city", "San Francisco");
customer.locale = DEFAULT_CUSTOMER_LOCALE;
// Make the API call
return await Customer.CreateOrUpdateCustomerAsync(customer);
}
}
}
| |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Xml.XPath;
using Imported.PeanutButter.Utils;
using NExpect.Implementations;
using NExpect.Interfaces;
using NExpect.MatcherLogic;
using static NExpect.Implementations.MessageHelpers;
// ReSharper disable MemberCanBePrivate.Global
namespace NExpect
{
/// <summary>
/// Provides Xml matchers via XDocument and xpath expressions
/// </summary>
public static class XmlMatchers
{
/// <summary>
/// Asserts that the provided document has a single element matched by the
/// provided xpath
/// </summary>
/// <param name="have"></param>
/// <param name="xpath"></param>
/// <returns></returns>
public static IMore<XDocument> Element(
this IHave<XDocument> have,
string xpath
)
{
return have.Element(xpath, NULL_STRING);
}
/// <summary>
/// Asserts that the provided document has a single element matched by the
/// provided xpath
/// </summary>
/// <param name="have"></param>
/// <param name="xpath"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<XDocument> Element(
this IHave<XDocument> have,
string xpath,
string customMessage
)
{
return have.Element(xpath, () => customMessage);
}
/// <summary>
/// Asserts that the provided document has a single element matched by the
/// provided xpath
/// </summary>
/// <param name="have"></param>
/// <param name="xpath"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<XDocument> Element(
this IHave<XDocument> have,
string xpath,
Func<string> customMessageGenerator
)
{
return have.AddMatcher(actual =>
{
if (actual is null)
{
return new EnforcedMatcherResult(false, "document is null");
}
var node = actual.XPathSelectElement(xpath);
actual.SetMetadata(SELECTED_NODE, node);
actual.SetMetadata(XPATH_CONTEXT, xpath);
var passed = node is not null;
return new MatcherResult(
passed,
FinalMessageFor(
() => $@"Expected document {
passed.AsNot()
}to contain node matched by '{
xpath
}':\nfull document follows:\n{
actual
}{Dump(actual)}",
customMessageGenerator
)
);
});
}
private const string SELECTED_NODE = "__xml_matchers::selected_node__";
private const string XPATH_CONTEXT = "__xml_matchers::xpath_context__";
private const string SELECTED_ATTRIBUTE = "__xml_matchers::selected_attribute__";
private const string EXPECTED_ELEMENT_TEXT = "__xml_matchers::expected_element_text__";
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="attribute"></param>
/// <returns></returns>
public static IMore<XDocument> Attribute(
this IWith<XDocument> with,
string attribute
)
{
return with.Attribute(attribute, NULL_STRING);
}
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="attribute"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<XDocument> Attribute(
this IWith<XDocument> with,
string attribute,
string customMessage
)
{
return with.Attribute(attribute, () => customMessage);
}
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="attribute"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<XDocument> Attribute(
this IWith<XDocument> with,
string attribute,
Func<string> customMessageGenerator
)
{
return with.AddMatcher(actual =>
{
if (!actual.TryGetMetadata<XElement>(SELECTED_NODE, out var el) ||
!actual.TryGetMetadata<string>(XPATH_CONTEXT, out var xpath))
{
return new EnforcedMatcherResult(false,
"no current element context; start with .To.Have.Element()");
}
var attrib = el.Attribute(attribute);
actual.SetMetadata(SELECTED_ATTRIBUTE, attrib);
var passed = attrib != null;
return new MatcherResult(
passed,
FinalMessageFor(
() => $@"Expected node selected by '{
xpath
}' {
passed.AsNot()
}to have attribute '{
attribute
}'{Dump(actual)}",
customMessageGenerator
)
);
});
}
/// <summary>
///
/// </summary>
/// <param name="having"></param>
/// <param name="value"></param>
/// <returns></returns>
public static IMore<XDocument> Value(
this IHaving<XDocument> having,
string value
)
{
return having.Value(value, NULL_STRING);
}
/// <summary>
///
/// </summary>
/// <param name="having"></param>
/// <param name="value"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<XDocument> Value(
this IHaving<XDocument> having,
string value,
string customMessage
)
{
return having.Value(value, () => customMessage);
}
/// <summary>
///
/// </summary>
/// <param name="having"></param>
/// <param name="value"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<XDocument> Value(
this IHaving<XDocument> having,
string value,
Func<string> customMessageGenerator
)
{
return having.AddMatcher(actual =>
{
if (!actual.TryGetMetadata<XAttribute>(SELECTED_ATTRIBUTE, out var attrib) ||
!actual.TryGetMetadata<string>(XPATH_CONTEXT, out var xpath))
{
return new EnforcedMatcherResult(false,
"no current attribute context; start with .To.Have.Element().With.Attribute()"
);
}
var passed = value == attrib?.Value;
return new MatcherResult(
passed,
FinalMessageFor(
() => $@"Expected node selected by '{
xpath
}' {passed.AsNot()}to have attribute '{
attrib?.Name
}' with value '{
value
}'{(passed ? "" : $" but found value '{attrib?.Value}' instead")}{
Dump(actual)
}",
customMessageGenerator
)
);
});
}
/// <summary>
///
/// </summary>
/// <param name="having"></param>
/// <param name="matching"></param>
/// <returns></returns>
public static IMore<XDocument> Value(
this IHaving<XDocument> having,
Regex matching
)
{
return having.Value(matching, NULL_STRING);
}
/// <summary>
///
/// </summary>
/// <param name="having"></param>
/// <param name="matching"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<XDocument> Value(
this IHaving<XDocument> having,
Regex matching,
string customMessage
)
{
return having.Value(matching, () => customMessage);
}
/// <summary>
///
/// </summary>
/// <param name="having"></param>
/// <param name="matching"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<XDocument> Value(
this IHaving<XDocument> having,
Regex matching,
Func<string> customMessageGenerator
)
{
return having.AddMatcher(actual =>
{
if (!actual.TryGetMetadata<XAttribute>(SELECTED_ATTRIBUTE, out var attrib) ||
!actual.TryGetMetadata<string>(XPATH_CONTEXT, out var xpath))
{
return new EnforcedMatcherResult(false,
"no current attribute context; start with .To.Have.Element().With.Attribute()"
);
}
var passed = matching.IsMatch(attrib?.Value ?? "");
return new MatcherResult(
passed,
FinalMessageFor(
() => $@"Expected node selected by '{
xpath
}' {passed.AsNot()}to have attribute '{
attrib?.Name
}' with value matching '{
matching
}'{(passed ? "" : $" but found value '{attrib?.Value}' instead")}{
Dump(actual)
}",
customMessageGenerator
)
);
});
}
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="expectedText"></param>
/// <returns></returns>
public static IMore<XDocument> Text(
this IWith<XDocument> with,
string expectedText
)
{
return with.Text(expectedText, NULL_STRING);
}
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="expectedText"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<XDocument> Text(
this IWith<XDocument> with,
string expectedText,
string customMessage
)
{
return with.Text(expectedText, () => customMessage);
}
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="expectedText"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<XDocument> Text(
this IWith<XDocument> with,
string expectedText,
Func<string> customMessageGenerator
)
{
return with.AddMatcher(actual =>
{
if (!actual.TryGetMetadata<XElement>(SELECTED_NODE, out var el) ||
!actual.TryGetMetadata<string>(XPATH_CONTEXT, out var xpath))
{
return new EnforcedMatcherResult(false,
"no current attribute context; start with .To.Have.Element()"
);
}
var text = string.Join(
" ",
el?.Nodes()
.OfType<XText>()
.Select(n => n.Value)
.ToArray() ?? new string[0]
);
var passed = text == expectedText;
return new MatcherResult(
passed,
FinalMessageFor(
() => $@"Expected {passed.AsNot()} to find text '{
expectedText
}' for node selected by '{
xpath
}'{(passed ? "" : " but found text '{text}' instead")}{
Dump(actual)
}",
customMessageGenerator
)
);
});
}
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="matcher"></param>
/// <returns></returns>
public static IMore<XDocument> Text(
this IWith<XDocument> with,
Regex matcher
)
{
return with.Text(matcher, NULL_STRING);
}
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="matcher"></param>
/// <param name="customMessage"></param>
/// <returns></returns>
public static IMore<XDocument> Text(
this IWith<XDocument> with,
Regex matcher,
string customMessage
)
{
return with.Text(matcher, () => customMessage);
}
/// <summary>
///
/// </summary>
/// <param name="with"></param>
/// <param name="matcher"></param>
/// <param name="customMessageGenerator"></param>
/// <returns></returns>
public static IMore<XDocument> Text(
this IWith<XDocument> with,
Regex matcher,
Func<string> customMessageGenerator
)
{
return with.AddMatcher(actual =>
{
if (!actual.TryGetMetadata<XElement>(SELECTED_NODE, out var el) ||
!actual.TryGetMetadata<string>(XPATH_CONTEXT, out var xpath))
{
return new EnforcedMatcherResult(false,
"no current attribute context; start with .To.Have.Element()"
);
}
var text = string.Join(
" ",
el?.Nodes()
.OfType<XText>()
.Select(n => n.Value)
.ToArray() ?? new string[0]
);
var passed = matcher.IsMatch(text ?? "");
return new MatcherResult(
passed,
FinalMessageFor(
() => $@"Expected {passed.AsNot()} to find text matching {
matcher
} for node selected by '{
xpath
}'{(passed ? "" : " but found text '{text}' instead")}{
Dump(actual)
}",
customMessageGenerator
)
);
});
}
private static string Dump(XDocument doc)
{
return $"\nfull document follows:\n{doc}";
}
}
}
| |
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class ErrorFacts
{
public static bool IsWarning(ErrorCode code)
{
switch (code)
{
case ErrorCode.WRN_InvalidMainSig:
case ErrorCode.WRN_UnreferencedEvent:
case ErrorCode.WRN_LowercaseEllSuffix:
case ErrorCode.WRN_DuplicateUsing:
case ErrorCode.WRN_NewRequired:
case ErrorCode.WRN_NewNotRequired:
case ErrorCode.WRN_NewOrOverrideExpected:
case ErrorCode.WRN_UnreachableCode:
case ErrorCode.WRN_UnreferencedLabel:
case ErrorCode.WRN_UnreferencedVar:
case ErrorCode.WRN_UnreferencedField:
case ErrorCode.WRN_IsAlwaysTrue:
case ErrorCode.WRN_IsAlwaysFalse:
case ErrorCode.WRN_ByRefNonAgileField:
case ErrorCode.WRN_UnreferencedVarAssg:
case ErrorCode.WRN_NegativeArrayIndex:
case ErrorCode.WRN_BadRefCompareLeft:
case ErrorCode.WRN_BadRefCompareRight:
case ErrorCode.WRN_PatternIsAmbiguous:
case ErrorCode.WRN_PatternStaticOrInaccessible:
case ErrorCode.WRN_PatternBadSignature:
case ErrorCode.WRN_SequentialOnPartialClass:
case ErrorCode.WRN_MainCantBeGeneric:
case ErrorCode.WRN_UnreferencedFieldAssg:
case ErrorCode.WRN_AmbiguousXMLReference:
case ErrorCode.WRN_VolatileByRef:
case ErrorCode.WRN_SameFullNameThisNsAgg:
case ErrorCode.WRN_SameFullNameThisAggAgg:
case ErrorCode.WRN_SameFullNameThisAggNs:
case ErrorCode.WRN_GlobalAliasDefn:
case ErrorCode.WRN_AlwaysNull:
case ErrorCode.WRN_CmpAlwaysFalse:
case ErrorCode.WRN_FinalizeMethod:
case ErrorCode.WRN_GotoCaseShouldConvert:
case ErrorCode.WRN_NubExprIsConstBool:
case ErrorCode.WRN_ExplicitImplCollision:
case ErrorCode.WRN_DeprecatedSymbol:
case ErrorCode.WRN_DeprecatedSymbolStr:
case ErrorCode.WRN_ExternMethodNoImplementation:
case ErrorCode.WRN_ProtectedInSealed:
case ErrorCode.WRN_PossibleMistakenNullStatement:
case ErrorCode.WRN_UnassignedInternalField:
case ErrorCode.WRN_VacuousIntegralComp:
case ErrorCode.WRN_AttributeLocationOnBadDeclaration:
case ErrorCode.WRN_InvalidAttributeLocation:
case ErrorCode.WRN_EqualsWithoutGetHashCode:
case ErrorCode.WRN_EqualityOpWithoutEquals:
case ErrorCode.WRN_EqualityOpWithoutGetHashCode:
case ErrorCode.WRN_IncorrectBooleanAssg:
case ErrorCode.WRN_NonObsoleteOverridingObsolete:
case ErrorCode.WRN_BitwiseOrSignExtend:
case ErrorCode.WRN_CoClassWithoutComImport:
case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter:
case ErrorCode.WRN_AssignmentToLockOrDispose:
case ErrorCode.WRN_ObsoleteOverridingNonObsolete:
case ErrorCode.WRN_DebugFullNameTooLong:
case ErrorCode.WRN_ExternCtorNoImplementation:
case ErrorCode.WRN_WarningDirective:
case ErrorCode.WRN_UnreachableGeneralCatch:
case ErrorCode.WRN_DeprecatedCollectionInitAddStr:
case ErrorCode.WRN_DeprecatedCollectionInitAdd:
case ErrorCode.WRN_DefaultValueForUnconsumedLocation:
case ErrorCode.WRN_IdentifierOrNumericLiteralExpected:
case ErrorCode.WRN_EmptySwitch:
case ErrorCode.WRN_XMLParseError:
case ErrorCode.WRN_DuplicateParamTag:
case ErrorCode.WRN_UnmatchedParamTag:
case ErrorCode.WRN_MissingParamTag:
case ErrorCode.WRN_BadXMLRef:
case ErrorCode.WRN_BadXMLRefParamType:
case ErrorCode.WRN_BadXMLRefReturnType:
case ErrorCode.WRN_BadXMLRefSyntax:
case ErrorCode.WRN_UnprocessedXMLComment:
case ErrorCode.WRN_FailedInclude:
case ErrorCode.WRN_InvalidInclude:
case ErrorCode.WRN_MissingXMLComment:
case ErrorCode.WRN_XMLParseIncludeError:
case ErrorCode.WRN_ALinkWarn:
case ErrorCode.WRN_CmdOptionConflictsSource:
case ErrorCode.WRN_IllegalPragma:
case ErrorCode.WRN_IllegalPPWarning:
case ErrorCode.WRN_BadRestoreNumber:
case ErrorCode.WRN_NonECMAFeature:
case ErrorCode.WRN_ErrorOverride:
case ErrorCode.WRN_InvalidSearchPathDir:
case ErrorCode.WRN_MultiplePredefTypes:
case ErrorCode.WRN_TooManyLinesForDebugger:
case ErrorCode.WRN_CallOnNonAgileField:
case ErrorCode.WRN_InvalidNumber:
case ErrorCode.WRN_IllegalPPChecksum:
case ErrorCode.WRN_EndOfPPLineExpected:
case ErrorCode.WRN_ConflictingChecksum:
case ErrorCode.WRN_InvalidAssemblyName:
case ErrorCode.WRN_UnifyReferenceMajMin:
case ErrorCode.WRN_UnifyReferenceBldRev:
case ErrorCode.WRN_DuplicateTypeParamTag:
case ErrorCode.WRN_UnmatchedTypeParamTag:
case ErrorCode.WRN_MissingTypeParamTag:
case ErrorCode.WRN_AssignmentToSelf:
case ErrorCode.WRN_ComparisonToSelf:
case ErrorCode.WRN_DotOnDefault:
case ErrorCode.WRN_BadXMLRefTypeVar:
case ErrorCode.WRN_UnmatchedParamRefTag:
case ErrorCode.WRN_UnmatchedTypeParamRefTag:
case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA:
case ErrorCode.WRN_CantHaveManifestForModule:
case ErrorCode.WRN_MultipleRuntimeImplementationMatches:
case ErrorCode.WRN_MultipleRuntimeOverrideMatches:
case ErrorCode.WRN_DynamicDispatchToConditionalMethod:
case ErrorCode.WRN_IsDynamicIsConfusing:
case ErrorCode.WRN_AsyncLacksAwaits:
case ErrorCode.WRN_FileAlreadyIncluded:
case ErrorCode.WRN_NoSources:
case ErrorCode.WRN_NoConfigNotOnCommandLine:
case ErrorCode.WRN_DefineIdentifierRequired:
case ErrorCode.WRN_BadUILang:
case ErrorCode.WRN_CLS_NoVarArgs:
case ErrorCode.WRN_CLS_BadArgType:
case ErrorCode.WRN_CLS_BadReturnType:
case ErrorCode.WRN_CLS_BadFieldPropType:
case ErrorCode.WRN_CLS_BadIdentifierCase:
case ErrorCode.WRN_CLS_OverloadRefOut:
case ErrorCode.WRN_CLS_OverloadUnnamed:
case ErrorCode.WRN_CLS_BadIdentifier:
case ErrorCode.WRN_CLS_BadBase:
case ErrorCode.WRN_CLS_BadInterfaceMember:
case ErrorCode.WRN_CLS_NoAbstractMembers:
case ErrorCode.WRN_CLS_NotOnModules:
case ErrorCode.WRN_CLS_ModuleMissingCLS:
case ErrorCode.WRN_CLS_AssemblyNotCLS:
case ErrorCode.WRN_CLS_BadAttributeType:
case ErrorCode.WRN_CLS_ArrayArgumentToAttribute:
case ErrorCode.WRN_CLS_NotOnModules2:
case ErrorCode.WRN_CLS_IllegalTrueInFalse:
case ErrorCode.WRN_CLS_MeaninglessOnPrivateType:
case ErrorCode.WRN_CLS_AssemblyNotCLS2:
case ErrorCode.WRN_CLS_MeaninglessOnParam:
case ErrorCode.WRN_CLS_MeaninglessOnReturn:
case ErrorCode.WRN_CLS_BadTypeVar:
case ErrorCode.WRN_CLS_VolatileField:
case ErrorCode.WRN_CLS_BadInterface:
case ErrorCode.WRN_UnobservedAwaitableExpression:
case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation:
case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation:
case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation:
case ErrorCode.WRN_MainIgnored:
case ErrorCode.WRN_DelaySignButNoKey:
case ErrorCode.WRN_InvalidVersionFormat:
case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName:
case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName:
case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath:
case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden:
case ErrorCode.WRN_FilterIsConstant:
case ErrorCode.WRN_UnimplementedCommandLineSwitch:
case ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName:
case ErrorCode.WRN_RefCultureMismatch:
case ErrorCode.WRN_ConflictingMachineAssembly:
case ErrorCode.WRN_UnqualifiedNestedTypeInCref:
case ErrorCode.WRN_NoRuntimeMetadataVersion:
case ErrorCode.WRN_PdbLocalNameTooLong:
case ErrorCode.WRN_AnalyzerCannotBeCreated:
case ErrorCode.WRN_NoAnalyzerInAssembly:
case ErrorCode.WRN_UnableToLoadAnalyzer:
case ErrorCode.WRN_NubExprIsConstBool2:
case ErrorCode.WRN_AlignmentMagnitude:
case ErrorCode.WRN_AttributeIgnoredWhenPublicSigning:
case ErrorCode.WRN_TupleLiteralNameMismatch:
case ErrorCode.WRN_Experimental:
case ErrorCode.WRN_DefaultInSwitch:
return true;
default:
return false;
}
}
public static bool IsFatal(ErrorCode code)
{
switch (code)
{
case ErrorCode.FTL_MetadataCantOpenFile:
case ErrorCode.FTL_DebugEmitFailure:
case ErrorCode.FTL_BadCodepage:
case ErrorCode.FTL_InvalidTarget:
case ErrorCode.FTL_InputFileNameTooLong:
case ErrorCode.FTL_OutputFileExists:
case ErrorCode.FTL_BadChecksumAlgorithm:
return true;
default:
return false;
}
}
public static bool IsInfo(ErrorCode code)
{
switch (code)
{
case ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer:
return true;
default:
return false;
}
}
public static bool IsHidden(ErrorCode code)
{
switch (code)
{
case ErrorCode.HDN_UnusedUsingDirective:
case ErrorCode.HDN_UnusedExternAlias:
return true;
default:
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using DarkMultiPlayerCommon;
using MessageStream2;
namespace DarkMultiPlayer
{
public class ChatWorker
{
public bool display = false;
public bool workerEnabled = false;
private bool isWindowLocked = false;
private bool safeDisplay = false;
private bool initialized = false;
//State tracking
private Queue<string> disconnectingPlayers = new Queue<string>();
private Queue<JoinLeaveMessage> newJoinMessages = new Queue<JoinLeaveMessage>();
private Queue<JoinLeaveMessage> newLeaveMessages = new Queue<JoinLeaveMessage>();
private Queue<ChannelEntry> newChannelMessages = new Queue<ChannelEntry>();
private Queue<PrivateEntry> newPrivateMessages = new Queue<PrivateEntry>();
private Queue<ConsoleEntry> newConsoleMessages = new Queue<ConsoleEntry>();
private Dictionary<string, List<string>> channelMessages = new Dictionary<string, List<string>>();
private Dictionary<string, List<string>> privateMessages = new Dictionary<string, List<string>>();
private List<string> consoleMessages = new List<string>();
private Dictionary<string, List<string>> playerChannels = new Dictionary<string, List<string>>();
private List<string> joinedChannels = new List<string>();
private List<string> joinedPMChannels = new List<string>();
private List<string> highlightChannel = new List<string>();
private List<string> highlightPM = new List<string>();
public bool chatButtonHighlighted = false;
private string selectedChannel = null;
private string selectedPMChannel = null;
private bool chatLocked = false;
private bool ignoreChatInput = false;
private bool selectTextBox = false;
private int previousTextID = 0;
private string sendText = "";
public string consoleIdentifier = "";
//chat command register
private Dictionary<string, ChatCommand> registeredChatCommands = new Dictionary<string, ChatCommand>();
//event handling
private bool leaveEventHandled = true;
private bool sendEventHandled = true;
//GUILayout stuff
private Rect windowRect;
private Rect moveRect;
private GUILayoutOption[] windowLayoutOptions;
private GUILayoutOption[] smallSizeOption;
private GUIStyle windowStyle;
private GUIStyle labelStyle;
private GUIStyle buttonStyle;
private GUIStyle highlightStyle;
private GUIStyle textAreaStyle;
private GUIStyle scrollStyle;
private Vector2 chatScrollPos;
private Vector2 playerScrollPos;
//window size
private float WINDOW_HEIGHT = 300;
private float WINDOW_WIDTH = 400;
//const
private const string DMP_CHAT_LOCK = "DMP_ChatLock";
private const string DMP_CHAT_WINDOW_LOCK = "DMP_Chat_Window_Lock";
//Services
private DMPGame dmpGame;
private Settings dmpSettings;
private NetworkWorker networkWorker;
private AdminSystem adminSystem;
private PlayerStatusWorker playerStatusWorker;
private NamedAction updateAction;
private NamedAction drawAction;
public ChatWorker(DMPGame dmpGame, Settings dmpSettings, NetworkWorker networkWorker, AdminSystem adminSystem, PlayerStatusWorker playerStatusWorker)
{
this.dmpGame = dmpGame;
this.dmpSettings = dmpSettings;
this.networkWorker = networkWorker;
this.adminSystem = adminSystem;
this.playerStatusWorker = playerStatusWorker;
RegisterChatCommand("help", DisplayHelp, "Displays this help");
RegisterChatCommand("join", JoinChannel, "Joins a new chat channel");
RegisterChatCommand("query", StartQuery, "Starts a query");
RegisterChatCommand("leave", LeaveChannel, "Leaves the current channel");
RegisterChatCommand("part", LeaveChannel, "Leaves the current channel");
RegisterChatCommand("ping", ServerPing, "Pings the server");
RegisterChatCommand("motd", ServerMOTD, "Gets the current Message of the Day");
RegisterChatCommand("resize", ResizeChat, "Resized the chat window");
RegisterChatCommand("version", DisplayVersion, "Displays the current version of DMP");
updateAction = new NamedAction(Update);
drawAction = new NamedAction(Draw);
dmpGame.updateEvent.Add(updateAction);
dmpGame.drawEvent.Add(drawAction);
}
private void PrintToSelectedChannel(string text)
{
if (selectedChannel == null && selectedPMChannel == null)
{
QueueChannelMessage(dmpSettings.playerName, "", text);
}
if (selectedChannel != null && selectedChannel != consoleIdentifier)
{
QueueChannelMessage(dmpSettings.playerName, selectedChannel, text);
}
if (selectedChannel == consoleIdentifier)
{
QueueSystemMessage(text);
}
if (selectedPMChannel != null)
{
QueuePrivateMessage(dmpSettings.playerName, selectedPMChannel, text);
}
}
private void DisplayHelp(string commandArgs)
{
List<ChatCommand> commands = new List<ChatCommand>();
int longestName = 0;
foreach (ChatCommand cmd in registeredChatCommands.Values)
{
commands.Add(cmd);
if (cmd.name.Length > longestName)
{
longestName = cmd.name.Length;
}
}
commands.Sort();
foreach (ChatCommand cmd in commands)
{
string helpText = cmd.name.PadRight(longestName) + " - " + cmd.description;
PrintToSelectedChannel(helpText);
}
}
private void DisplayVersion(string commandArgs)
{
string versionMessage = (Common.PROGRAM_VERSION.Length == 40) ? "DarkMultiPlayer development build " + Common.PROGRAM_VERSION.Substring(0, 7) : "DarkMultiPlayer " + Common.PROGRAM_VERSION;
PrintToSelectedChannel(versionMessage);
}
private void JoinChannel(string commandArgs)
{
if (commandArgs != "" && commandArgs != "Global" && commandArgs != consoleIdentifier && commandArgs != "#Global" && commandArgs != "#" + consoleIdentifier)
{
if (commandArgs.StartsWith("#", StringComparison.Ordinal))
{
commandArgs = commandArgs.Substring(1);
}
if (!joinedChannels.Contains(commandArgs))
{
DarkLog.Debug("Joining channel " + commandArgs);
joinedChannels.Add(commandArgs);
selectedChannel = commandArgs;
selectedPMChannel = null;
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.JOIN);
mw.Write<string>(dmpSettings.playerName);
mw.Write<string>(commandArgs);
networkWorker.SendChatMessage(mw.GetMessageBytes());
}
}
}
else
{
ScreenMessages.PostScreenMessage("Couldn't join '" + commandArgs + "', channel name not valid!");
}
}
private void LeaveChannel(string commandArgs)
{
leaveEventHandled = false;
}
private void StartQuery(string commandArgs)
{
bool playerFound = false;
if (commandArgs != consoleIdentifier)
{
foreach (PlayerStatus ps in playerStatusWorker.playerStatusList)
{
if (ps.playerName == commandArgs)
{
playerFound = true;
}
}
}
else
{
//Make sure we can always query the server.
playerFound = true;
}
if (playerFound)
{
if (!joinedPMChannels.Contains(commandArgs))
{
DarkLog.Debug("Starting query with " + commandArgs);
joinedPMChannels.Add(commandArgs);
selectedChannel = null;
selectedPMChannel = commandArgs;
}
}
else
{
ScreenMessages.PostScreenMessage("Couldn't start query with '" + commandArgs + "', player not found!");
}
}
private void ServerPing(string commandArgs)
{
networkWorker.SendPingRequest();
}
private void ServerMOTD(string commandArgs)
{
networkWorker.SendMotdRequest();
}
private void ResizeChat(string commandArgs)
{
string func = "";
float size = 0;
func = commandArgs;
if (commandArgs.Contains(" "))
{
func = commandArgs.Substring(0, commandArgs.IndexOf(" ", StringComparison.Ordinal));
if (commandArgs.Substring(func.Length).Contains(" "))
{
try
{
size = Convert.ToSingle(commandArgs.Substring(func.Length + 1));
}
catch (FormatException)
{
PrintToSelectedChannel("Error: " + size + " is not a valid number");
size = 400f;
}
}
}
switch (func)
{
default:
PrintToSelectedChannel("Undefined function. Usage: /resize [default|medium|large], /resize [x|y] size, or /resize show");
PrintToSelectedChannel("Chat window size is currently: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
case "x":
if (size <= 800 && size >= 300)
{
WINDOW_WIDTH = size;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
}
else
{
PrintToSelectedChannel("Size is out of range.");
}
break;
case "y":
if (size <= 800 && size >= 300)
{
WINDOW_HEIGHT = size;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
}
else
{
PrintToSelectedChannel("Size is out of range.");
}
break;
case "default":
WINDOW_HEIGHT = 300;
WINDOW_WIDTH = 400;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
case "medium":
WINDOW_HEIGHT = 600;
WINDOW_WIDTH = 600;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
case "large":
WINDOW_HEIGHT = 800;
WINDOW_WIDTH = 800;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
case "show":
PrintToSelectedChannel("Chat window size is currently: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
}
}
private void InitGUI()
{
//Setup GUI stuff
windowRect = new Rect(Screen.width / 10, Screen.height / 2f - WINDOW_HEIGHT / 2f, WINDOW_WIDTH, WINDOW_HEIGHT);
moveRect = new Rect(0, 0, 10000, 20);
windowLayoutOptions = new GUILayoutOption[4];
windowLayoutOptions[0] = GUILayout.MinWidth(WINDOW_WIDTH);
windowLayoutOptions[1] = GUILayout.MaxWidth(WINDOW_WIDTH);
windowLayoutOptions[2] = GUILayout.MinHeight(WINDOW_HEIGHT);
windowLayoutOptions[3] = GUILayout.MaxHeight(WINDOW_HEIGHT);
smallSizeOption = new GUILayoutOption[1];
smallSizeOption[0] = GUILayout.Width(WINDOW_WIDTH * .25f);
windowStyle = new GUIStyle(GUI.skin.window);
scrollStyle = new GUIStyle(GUI.skin.scrollView);
chatScrollPos = new Vector2(0, 0);
labelStyle = new GUIStyle(GUI.skin.label);
buttonStyle = new GUIStyle(GUI.skin.button);
highlightStyle = new GUIStyle(GUI.skin.button);
highlightStyle.normal.textColor = Color.red;
highlightStyle.active.textColor = Color.red;
highlightStyle.hover.textColor = Color.red;
textAreaStyle = new GUIStyle(GUI.skin.textArea);
}
public void QueueChatJoin(string playerName, string channelName)
{
JoinLeaveMessage jlm = new JoinLeaveMessage();
jlm.fromPlayer = playerName;
jlm.channel = channelName;
newJoinMessages.Enqueue(jlm);
}
public void QueueChatLeave(string playerName, string channelName)
{
JoinLeaveMessage jlm = new JoinLeaveMessage();
jlm.fromPlayer = playerName;
jlm.channel = channelName;
newLeaveMessages.Enqueue(jlm);
}
public void QueueChannelMessage(string fromPlayer, string channelName, string channelMessage)
{
// Check if any of these is null before doing anything else
if (!string.IsNullOrEmpty(fromPlayer) && !string.IsNullOrEmpty(channelMessage))
{
ChannelEntry ce = new ChannelEntry();
ce.fromPlayer = fromPlayer;
ce.channel = channelName;
ce.message = channelMessage;
newChannelMessages.Enqueue(ce);
}
}
public void QueuePrivateMessage(string fromPlayer, string toPlayer, string privateMessage)
{
PrivateEntry pe = new PrivateEntry();
pe.fromPlayer = fromPlayer;
pe.toPlayer = toPlayer;
pe.message = privateMessage;
newPrivateMessages.Enqueue(pe);
}
public void QueueRemovePlayer(string playerName)
{
disconnectingPlayers.Enqueue(playerName);
}
public void PMMessageServer(string message)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.PRIVATE_MESSAGE);
mw.Write<string>(dmpSettings.playerName);
mw.Write<string>(consoleIdentifier);
mw.Write<string>(message);
networkWorker.SendChatMessage(mw.GetMessageBytes());
}
}
public void QueueSystemMessage(string message)
{
ConsoleEntry ce = new ConsoleEntry();
ce.message = message;
newConsoleMessages.Enqueue(ce);
}
public void RegisterChatCommand(string command, Action<string> func, string description)
{
ChatCommand cmd = new ChatCommand(command, func, description);
if (!registeredChatCommands.ContainsKey(command))
{
registeredChatCommands.Add(command, cmd);
}
}
public void HandleChatInput(string input)
{
if (!input.StartsWith("/", StringComparison.Ordinal) || input.StartsWith("//", StringComparison.Ordinal))
{
//Handle chat messages
if (input.StartsWith("//", StringComparison.Ordinal))
{
input = input.Substring(1);
}
if (selectedChannel == null && selectedPMChannel == null)
{
//Sending a global chat message
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.CHANNEL_MESSAGE);
mw.Write<string>(dmpSettings.playerName);
//Global channel name is empty string.
mw.Write<string>("");
mw.Write<string>(input);
networkWorker.SendChatMessage(mw.GetMessageBytes());
}
}
if (selectedChannel != null && selectedChannel != consoleIdentifier)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.CHANNEL_MESSAGE);
mw.Write<string>(dmpSettings.playerName);
mw.Write<string>(selectedChannel);
mw.Write<string>(input);
networkWorker.SendChatMessage(mw.GetMessageBytes());
}
}
if (selectedChannel == consoleIdentifier)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.CONSOLE_MESSAGE);
mw.Write<string>(dmpSettings.playerName);
mw.Write<string>(input);
networkWorker.SendChatMessage(mw.GetMessageBytes());
DarkLog.Debug("Server Command: " + input);
}
}
if (selectedPMChannel != null)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.PRIVATE_MESSAGE);
mw.Write<string>(dmpSettings.playerName);
mw.Write<string>(selectedPMChannel);
mw.Write<string>(input);
networkWorker.SendChatMessage(mw.GetMessageBytes());
}
}
}
else
{
string commandPart = input.Substring(1);
string argumentPart = "";
if (commandPart.Contains(" "))
{
if (commandPart.Length > commandPart.IndexOf(' ') + 1)
{
argumentPart = commandPart.Substring(commandPart.IndexOf(' ') + 1);
}
commandPart = commandPart.Substring(0, commandPart.IndexOf(' '));
}
if (commandPart.Length > 0)
{
if (registeredChatCommands.ContainsKey(commandPart))
{
try
{
DarkLog.Debug("Chat Command: " + input.Substring(1));
registeredChatCommands[commandPart].func(argumentPart);
}
catch (Exception e)
{
DarkLog.Debug("Error handling chat command " + commandPart + ", Exception " + e);
PrintToSelectedChannel("Error handling chat command: " + commandPart);
}
}
else
{
PrintToSelectedChannel("Unknown chat command: " + commandPart);
}
}
}
}
private void HandleChatEvents()
{
//Handle leave event
if (!leaveEventHandled)
{
if (!string.IsNullOrEmpty(selectedChannel) && selectedChannel != consoleIdentifier)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.LEAVE);
mw.Write<string>(dmpSettings.playerName);
mw.Write<string>(selectedChannel);
networkWorker.SendChatMessage(mw.GetMessageBytes());
}
if (joinedChannels.Contains(selectedChannel))
{
joinedChannels.Remove(selectedChannel);
}
selectedChannel = null;
selectedPMChannel = null;
}
if (!string.IsNullOrEmpty(selectedPMChannel))
{
if (joinedPMChannels.Contains(selectedPMChannel))
{
joinedPMChannels.Remove(selectedPMChannel);
}
selectedChannel = null;
selectedPMChannel = null;
}
leaveEventHandled = true;
}
//Handle send event
if (!sendEventHandled)
{
if (sendText != "")
{
HandleChatInput(sendText);
}
sendText = "";
sendEventHandled = true;
}
//Handle join messages
while (newJoinMessages.Count > 0)
{
JoinLeaveMessage jlm = newJoinMessages.Dequeue();
if (!playerChannels.ContainsKey(jlm.fromPlayer))
{
playerChannels.Add(jlm.fromPlayer, new List<string>());
}
if (!playerChannels[jlm.fromPlayer].Contains(jlm.channel))
{
playerChannels[jlm.fromPlayer].Add(jlm.channel);
}
}
//Handle leave messages
while (newLeaveMessages.Count > 0)
{
JoinLeaveMessage jlm = newLeaveMessages.Dequeue();
if (playerChannels.ContainsKey(jlm.fromPlayer))
{
if (playerChannels[jlm.fromPlayer].Contains(jlm.channel))
{
playerChannels[jlm.fromPlayer].Remove(jlm.channel);
}
if (playerChannels[jlm.fromPlayer].Count == 0)
{
playerChannels.Remove(jlm.fromPlayer);
}
}
}
//Handle channel messages
while (newChannelMessages.Count > 0)
{
ChannelEntry ce = newChannelMessages.Dequeue();
if (!channelMessages.ContainsKey(ce.channel))
{
channelMessages.Add(ce.channel, new List<string>());
}
// Write message to screen if chat window is disabled
if (!display)
{
chatButtonHighlighted = ce.fromPlayer != consoleIdentifier;
if (!string.IsNullOrEmpty(ce.channel))
ScreenMessages.PostScreenMessage(ce.fromPlayer + " -> #" + ce.channel + ": " + ce.message, 5f, ScreenMessageStyle.UPPER_LEFT);
else
ScreenMessages.PostScreenMessage(ce.fromPlayer + " -> #Global : " + ce.message, 5f, ScreenMessageStyle.UPPER_LEFT);
}
//Highlight if the channel isn't selected.
if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(ce.channel) && ce.fromPlayer != consoleIdentifier)
{
if (!highlightChannel.Contains(ce.channel))
highlightChannel.Add(ce.channel);
}
if (!string.IsNullOrEmpty(ce.channel) && ce.channel != selectedChannel)
{
if (!highlightChannel.Contains(ce.channel))
highlightChannel.Add(ce.channel);
}
//Move the bar to the bottom on a new message
if (string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && string.IsNullOrEmpty(ce.channel))
{
chatScrollPos.y = float.PositiveInfinity;
selectTextBox = chatLocked;
}
if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && ce.channel == selectedChannel)
{
chatScrollPos.y = float.PositiveInfinity;
selectTextBox = chatLocked;
}
channelMessages[ce.channel].Add(ce.fromPlayer + ": " + ce.message);
}
//Handle private messages
while (newPrivateMessages.Count > 0)
{
PrivateEntry pe = newPrivateMessages.Dequeue();
if (pe.fromPlayer != dmpSettings.playerName)
{
if (!privateMessages.ContainsKey(pe.fromPlayer))
{
privateMessages.Add(pe.fromPlayer, new List<string>());
}
//Highlight if the player isn't selected
if (!joinedPMChannels.Contains(pe.fromPlayer))
{
joinedPMChannels.Add(pe.fromPlayer);
}
if (selectedPMChannel != pe.fromPlayer)
{
if (!highlightPM.Contains(pe.fromPlayer))
{
highlightPM.Add(pe.fromPlayer);
}
}
}
if (!privateMessages.ContainsKey(pe.toPlayer))
{
privateMessages.Add(pe.toPlayer, new List<string>());
}
//Move the bar to the bottom on a new message
if (!string.IsNullOrEmpty(selectedPMChannel) && string.IsNullOrEmpty(selectedChannel) && (pe.fromPlayer == selectedPMChannel || pe.fromPlayer == dmpSettings.playerName))
{
chatScrollPos.y = float.PositiveInfinity;
selectTextBox = chatLocked;
}
if (pe.fromPlayer != dmpSettings.playerName)
{
privateMessages[pe.fromPlayer].Add(pe.fromPlayer + ": " + pe.message);
if (!display)
{
chatButtonHighlighted = true;
ScreenMessages.PostScreenMessage(pe.fromPlayer + " -> @" + pe.toPlayer + ": " + pe.message, 5f, ScreenMessageStyle.UPPER_LEFT);
}
}
else
{
privateMessages[pe.toPlayer].Add(pe.fromPlayer + ": " + pe.message);
}
}
//Handle console messages
while (newConsoleMessages.Count > 0)
{
ConsoleEntry ce = newConsoleMessages.Dequeue();
//Highlight if the channel isn't selected.
if (selectedChannel != consoleIdentifier)
{
if (!highlightChannel.Contains(consoleIdentifier))
{
highlightChannel.Add(consoleIdentifier);
}
}
//Move the bar to the bottom on a new message
if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && consoleIdentifier == selectedChannel)
{
chatScrollPos.y = float.PositiveInfinity;
selectTextBox = chatLocked;
}
consoleMessages.Add(ce.message);
}
while (disconnectingPlayers.Count > 0)
{
string disconnectingPlayer = disconnectingPlayers.Dequeue();
if (playerChannels.ContainsKey(disconnectingPlayer))
{
playerChannels.Remove(disconnectingPlayer);
}
if (joinedPMChannels.Contains(disconnectingPlayer))
{
joinedPMChannels.Remove(disconnectingPlayer);
}
if (highlightPM.Contains(disconnectingPlayer))
{
highlightPM.Remove(disconnectingPlayer);
}
if (privateMessages.ContainsKey(disconnectingPlayer))
{
privateMessages.Remove(disconnectingPlayer);
}
}
}
private void Update()
{
safeDisplay = display;
ignoreChatInput = false;
if (chatButtonHighlighted && display)
{
chatButtonHighlighted = false;
}
if (chatLocked && !display)
{
chatLocked = false;
InputLockManager.RemoveControlLock(DMP_CHAT_LOCK);
}
if (workerEnabled)
{
HandleChatEvents();
}
}
public void Draw()
{
if (safeDisplay)
{
if (!initialized)
{
InitGUI();
initialized = true;
}
bool pressedChatShortcutKey = (Event.current.type == EventType.KeyDown && Event.current.keyCode == dmpSettings.chatKey);
if (pressedChatShortcutKey)
{
ignoreChatInput = true;
selectTextBox = true;
}
windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6704 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer Chat", windowStyle, windowLayoutOptions));
}
CheckWindowLock();
}
private void DrawContent(int windowID)
{
bool pressedEnter = (Event.current.type == EventType.KeyDown && !Event.current.shift && Event.current.character == '\n');
GUILayout.BeginVertical();
GUI.DragWindow(moveRect);
GUILayout.BeginHorizontal();
DrawRooms();
GUILayout.FlexibleSpace();
if (selectedChannel != null && selectedChannel != consoleIdentifier || selectedPMChannel != null)
{
if (GUILayout.Button("Leave", buttonStyle))
{
leaveEventHandled = false;
}
}
DrawConsole();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
chatScrollPos = GUILayout.BeginScrollView(chatScrollPos, scrollStyle);
if (selectedChannel == null && selectedPMChannel == null)
{
if (!channelMessages.ContainsKey(""))
{
channelMessages.Add("", new List<string>());
}
foreach (string channelMessage in channelMessages[""])
{
GUILayout.Label(channelMessage, labelStyle);
}
}
if (selectedChannel != null && selectedChannel != consoleIdentifier)
{
if (!channelMessages.ContainsKey(selectedChannel))
{
channelMessages.Add(selectedChannel, new List<string>());
}
foreach (string channelMessage in channelMessages[selectedChannel])
{
GUILayout.Label(channelMessage, labelStyle);
}
}
if (selectedChannel == consoleIdentifier)
{
foreach (string consoleMessage in consoleMessages)
{
GUILayout.Label(consoleMessage, labelStyle);
}
}
if (selectedPMChannel != null)
{
if (!privateMessages.ContainsKey(selectedPMChannel))
{
privateMessages.Add(selectedPMChannel, new List<string>());
}
foreach (string privateMessage in privateMessages[selectedPMChannel])
{
GUILayout.Label(privateMessage, labelStyle);
}
}
GUILayout.EndScrollView();
playerScrollPos = GUILayout.BeginScrollView(playerScrollPos, scrollStyle, smallSizeOption);
GUILayout.BeginVertical();
GUILayout.Label(dmpSettings.playerName, labelStyle);
if (selectedPMChannel != null)
{
GUILayout.Label(selectedPMChannel, labelStyle);
}
else
{
if (selectedChannel == null)
{
//Global chat
foreach (PlayerStatus player in playerStatusWorker.playerStatusList)
{
if (joinedPMChannels.Contains(player.playerName))
{
GUI.enabled = false;
}
if (GUILayout.Button(player.playerName, labelStyle))
{
if (!joinedPMChannels.Contains(player.playerName))
{
joinedPMChannels.Add(player.playerName);
}
}
GUI.enabled = true;
}
}
else
{
foreach (KeyValuePair<string, List<string>> playerEntry in playerChannels)
{
if (playerEntry.Key != dmpSettings.playerName)
{
if (playerEntry.Value.Contains(selectedChannel))
{
if (joinedPMChannels.Contains(playerEntry.Key))
{
GUI.enabled = false;
}
if (GUILayout.Button(playerEntry.Key, labelStyle))
{
if (!joinedPMChannels.Contains(playerEntry.Key))
{
joinedPMChannels.Add(playerEntry.Key);
}
}
GUI.enabled = true;
}
}
}
}
}
GUILayout.EndVertical();
GUILayout.EndScrollView();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUI.SetNextControlName("SendTextArea");
string tempSendText = GUILayout.TextArea(sendText, textAreaStyle);
//When a control is inserted or removed from the GUI, Unity's focusing starts tripping balls. This is a horrible workaround for unity that shouldn't exist...
int newTextID = GUIUtility.GetControlID(FocusType.Keyboard);
if (previousTextID != newTextID)
{
previousTextID = newTextID;
if (chatLocked)
{
selectTextBox = true;
}
}
//Don't add the newline to the messages, queue a send
if (!ignoreChatInput)
{
if (pressedEnter)
{
sendEventHandled = false;
}
else
{
sendText = tempSendText;
}
}
if (sendText == "")
{
GUI.enabled = false;
}
if (GUILayout.Button("Send", buttonStyle, smallSizeOption))
{
sendEventHandled = false;
}
GUI.enabled = true;
GUILayout.EndHorizontal();
GUILayout.EndVertical();
if (!selectTextBox)
{
if ((GUI.GetNameOfFocusedControl() == "SendTextArea") && !chatLocked)
{
chatLocked = true;
InputLockManager.SetControlLock(DMPGuiUtil.BLOCK_ALL_CONTROLS, DMP_CHAT_LOCK);
}
if ((GUI.GetNameOfFocusedControl() != "SendTextArea") && chatLocked)
{
chatLocked = false;
InputLockManager.RemoveControlLock(DMP_CHAT_LOCK);
}
}
else
{
selectTextBox = false;
GUI.FocusControl("SendTextArea");
}
}
private void DrawConsole()
{
GUIStyle possibleHighlightButtonStyle = buttonStyle;
if (selectedChannel == consoleIdentifier)
{
GUI.enabled = false;
}
if (highlightChannel.Contains(consoleIdentifier))
{
possibleHighlightButtonStyle = highlightStyle;
}
else
{
possibleHighlightButtonStyle = buttonStyle;
}
if (adminSystem.IsAdmin(dmpSettings.playerName))
{
if (GUILayout.Button("#" + consoleIdentifier, possibleHighlightButtonStyle))
{
if (highlightChannel.Contains(consoleIdentifier))
{
highlightChannel.Remove(consoleIdentifier);
}
selectedChannel = consoleIdentifier;
selectedPMChannel = null;
chatScrollPos.y = float.PositiveInfinity;
}
}
GUI.enabled = true;
}
private void DrawRooms()
{
GUIStyle possibleHighlightButtonStyle = buttonStyle;
if (selectedChannel == null && selectedPMChannel == null)
{
GUI.enabled = false;
}
if (highlightChannel.Contains(""))
{
possibleHighlightButtonStyle = highlightStyle;
}
else
{
possibleHighlightButtonStyle = buttonStyle;
}
if (GUILayout.Button("#Global", possibleHighlightButtonStyle))
{
if (highlightChannel.Contains(""))
{
highlightChannel.Remove("");
}
selectedChannel = null;
selectedPMChannel = null;
chatScrollPos.y = float.PositiveInfinity;
}
GUI.enabled = true;
foreach (string joinedChannel in joinedChannels)
{
if (highlightChannel.Contains(joinedChannel))
{
possibleHighlightButtonStyle = highlightStyle;
}
else
{
possibleHighlightButtonStyle = buttonStyle;
}
if (selectedChannel == joinedChannel)
{
GUI.enabled = false;
}
if (GUILayout.Button("#" + joinedChannel, possibleHighlightButtonStyle))
{
if (highlightChannel.Contains(joinedChannel))
{
highlightChannel.Remove(joinedChannel);
}
selectedChannel = joinedChannel;
selectedPMChannel = null;
chatScrollPos.y = float.PositiveInfinity;
}
GUI.enabled = true;
}
foreach (string joinedPlayer in joinedPMChannels)
{
if (highlightPM.Contains(joinedPlayer))
{
possibleHighlightButtonStyle = highlightStyle;
}
else
{
possibleHighlightButtonStyle = buttonStyle;
}
if (selectedPMChannel == joinedPlayer)
{
GUI.enabled = false;
}
if (GUILayout.Button("@" + joinedPlayer, possibleHighlightButtonStyle))
{
if (highlightPM.Contains(joinedPlayer))
{
highlightPM.Remove(joinedPlayer);
}
selectedChannel = null;
selectedPMChannel = joinedPlayer;
chatScrollPos.y = float.PositiveInfinity;
}
GUI.enabled = true;
}
}
public void Stop()
{
workerEnabled = false;
RemoveWindowLock();
dmpGame.updateEvent.Remove(updateAction);
dmpGame.drawEvent.Remove(drawAction);
if (chatLocked)
{
chatLocked = false;
InputLockManager.RemoveControlLock(DMP_CHAT_LOCK);
}
}
private void CheckWindowLock()
{
if (!dmpGame.running)
{
RemoveWindowLock();
return;
}
if (HighLogic.LoadedSceneIsFlight)
{
RemoveWindowLock();
return;
}
if (safeDisplay)
{
Vector2 mousePos = Input.mousePosition;
mousePos.y = Screen.height - mousePos.y;
bool shouldLock = windowRect.Contains(mousePos);
if (shouldLock && !isWindowLocked)
{
InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, DMP_CHAT_WINDOW_LOCK);
isWindowLocked = true;
}
if (!shouldLock && isWindowLocked)
{
RemoveWindowLock();
}
}
if (!safeDisplay && isWindowLocked)
{
RemoveWindowLock();
}
}
private void RemoveWindowLock()
{
if (isWindowLocked)
{
isWindowLocked = false;
InputLockManager.RemoveControlLock(DMP_CHAT_WINDOW_LOCK);
}
}
private class ChatCommand : IComparable
{
public string name;
public Action<string> func;
public string description;
public ChatCommand(string name, Action<string> func, string description)
{
this.name = name;
this.func = func;
this.description = description;
}
public int CompareTo(object obj)
{
var cmd = obj as ChatCommand;
return string.Compare(name, cmd.name, StringComparison.Ordinal);
}
}
}
public class ChannelEntry
{
public string fromPlayer;
public string channel;
public string message;
}
public class PrivateEntry
{
public string fromPlayer;
public string toPlayer;
public string message;
}
public class JoinLeaveMessage
{
public string fromPlayer;
public string channel;
}
public class ConsoleEntry
{
public string message;
}
}
| |
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 YumSale.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");
}
var controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = api.ActionDescriptor.ActionName;
var parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
var 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))
{
var sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (var mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
var 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 (var 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)
{
var controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = api.ActionDescriptor.ActionName;
var 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
var 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:
var 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;
var reader = new StreamReader(ms);
var 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)
{
var 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
var 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
{
var 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
{
var 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)
{
var parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
var 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)
{
var stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.